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. 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.
Is there a consistent way to have PHP round a number like this correctly? 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).
So is there a solution that I can use to get a consistently correct rounded number with PHP?