Friday, September 23, 2011

Comparison of float values in PHP

That surprise is not pleasant at all. Especially if you work with money.
<?php
  $a = 0.1 + 0.7;
  $b = 0.8;
  var_dump($a, $b, $a == $b); 

// float(0.8) float(0.8) bool(false) 
?>
To avoid this type of problems let's follow the advice of Richard Johnson, that was published in the April 2013 issue of Web & PHP magazine:
"Be sure you are using ints and working in the smallest non-divisible monetary value (cents or pence). Alternatively make use of the BC or GMP maths functions which can also be useful if you need to do precise decimal operations."