Jump to content

Math bug or user error?


fooDigi

Recommended Posts

Can someone tell me why i get this absurd number when doing simply addition and subtraction? thx

 

$charge_amount = 34.55;
$amount_paid = 179.99;
$order_total = 214.54;

// returns 2.84217094304E-14 ... should be zero
echo $charge_amount + $amount_paid - $order_total;

Link to comment
https://forums.phpfreaks.com/topic/182924-math-bug-or-user-error/
Share on other sites

k, so even though when i print the sum of $charge_amount and $amount_paid, it returns 214.54, and $order_total is 214.54, their internal values may not be as exact?? confusing, what would be the best and most accurate way to avoid this?

 

changing it to the following worked, but not sure if it is best...

echo round($charge_amount + $amount_paid,2) - $order_total;

 

also, i have been running this code for some time, and this is the first time this issue has arose...

Depends what you math is for.

 

Simply use round or number_format to control the number of decimal place if you just want to echo the result.

If these are monetary values, then it's always a lot better to hold the values as an integer number of cents/pennies rather than a float dollars/pounds: doing all of your math using integers won't give any rounding errors.

Use the bc math functions, as the Warning message suggests

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.