Why not FP for Money?

Peter Hansen peter at engcorp.com
Wed Sep 22 14:22:23 CEST 2004

John Burton wrote:
> "Chris Barker" <Barkmann at gmail.com> wrote:
>>I've seen it suggested various times that one should use fixed point
>>for money, perhaps micro cents represented as integers. However, if
>>you do that, you need to make sure you do all the rounding correctly.
> On my version of python:
> # I spent £1 and 13 pence
> p = 1.13
> # How many pence is that?
> print int(p*100)
> 112
> # Oops
> You don't need quadrillions of dollars before you run into a value which 
> can't be represented in a floating point value to such a degree that the 
> rounding comes out wrong.  Yes you could probably "fix" the rounding to make 

At the risk of sounding like I might be supporting the idea of
using floats (which I'm not):

 >>> p = 1.12
 >>> print round(p*100)
 >>> print int(round(p*100))

int() doesn't do rounding, it truncates.  If you actually *do* round,
it tends to work just fine.  If all operations ended with a call to
round(), the floating point idea would not really be as bad as you
suggest here...  but it's still a bad idea. :-)


More information about the Python-list mailing list