Decimal arithmatic, was Re: Python GUI app to impress the boss?

Steve Holden sholden at
Sun Sep 29 13:00:34 CEST 2002

<sismex01 at> wrote...
> >
[ ... ]
OK, so don't use whole pennies (or smallest currency) as your
base, use 10,000ths of a penny, but still use integer arithmetic
for your calculations.

Floating point has too many rounding errors to be trustworthy;
or, looking at it from another angle, floating-point calculations
cannot be 100% accurate because of the way it's implemented.

"...has too many errors to be trustworthy..." is clearly an overstatement
given the huge number of computations each day which use floating-point
without any apparent problem. Floating-point got us to the moon and back,
surely it can handle a few money computations.

The real problem is that you have to grok the nature of floating-point to
use it well and appropriately. This is not a simple task (and you only have
to look at the timbot to realise that it can have disastrous consequences
;-). A typical modern double (64-bit floating-point number) will give you an
effective 53 bits of fraction, which equates to over 14 significant figures.
Since you always need two digits after the decimal point you can work with
amounts up to 999,999,999,999.99 without loss of accuracy as long as you
know what you are doing. Appropriate rounding before storage will avoid
accumulation of rounding errors.

Of course, none of this is necessarily an argument that f-p is the *best*
representation for money, but I'm always amused to see people arguing
against it on general grounds when it's perfectly acceptable for many such
purposes *when correctly used*.

Steve Holden                        
Python Web Programming       
Previous .sig file retired to          

More information about the Python-list mailing list