Extra decimal places?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Extra decimal places?

Post 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.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Extra decimal places?

Post 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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Extra decimal places?

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