Problem whit float precision, 1.6 Windows 98

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Wed Sep 13 08:04:13 EDT 2000


Juan Huertas wrote in comp.lang.python:
> Interactive windows:
> 
> >>> a=12020.685
> >>> a
> 12020.684999999999
> 
> This is a great problem for monetary treatment.
> 
> Please aid.

Floats are represented in binary form inside the computer. It's not
possible to represent 12020.685 exactly in binary, just like it's not
possible to write 1/3 in a finite amount of decimal digits.

Using floats for money is not a good idea. Little inaccuracies are
unavoidable, and some people have gone so far as to suggest that comparing
two floats with == should be illegal.

If you need a precision of, say, 1/10th of a cent, just multiply the
amount by 1000 and use integers. Integers are exact.

Older versions of Python used to hide this, and printed "12020.685", just
like str(12020.685) still does. But it's always inaccurate under the covers.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl

   This is no way to be
     Man ought to be free      -- Ted Bundy
       That man should be me



More information about the Python-list mailing list