I want to compare two floats in PHP, like in this sample code:
$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
echo \'a and b are same\';
}
else {
echo \'a
If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if $a
is a literal .17
and $b
arrives there through a calculation it can well be that they are different, albeit both display the same value.
Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:
if (abs(($a-$b)/$b) < 0.00001) {
echo "same";
}
Something like that.