Show a number to 2 decimal places

2018-12-31 02:48发布

What's the correct way to round a PHP string to 2 decimal places?

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

$formatted_number = round_to_2dp($number);

echo $formatted_number;

The output should be 520.00;

How should the round_to_2dp() function definition be?

20条回答
残风、尘缘若梦
2楼-- · 2018-12-31 03:37

http://php.net/manual/en/function.round.php

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06
查看更多
君临天下
3楼-- · 2018-12-31 03:40
$twoDecNum = sprintf('%0.2f', round($number, 2));

The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.

查看更多
登录 后发表回答