PHP四舍五入到小数点后第二位 [英] PHP to round up to the 2nd decimal place
问题描述
通过计算面积,我得到了一个需要以一种奇怪的方式显示的数字.
By calculating areas I have a number which I need to display in a strange way.
始终显示 2 个小数位.如果第 3 个以上的小数位 > 0,则始终舍入第 2 个小数位.
Always display 2 decimal places. Always round up the 2nd decimal place if the 3rd+ decimal places > 0.
示例:
0.5 = 0.50
0.500003 = 0.51
0.96531 = 0.97
0.96231 = 0.97
0.8701 = 0.88
是否有内置函数可以在 PHP 中执行此操作,还是我需要编写一个函数?
Is there a built in function to do this in PHP or do I need to write one?
推荐答案
您可以使用 2 个功能:
You can use 2 functions:
- round() - 此处的文档:http://www.php.net/manual/en/function.round.php
- number_format() - 此处的文档: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.
后期如果你只想四舍五入,你可以使用 ceil() - http://www.php.net/manual/en/function.ceil.php + 数字格式或舍入
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
这篇关于PHP四舍五入到小数点后第二位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!