| 0 comments ]

Can we compare equality of two floats in php ?

The answer is NO. Its not encouraged in php programming. The reason is, its related to system confugurations. We can not trust these values, it may vary in different systems. Consider this example


if( 0.111 + 0.222 == 0.333 ){
 echo 'a and b are same';
}
else {
 echo 'a and b are not same';
} 


Here the value 0.333 is A literal but a float(calculated sum) using to compare it. So it may result some variations in the result. some times it will show the 'true' part, sometime it will show the 'false' part.
You can see its more explantions on php.net
here are the links

http://php.net/manual/en/language.operators.comparison.php 
http://in.php.net/float 

 To overcome this, we can use the precition checking


  function floatCheck($x,$y,$precision=0.0000001) 
    { 
        return ($x+$precision >= $y) && ($x-$precision <= $y); 
    }

floatCheck(1.0002541,1.0002540,$precision=0.0000002);