简体   繁体   English

用PHP round()和14个十进制浮点数舍入不正确

[英]Improper rounding with PHP round() and a 14 decimal float

I have the age-old floating point rounding issue as many people before me have, but I can't seem to find a good solution for my situation. 我面临着很多人以前有的古老的浮点取整问题,但是我似乎找不到适合我的情况的好的解决方案。 I'm doing some math operations in MySQL and returning the result to PHP as a float, then using round() to round the result. 我正在MySQL中进行一些数学运算,并将结果以浮点数的形式返回给PHP,然后使用round()将结果取整。 The problem I'm running into is with numbers like 10.50499999999977 which seem to trip up round() , rounding the number to 10.5 instead of the expected 10.51 . 10.50499999999977的问题是像10.50499999999977这样的数字,它似乎10.50499999999977round() ,将数字四舍五入为10.5而不是预期的10.51

Is there a consistent way to have PHP round a number like this correctly? 是否有一致的方法可以使PHP正确地对这样的数字取整? I found a quick solution, but I'm afraid this wouldn't hold up in the long run: 我找到了一个快速解决方案,但恐怕长此以往不会成立:

echo round(10.50499999999977, 2, PHP_ROUND_HALF_UP); // 10.5
echo round(round(10.50499999999977, 5, PHP_ROUND_HALF_UP), 2); // 10.51

I'm especially worried that if I use this solution and try to round a number like 10.50444449 that this would end up rounding wrong (10.5 vs 10.51). 我特别担心,如果我使用此解决方案并尝试四舍五入到10.50444449类的10.50444449 ,最终将导致四舍五入错误(10.5对10.51)。

So is there a solution that I can use to get a consistently correct rounded number with PHP? 那么,有没有一种解决方案可以用来用PHP获得一致正确的舍入数呢?

You're seeing expected behavior: 您正在看到预期的行为:

php>  echo round(10.50499999999977);
11
php > echo round(10.50499999999977, 1);
10.5
php > echo round(10.50499999999977, 2);
10.5
php > echo round(10.50499999999977, 3);
10.505
php > echo round(10.50499999999977, 4);
10.505
php > echo round(10.50499999999977, 6);
10.505
php > echo round(10.50499999999977, 7);
10.505

As per the docs: 根据文档:

PHP_ROUND_HALF_UP Round val up to precision decimal places away from zero, when it is half way there. PHP_ROUND_HALF_UP val PHP_ROUND_HALF_UP到精确到小数点后PHP_ROUND_HALF_UP零处(零位的一半)。 Making 1.5 into 2 and -1.5 into -2. 将1.5设为2,并将-1.5设为-2。

...049999 isn't "half-way there". ... 049999不是“半途而废”。 it's below 0.5, so php rounds down. 它低于0.5,因此php向下取整。

round() is doing exactly what you're asking: round()完全按照您的要求进行:

echo round(10.50499999999977, 2, PHP_ROUND_HALF_UP); // 10.5

You're asking for rounding to two decimal places, rounding 'half' and above up. 您要四舍五入到小数点后两位,“一半”以上四舍五入。

Here the third decimal place and beyond is less than 'half' (0.00499999999777) so it's rounded down , giving 10.500. 在这里,小数点后第三位及以后不到“半壁江山”(0.00499999999777),所以它舍去 ,给人10.500。 The trailing zeroes are dropped as they have no significance. 尾随零将被删除,因为它们没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM