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

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

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应该是520.00;

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


当前回答

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

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

其他回答

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

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

你可以使用number_format():

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

例子:

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

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

$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

小数点后会有2个数。

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

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

使用PHP number_format()函数。