Floating point comparisons or why prices need to be stored in cents

Posted by Stanislav Furman  on September 5, 2013

In PHP you should be careful working with floating point number comparisons because sometimes the result that you get can be unexpected and unpredictable even if it looks pretty obvious. Here is an example. Can you guess what will be the result?

<?php
$a = 0.7;
$b = 0.1;
$c = $a + $b;
if ($c == 0.8) {
   echo '$c == 0.8';
} else {
   echo '$c!=0.8';
}

Even if it's obvious that the correct option is $c == 0.8', the answer is "$c!=0.8'". It happens because depending on the system floating point numbers have limited precision and can be handled differently (see this).

This is why I'd recommend for those who work with prices to operate with prices in cents (i.e. use 999 instead of 9.99).

However, if you need to compare numbers with floating point use rounding. For example this will work as expected:

<?php
$a = 0.7;
$b = 0.1;
$c = round($a + $b, 1);
if ($c == 0.8) {
   echo '$c == 0.8';
} else {
   echo '$c!=0.8';
}

Update:: I also recommend to read about loose comparison in PHP based on example with switch/case operator. This example will give you an idea about how loose comparison can break the logic in your PHP application.


Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.