Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

laravel - number_format() behavior is not as expected in php

i have make helper function for getting value by using number_formate()

 function getRatePrecision($rate)
    {
        return number_format((float)$rate, (int)getSingleOrganisationSetting('default_rates_percision'));
    }

I am passing value to this function to use number_format() there is another function getSingleOrganisationSetting('default_rates_percision') which is getting value from database which I need after . for example if it is 24.8888 it will convert it to 24.9 . But weirdly it is converting. it is converting 10687 to 10 which doesn't make sense. obviously this is error from my end but I can't figure it out why.

question from:https://stackoverflow.com/questions/65950254/number-format-behavior-is-not-as-expected-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With php round function it will make it simpler

round — Rounds a float

round ( float $val , int $precision = 0 , int $mode = PHP_ROUND_HALF_UP ) : float

Example: Round 24.8888 to 24.9 with 1 precision

round(24.8888, 1); // 24.9

With str_replace replace ',' to '.' and floatval evaluate the string value to float. Because round function need only a float param in first argument. And the function should be like this one

function getRatePrecision($rate)
{
   return round(floatval(str_replace(',', '.', $rate)), 1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...