phpcomparefloating-accuracy

Is there any way to compare float numbers correctly in PHP?


In PHP, I was willing to compare float numbers after some operations, but it doesn't show properly. For example:

$a = 0.2;
if ( ($a - 0.2) === 0 )
    return true;
else
    return false;

It returns false. Even I tried epsilon constant, but sometimes it's incorrect. Does anyone know how to resolve this?


Solution

  • Use this method:

    $a = 0.2;
    if ( abs($a - 0.2) < 0.00001 )
        return true;
    else
        return false;