I have this code that is returning incorrect value.
The result is ‘7 price3’ but it is wrong. 7 should fall on second if statement since $value is greater than 5 and less than or equal to 7. You can try on your php editor and it will return on the third if statement.
$price = 100;
$requestprice = 93;
$value = (($price - $requestprice) / $price) * 100;
if ($value <= 5) {
echo $value . ' price 1';
} else if ($value > 5 && $value <= 7) {
echo $value . ' price 2';
} else if ($value > 7 && $value <= 10) {
echo $value . ' price 3';
}
Tried to run the code on any php editor and still got the wrong result
2
Answers
It’s because of floating point imprecision. The actual value of
$value
isn’t just7
, it’s7.00000000000000088818
. You can see that if you add the following line just after$value = (($price - $requestprice) / $price) * 100;
:Since
7.00000000000000088818
is greater than7
, the code is taking the right branch.$value
is a float value, convert it to an integer for accurate comparisons. Also, you don’t need repeated comparisons. See alsoOnline Demo