SPUG: Incorrect subtraction result

Mike Schuh schuh at farmdale.com
Tue Aug 26 02:50:43 PDT 2008


On Tue, 26 Aug 2008, Christopher Howard wrote:

>I was hoping someone might help me figure what is wrong with
>some code I wrote.

The quick and simple answer is "don't use floating point numbers to
represent money".  Currency transactions need to track pennies as though
they were integers, not 0.01.

Why not use floating point values?  What is the binary representation of
0.01?  Well, it can't be exactly described in binary, so there will always
be some sort of round off error when adding and subtracting pennies.

Solutions: Use integer pennies, dividing by 100 when displaying the values
as dollars (and use the integer pragma).  There are also binary coded
decimal techniques.

Good luck!

--
Mike Schuh - Seattle, Washington USA
http://www.farmdale.com


More information about the spug-list mailing list