Improper rounding with PHP round() and a 14 decimal float -
i have age-old floating point rounding issue many people before me have, can't seem find solution situation. i'm doing math operations in mysql , returning result php float, using round()
round result. problem i'm running numbers 10.50499999999977
seem trip round()
, rounding number 10.5
instead of expected 10.51
.
is there consistent way have php round number correctly? found quick solution, i'm afraid wouldn't hold in 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 worried if use solution , try round number 10.50444449
end rounding wrong (10.5 vs 10.51).
so there solution can use consistently correct rounded number 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 docs:
php_round_half_up
round val precision decimal places away zero, when half way there. making 1.5 2 , -1.5 -2.
...049999 isn't "half-way there". it's below 0.5, php rounds down.
Comments
Post a Comment