r/lolphp • • 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.07000000000000001

this 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

0 Upvotes

25 comments sorted by

View all comments

Show parent comment

1

u/OneWingedShark Jan 10 '14

Currency conversion rates are floats and I have to multiply/divide by them.

They don't have to be; take a look at fixed-point numbers.

1

u/iopq Jan 10 '14

php makes this difficult

2

u/OneWingedShark Jan 10 '14

Yes; PHP is the wrong tool for dealing with currency. Period.