0

Possible Duplicate:
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;

When I run the above in php, I get the following output:

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

But if you look at LHS, it should be 0, and this happens with or without float....any idea why?

Community
  • 1
  • 1
Bluemagica
  • 5,000
  • 12
  • 47
  • 73

2 Answers2

2

Floating point arithmetic is never that accurate. If you need to compare to zero, you need to take the different and compare it to some small number.

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

}
laurent
  • 88,262
  • 77
  • 290
  • 428
1

Because float. Use ints and calculate the value with cents (* 100).

CodeCaster
  • 147,647
  • 23
  • 218
  • 272