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
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...

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.