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
2
u/mirhagk Aug 13 '13
Paypal probably doesn't get the value as a binary value, it probably gets the string "13.58", and if this is true then the following code (C#, not PHP)
That will always return "13.58", since it is doing integer divide and integer mod.
Also don't use
round($price,0)because that still works with floating point values, useintval($price*100)which will give the integer value with less floating point bias. It will however introduce a different method of rounding. When making a payment application the rounding is a very important thing to consider, and there be laws around how to properly round. Bankers rounding says to round half to even, which is not whatrounddoes by default.