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

Try:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

The output will be:

1,234,545,454.00
查看更多
人气声优
3楼-- · 2018-12-31 03:23

Use PHP number_format() function.

查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 03:24

You can use number_format():

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

Example:

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

This function returns a string.

查看更多
公子世无双
5楼-- · 2018-12-31 03:25

Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
查看更多
骚的不知所云
6楼-- · 2018-12-31 03:28

You can use php printf or sprintf functions:

example with sprintf:

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

You can run same without echo as well, ex: sprintf("%.3f",$num);

output:

2.120

Alternatively, with printf:

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

output:

2.124 
查看更多
不流泪的眼
7楼-- · 2018-12-31 03:29

If you want to use 2 decimal digit in your entire project you can define

bcscale(2);

Then the following function will produce your desired result

$myvalue=10.165445;
echo bcadd(0,$myvalue);
//result=10.11

But if you don't use bcscale function you need to write the code as follow to get your desire result

  $myvalue=10.165445;
  echo bcadd(0,$myvalue,2);
 //result=10.11

To know more

查看更多
登录 后发表回答