Page 1 of 1

Extra decimal places?

Posted: Wed Dec 29, 2010 10:09 am
by Celauran
So I've got a fairly straightforward application where I'm pulling customer's invoices from the database. Under a given set of circumstances, a discount is to be applied. So as I'm looping through the entries on the invoice, I've got something like this:

Code: Select all

...
$cost = round((($row['ccost'] * 0.95) + 0.0001), 2);
...
$grand_total += $cost
Given that $cost is always rounded to 2 decimal places, I would expect $grand_total to also be two decimal places. Occasionally, however, I end up with a mess of 8 or 9 decimal places. Rounding the grand total fixes it, but any idea what's causing this? Seems like strange behaviour.

Re: Extra decimal places?

Posted: Wed Dec 29, 2010 10:38 am
by Apollo
Has to do with the day floating point numbers are stored internally (more specifically: IEEE). Even with double precision (64-bit), even seemingly 'basic' numbers like 1/10 = 0.1 can't be represented exactly. You normally won't notice because the differences are insignificantly small, but occasionally you may notice this effect by results ending with .xxx999999 where you expected a rounded result.

Re: Extra decimal places?

Posted: Wed Dec 29, 2010 10:41 am
by Celauran
Precisely what's happening. Now that I've read your explanation, I do seem to recall having learned that at some point. Thanks for the refresher.