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:30

Use PHP number_format() function. e.g.

$num = 7234545423; 
echo number_format($num, 2); 

The output will be:

7,234,545,423.00

查看更多
孤独总比滥情好
3楼-- · 2018-12-31 03:30
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

This will give you 2 number after decimal.

查看更多
君临天下
4楼-- · 2018-12-31 03:32

Number without round

$double = '21.188624';
echo intval($double).'.'.substr(end(explode('.',$double)),0,2);
查看更多
怪性笑人.
5楼-- · 2018-12-31 03:33

Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.

$formatted_number = bcadd($number, 0, 2);
查看更多
孤独总比滥情好
6楼-- · 2018-12-31 03:35

round_to_2dp is an user defined function, nothing can be done unless you posted the declaration of that function

However, my guess is doing this number_format($number,2);

查看更多
荒废的爱情
7楼-- · 2018-12-31 03:36
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

It will return 5.98 without rounding the number.

查看更多
登录 后发表回答