0
dump($available_funds);
dump($meal_price);

if ($available_funds < $meal_price) {
    dd('hit');
    return false;
}

$available_funds and $meal_price are both 'double' values set to 2.78

Why would the if statement be hit when the values are the same?

I have attempted to (float) the variables and floatval() to try and update the types to see if this would resolve the condition but had no luck.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
lky
  • 1,081
  • 3
  • 15
  • 31
  • 1
    Could you create a [mre] that we can run ourselves? Include code that initializes both variables to values that fail, and show us the output of `dump` that you're seeing. – John Kugelman Dec 09 '22 at 14:44
  • Can't reproduce: https://3v4l.org/8BvUN – Jared Farrish Dec 09 '22 at 14:47
  • Are you sure they are the same value? 2.78 is not exactly representable as a float. – Andrew Dec 09 '22 at 16:10
  • The closest exactly representable 64bit float value to 2.78 is 2.779999999999999804600747665972448885440826416015625. Many other exactly representable 64bit float values round to 2.78 – Andrew Dec 09 '22 at 16:24

1 Answers1

2

The problem may be due to the precision of the double data type. double values can have up to 15 decimal digits of precision, but in some cases, the actual value stored may not have the same precision as the declared type. This can cause problems when comparing double values, as the values may not be exactly equal even if they appear to be the same.

One solution to this problem is to use the round() function to round the values to a specific number of decimal places before comparing them. For example, you could use the following code to compare the values with two decimal places of precision:

$available_funds = round($available_funds, 2);
$meal_price = round($meal_price, 2);

if ($available_funds < $meal_price) {
    dd('hit');
    return false;
}
Rijad Husic
  • 317
  • 3
  • 13
  • Check this out in python: print("%6.6f\n" % (2.779999999999999804600747665972448885440826416015625)) ==> 2.780000; print("%6.6f\n" % (2.779999999999999804600747665972448885440826416015625 - 1/2\*\*22.0)) ==> 2.780000; print("%6.6f\n" % (2.779999999999999804600747665972448885440826416015625 + 1/2\*\*22.0)) ==> 2.780000 – Andrew Dec 09 '22 at 20:13