PHP to round up to the 2nd decimal place

自闭症网瘾萝莉.ら 提交于 2020-05-08 17:33:03

问题


By calculating areas I have a number which I need to display in a strange way.

Always display 2 decimal places. Always round up the 2nd decimal place if the 3rd+ decimal places > 0.

Examples:

0.5 = 0.50
0.500003 = 0.51
0.96531 = 0.97
0.96231 = 0.97
0.8701 = 0.88

Is there a built in function to do this in PHP or do I need to write one?


回答1:


You can use 2 functions:

  • round() - docs here: http://www.php.net/manual/en/function.round.php
  • number_format() - docs here: http://ro1.php.net/number_format

I've used both with success, and depending on what you're doing with the result, you may chose either of the above functions.

Later edit: If you want to only round up, you can use ceil() - http://www.php.net/manual/en/function.ceil.php + number format or round

echo round(ceil($number*100)/100,2);

As another user suggested earlier




回答2:


To always round up you will want to use something like this:

$number = 0.8701;

echo ceil($number*100)/100;

// = 0.88


来源:https://stackoverflow.com/questions/22991021/php-to-round-up-to-the-2nd-decimal-place

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!