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

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

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应该是520.00;

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


当前回答

$twoDecNum = sprintf('%0.2f', round($number, 2));

四舍五入可以正确地将数字四舍五入,如果四舍五入后恰好只有1位小数,则sprintf会强制将其四舍五入到小数点后2位。

其他回答

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

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

另外,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point

这将显示小数点后的两位数字。

优势:

如果你只想在浮点值后显示两个数字,而不是int,那么使用这个。

如果你像我一样使用数学方程,你可以这样设置:

{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}

你可以使用number_format():

return number_format((float)$number, 2, '.', '');

例子:

$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00

这个函数返回一个字符串。