PHP 尽管输入正确,但值比较错误

PHP value comparison wrong despite correct typing

这段代码:

$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'];
   }

给我这个输出:

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

为什么?这怎么可能?

我确保所有比较的值都是 float 类型的,所以没有字符串可以滑入。

我一定是漏了什么。

很抱歉没有提供真正可重现的代码,但我不知道在这种情况下如何。

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.

我认为其他人也遇到了完全相同的问题。