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

其他回答

你可以使用PHP printf或sprintf函数:

sprintf的示例:

$num = 2.12;
echo sprintf("%.3f", $num);

您也可以在没有echo的情况下运行相同的程序。例如:sprintf(“%。3 f”,num美元);

输出:

2.120

或者,使用printf:

echo printf("%.2f", $num);

输出:

2.124

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

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

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

bcdiv($number, 1, 2) // 2 varies for digits after the decimal point

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

优势:

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

下面是strtok和str_pad的另一个解决方案:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

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