可能重复:
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
,这种情况发生在有或没有浮动......任何想法为什么?
答案 0 :(得分:2)
浮点运算从未如此准确。如果你需要比较为零,你需要采取不同的比较并将它与一些小数字进行比较。
if (abs($result) < 0.00001)) {
// it's zero
} else {
}
答案 1 :(得分:1)
因为漂浮。使用int
s并以美分(* 100)计算值。