Thursday 21 March 2013

Floating away...

In many languages, a true `float`/`long` value is not what the visual representation is, i.e. there may be many decimal places not displayed.
In PHP, this will be your saviour!
function float_cmp($float1, $float2, $abs = true)
{
 if ($float1 == $float2)
 {
  return true;
 }

    $error_tolerance = ($abs) ? 0.00001 : 0.001;
 
    if (abs($float1 - $float2) < $error_tolerance)
 {
  return true;
 }

 return false;
}