PHP字符串四舍五入到小数点后两位的正确方法是什么?

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应该是520.00;

round_to_2dp()函数应该如何定义?


当前回答

$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

它将返回5.98而不是四舍五入的数字。

其他回答

使用round(yourValue,decimalPoint) (php手册的页面)或number_format(yourValue,decimalPoint);

Number_format()返回类似12344.67类型的字符串。所以在这种情况下,你不能用它来做加法或任何计算。如果你尝试,那么你必须处理数字格式错误…

在这种情况下,轮(121222.299000000,2)将是更好的选择。 结果是121222.29…

添加到其他答案,因为默认情况下,number_format()将添加数千分隔符。

要删除它,请执行以下操作:

$number = number_format($number, 2, ".", "");

http://php.net/manual/en/function.round.php

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

它将返回5.98而不是四舍五入的数字。

使用PHP number_format()函数。