PHP - number_format issues

我的梦境 提交于 2019-12-08 08:54:12

问题


number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...

42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9

I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.

Any ideas?


回答1:


The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.

$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);



回答2:


If anyone's interested in this, I've written a little function to get around this problem.

With credit to Joel Hinz above, I came up with...

function number_format_with_decimals($value, $round_to){
    //$value is the decimal number you want to show with number_format.
    //$round_to is the deicimal place value you want to round to.

    $round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
    $ans = number_format($value, $round_to);

    return $ans;
}



回答3:


I tried these solutions, but what ended up being my answer was this:

$output=money_format('%!i', $value);

This gives you something like 3,234.90 instead of 3,234 or 3,234.9



来源:https://stackoverflow.com/questions/19071112/php-number-format-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!