php中如何四舍五入到最接近的有效数字
php 有没有什么巧妙的方法可以四舍五入到最接近的有效数字?
所以:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
Is there any slick way to round down to the nearest significant figure in php?
So:
0->0
9->9
10->10
17->10
77->70
114->100
745->700
1200->1000
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不幸的是,当 $number 为 0 时,这会严重失败,但它确实会产生正整数的预期结果。这是一个纯数学解决方案。
Unfortunately this fails horribly when $number is 0, but it does produce the expected result for positive integers. And it is a math-only solution.
这是一个纯数学解决方案。如果您想要向上或向下舍入,而不仅仅是向下舍入,这也是一个更灵活的解决方案。它适用于 0 :)
您可以将
floor
替换为round
或ceil
。实际上,如果您想四舍五入到最接近的值,您可以进一步简化第三行。Here's a pure math solution. This is also a more flexible solution if you ever wanted to round up or down, and not just down. And it works on 0 :)
You could replace
floor
withround
orceil
. Actually, if you wanted to round to the nearest, you could simplify the third line even more.如果您确实想要一个数学解决方案,请尝试以下操作:
If you do want to have a mathy solution, try this:
像这样的事情:
Something like this:
这完全不是数学问题,但我只是利用刺痛长度来做到这一点......可能有一种更平滑的方法来处理它,但你可以用以下方法完成它
It's totally non-mathy, but I would just do this utilizing sting length... there's probably a smoother way to handle it but you could acomplish it with
基于数学的替代方案:
A math based alternative:
我知道这是一个旧线程,但我在寻找如何解决这个问题的灵感时阅读了它。这是我想出的:
I know this is an old thread but I read it when looking for inspiration on how to solve this problem. Here's what I came up with:
虽然这里的函数有效,但我需要非常小的数字的有效数字(将低价值的加密货币与比特币进行比较)。
在 PHP 中将数字格式化为 N 个有效数字 的答案有效,在某种程度上,尽管 PHP 以科学记数法显示非常小的数字,这使得某些人难以阅读。
我尝试使用 number_format,尽管这需要小数点后的特定位数,这破坏了数字的“有效”部分(如果输入了一组数字),有时返回 0(对于数字小于设定数)。
解决方案是修改该函数以识别非常小的数字,然后对其使用 number_format - 将科学记数法位数作为 number_format 的位数:
该函数保留有效数字并以易于理解的方式呈现数字- 适合所有人阅读的格式。 对于科学家来说不是最好的,甚至不是长度最一致的“漂亮”数字,但总的来说,它是满足我们需要的最佳解决方案。)
(我知道,这 net/OA0VL.png" rel="nofollow noreferrer">
While the functions here worked, I needed significant digits for very small numbers (comparing low-value cryptocurrency to bitcoin).
The answer at Format number to N significant digits in PHP worked, somewhat, though very small numbers are displayed by PHP in scientific notation, which makes them hard for some people to read.
I tried using number_format, though that needs a specific number of digits after the decimal, which broke the 'significant' part of the number (if a set number is entered) and sometimes returned 0 (for numbers smaller than the set number).
The solution was to modify the function to identify really small numbers and then use number_format on them - taking the number of scientific notation digits as the number of digits for number_format:
This function retains the significant digits as well as presents the numbers in easy-to-read format for everyone. (I know, it is not the best for scientific people nor even the most consistently length 'pretty' looking numbers, but it is overall the best solution for what we needed.)