如何确保 PHP 中的浮点数始终四舍五入?
我想确保 PHP 中的浮点数在存在任何小数的情况下进行四舍五入,而不用担心数学舍入规则。该函数的工作原理如下:
1.1 to 2
1.2 to 2
1.9 to 2
2.3 to 3
2.8 to 3
我知道 round() 函数存在,但我没有看到任何在找到任何小数时进行四舍五入的函数。有什么简单的方法可以做到这一点吗?
I want to make sure a float in PHP is rounded up if any decimal is present, without worrying about mathematical rounding rules. This function would work as follows:
1.1 to 2
1.2 to 2
1.9 to 2
2.3 to 3
2.8 to 3
I know the round()
function exists but I don't see any function for rounding up if any decimal is found. Is there any easy way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
ceil
函数:Use the
ceil
function:我知道这是一个老话题,但它出现在谷歌中。我将扩展布莱克·普拉姆关于精度的回答。
乘以 100 和除以 100 只能计算百分之一。这在十分之一、千分之一、万分之一等方面并不准确。
结果:
注释:
感谢 Joseph McDermott 和 Brandom 的贡献,改进了我的原始数据片段。
I know this is an old topic, however it appears in Google. I will extend Blake Plumb's answer regarding precision.
Multiplying by 100 and dividing by 100 only works with one-hundredths. This isn't accurate on tenths, one-thousandths, one-hundred thousandths, etc.
Results:
Notes:
Thanks for the contributions from Joseph McDermott and brandom for improving my original snippet.
官方的 Ceil 函数将为您完成此操作。
摘自示例:
The official Ceil function will do that for you.
Taken from the example:
我知道这个问题早已得到解答,但当我对这个主题进行谷歌搜索时,它就出现了。如果您想精确舍入,那么一个好的方法是使用 ceil 函数,将数字乘以您想要表示的小数点位数,然后除以该数字。
将产生 1024.33
I know this question has long since been answered, but it came up when I did a google search on the topic. If you want to round up with precision, then a good method would be to use the ceil function and times the number by how many decimal points you want to represent and then divide by that number.
would produce 1024.33
我喜欢 Ash 的回应,尽管我会这样:
如果我提供精度“2”,我希望它四舍五入到小数点后两位,这是有道理的。不过我想这只是选择的问题。感谢阿什的回答,效果很好。
I like Ash's response, although I would have:
Makes sense that if I provide precision '2', I would expect it rounded to 2 decimal places. Matter of choice though I suppose. Thanks for the answer Ash, works well.