PHP字符串四舍五入到小数点后两位的正确方法是什么?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
输出应该是520.00;
round_to_2dp()函数应该如何定义?
PHP字符串四舍五入到小数点后两位的正确方法是什么?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
输出应该是520.00;
round_to_2dp()函数应该如何定义?
当前回答
无整数
$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
其他回答
Try:
$number = 1234545454;
echo $english_format_number = number_format($number, 2);
输出将是:
1,234,545,454.00
http://php.net/manual/en/function.round.php
e.g.
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
无整数
$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
我自己做。
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
使用PHP number_format()函数。