0

In php I was comparing if 2 quantities are equal or not with if statement. Can anyone explain why these 2 numbers are not equal according to php?

DEMO

$new_q = 8.345;
$remain_q = 0.075;
$actual_q = $remain_q + 8.270;

if( $new_q !== $actual_q ){
    $output['new_q'] = number_format($new_q,20,",",".");
    $output['actual_q'] = number_format($actual_q,20,",",".");
    print_r($output);
} else {
    echo "Numbers are equal";
}
  • As the demo clearly shows, one of the numbers is `8,34500000000000063949`, the other is `8,34499999999999886313`. Trivially, from observation, those are not the same. There's a rounding difference. – ADyson Jul 20 '22 at 12:35
  • do manual math, $new_q is 8.345 and $actual_q is also 8.345. I am not rounding any numbers here. Check if statement, raw numbers are there, not rounded. So, php fails to compare raw $new_q and $actual_q. – DrWalt Bishop Jul 20 '22 at 12:39
  • 1
    You're not rounding anything, but your computer is. Read the duplicate :-) – ADyson Jul 20 '22 at 12:42
  • 1
    P.S. we can dump the numeric values instead of the strings: https://3v4l.org/DgAiS#v5.6.40 (n.b. var_dump is always a better option than print_r, you get more detail and more accuracy). They look equal. However you're using a very old, unsupported version of PHP. If we update to the latest version, they've improved the output handling, and now you see the root cause more easily: https://3v4l.org/DgAiS#v8.1.8 – ADyson Jul 20 '22 at 12:44
  • yes i read, there are many technical terms and explanations which i found where difficult to understand. So, as a simple solution I will compare round($new_q, 3) with round($actual_q, 3). But I still think there should be one single standard for these decimal comparisons. – DrWalt Bishop Jul 20 '22 at 12:46
  • 1
    If you don't fully understand the explanations or the mathematics behind them then just pay attention to the last part of the accepted answer which explains ways to work around it. As you say, applying rounding first is one of the ways. – ADyson Jul 20 '22 at 12:48
  • @DrWaltBishop ... been looking forward to a single standard myself since 1968 ... – YvesLeBorg Jul 20 '22 at 12:48
  • 2
    There _is_ a standard - it's mentioned in the accepted answer, right at the start (IEEE754). The issue is it's perhaps a little bit flawed, due to the way it represents the numbers. However, as it goes onto explain, most numbering systems (even without involving computers) suffer from some sort of representation issue in certain situations. – ADyson Jul 20 '22 at 12:49

0 Answers0