Skip to content
Advertisement

PHP round() bug with round(908.5449, 2, PHP_ROUND_HALF_UP) = 908.54?

I am currently investing a rounding problem in PHP. I’ve tested it here https://3v4l.org/NpRPp and it seems to be the same, since ever.

But is this correct behaviour? Because i expected the following.

echo round(908.5449, 2, PHP_ROUND_HALF_UP); // should be 908.55, but returns actually 908.54

Can someone tell if this behaviour is intended, and if so, how to solve it properly for every possible floating point number?

Edit: Thanks to the answers, this behaviour is correct but i expected the wrong result. My original number in the program was 908.55 which somewhere in the chain of the program became 908.5449999999994 due to storage in DB and floating point precision issues. So i wanted it to be 908.55 again, which does not work with regular use of round().

Advertisement

Answer

This is working correctly. The output of

echo round(908.5449, 2, PHP_ROUND_HALF_UP);

Should be 908.54. You’re rounding to two decimals, so the remainder, that is rounded off is 0.0049. This is less than 0.005, which would be half, so it is rounded down.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement