Friday, June 26, 2009

PHP rounding errors

What's 2.3 * 100 - 230?

You'd expect 0, right?

Well, not so much in PHP.

PHP seems to have troubles with floating point math, even in the simplest of circumstances.

Take the following snippet of code

$r = 2.3;
echo $r.PHP_EOL;
$r = $r * 100.0;
echo $r.PHP_EOL;
echo ($r - 230).PHP_EOL;

Instead of 0 for the last echo, you get -2.8421709430404E-14.

And setting precision via ini_set() isnt going to help either. By default, precision is set to 14. Setting it to 2 will result in -2.8E-14.

To avoid rounding errors in PHP, especially when doing financial calculations that should be limited to 2 decimal places, you should round() every floating point operation with a precision of 2. Most of the time, the calculations will appear normal, but on the off chance that the value to the left of the decimal point is 0, what appears on the right might not be what you expect.

Just for clarity, I'm running PHP 5.2.8, though will be doing an upgrade to 5.2.10 in the near future.

No comments: