简体   繁体   English

PHP-number_format问题

[英]PHP - number_format issues

number_format stupidly rounds numbers by default. 默认情况下, number_format 愚蠢地四舍五入数字。 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 * .003 = 127.599或,
42533 * .03 = 1275.99 or, 42533 * .03 = 1275.99或,
42533 * .3 = 12759.9 42533 * .3 = 12759.9

I need number_format (or something else) to express the result in traditional US format (with a comma separating the thousands) and not round the decimal. 我需要用number_format(或其他格式)以传统的美国格式(用逗号分隔千位)来表示结果,而不是四舍五入。

Any ideas? 有任何想法吗?

The second argument of number_format is the number of decimals in the number. number_format的第二个参数是数字中的小数位数。 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);

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... 归功于以上的Joel Hinz,我想出了...

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;
}

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 这使您像3,234.90而不是3,234或3,234.9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM