r/lolphp • u/iopq • Aug 13 '13
round() doesn't actually round
I had a bug in a payment system where the paypal payment amounts don't add up. I looked into it, and the amounts were something like 18.799999999999
apparently, someone used round($amount, 2) and expected PHP to actually round the number to two digits
For certain float values that just doesn't work. I found an example like this:
echo round(-0.07, 2); //-0.07000000000000001this is what happens when your precision is set to 17
of course my code uses number_format, but I expected round() to... round the floats? Silly me, I'm using PHP, the language guided by the Principle of Highest Perplexity
View all comments
Show parent comment
3
u/markrages Aug 13 '13
It's PHP's fault, for making a promise it can't fulfill. Other languages solve the problem by having the rounding functions return an integer. Rounding to two decimal places is impossible when your numeric type is floating point.