-1

I am getting wrong result while adding float numbers, pls tell me how you programmer are escaping from this

Code:

 $tot = 0;
    $ans = (float)101;
    for($i=1; $i<= 10; $i++){
        $tot = $tot + 10.1;
    }
    var_dump($tot);
    var_dump($ans);
    if($tot == $ans){
        echo '<br />Both are equal ';
    }
    else{
        echo '<br />Both are not equal ';
    }

Result:

float 101

float 101

Both are not equal

shanavas
  • 1
  • 2

2 Answers2

1

This problem is inherited from C language.

There will be a small difference while comparing floating values,

See this, ans this

try this,

if (abs(($tot-$ans)/$tot) < 0.00001) {
    echo '<br />Both are equal ';
}
else{
    echo '<br />Both are not equal ';
}
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

Try with '===' , '==' compares the variable references and '===' compares the value

if($tot === $ans){
    echo '<br />Both are equal ';
}
else{
    echo '<br />Both are not equal ';
}
AndresJ
  • 51
  • 5