-1

This piece of code:

$total=$o->cart->getTotalSum();
$subTotal=$o->cart->getSubTotal();

if(floatval($r['sum_total']) != floatval($total) ||
   floatval($r['sum_sub']) != floatval($subTotal)) {
      echo 'Differs on #' . $r['id'];
      echo 'Total: ' . $total . ' / ' . $r['sum_total'];
      echo 'Sub: ' . $subTotal . ' / ' . $r['sum_sub'];
   }

Gives me this output:

Differs on #697
Total: 19.6 / 19.6
Sub: 19.6 / 19.6

Why? How is that even possible?

I make sure that all values compared are of type float, so no strings could have slipped in.

I must be missing something.

My apologies for not providing really reproducible code, but i wouldn't know how in this case.

SquareCat
  • 5,699
  • 9
  • 41
  • 75

1 Answers1

0

If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if $a is a literal .17 and $b arrives there through a calculation it can well be that they are different, albeit both display the same value.

Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:

if (abs(($a-$b)/$b) < 0.00001) { echo "same"; } Something like that.

I think someone else had the exact same problem.

https://stackoverflow.com/a/3148991/2725502

ImAtWar
  • 1,073
  • 3
  • 11
  • 23
  • Vote to close as duplicate, don't copy answers. – deceze Mar 30 '18 at 09:32
  • Thank you for pointing me to that question, i was unable to find it an appropriate one for my problem while searching. Please remove your answer so i can delete my question. It's useless in the network given the circumstances – SquareCat Mar 30 '18 at 09:34