【问题标题】:Weird calculation in PHP [duplicate]PHP中的奇怪计算[重复]
【发布时间】:2012-07-03 09:38:03
【问题描述】:

可能重复:
Is JavaScript's Math broken?
Adding fractions number yields different result in PHP

$grand_total =  (float)$subtotal_email +  (float)$delivery_email + (float)$fuel_surcharge_email - (float)$discount_coupon_email + (float)$texas_tax_email - (float)$cancel_fee_email -  (float)$refund_email - (float)$refund_tax_email - (float)$coupon_tmp;
echo (float)$subtotal_email." +  ".(float)$delivery_email." + ".(float)$fuel_surcharge_email." - ".(float)$discount_coupon_email." + ".(float)$texas_tax_email." - ".(float)$cancel_fee_email." -  ".(float)$refund_email." - ".(float)$refund_tax_email." - ".(float)$coupon_tmp." = ".(float)$grand_total;

当我在 php 中运行上述内容时,我得到以下输出:

89.99 + 0 + 16.2 - 0 + 8.61 - 3 - 100 - 10 - 1.8 = -2.88657986403E-15

但是,如果您查看 LHS,它应该是 0,无论有没有浮点数都会发生这种情况......知道为什么吗?

【问题讨论】:

标签: php


【解决方案1】:

浮点运算永远不会那么准确。如果您需要与零进行比较,则需要取不同并将其与某个较小的数字进行比较。

if (abs($result) < 0.00001)) {
    // it's zero
} else {

}

【讨论】:

    【解决方案2】:

    因为浮动。使用ints 并用美分(* 100)计算值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多