skip to Main Content

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


  1. It’s because of floating point imprecision. The actual value of $value isn’t just 7, it’s 7.00000000000000088818. You can see that if you add the following line just after $value = (($price - $requestprice) / $price) * 100;:

    printf("%.20f", $value);
    

    Since 7.00000000000000088818 is greater than 7, the code is taking the right branch.

    Login or Signup to reply.
  2. $value is a float value, convert it to an integer for accurate comparisons. Also, you don’t need repeated comparisons. See also

    <?php
    
    $price = 100;
    $requestprice = 93;
    
    $value = intval((($price - $requestprice) / $price) * 100);
    
    if ($value <= 5) {
        echo $value . ' price 1';
    } else if ($value <= 7) {
        echo $value . ' price 2';
    } else if ($value <= 10) {// or skip this if condition
        echo $value . ' price 3';
    }
    

    Online Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search