小编典典

显示一个数字到小数点后两位

php

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

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

$formatted_number = round_to_2dp($number);

echo $formatted_number;

输出应该是520.00;

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


阅读 375

收藏
2020-05-26

共1个答案

小编典典

您可以使用number_format():

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

例:

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

该函数返回一个 字符串

2020-05-26