Floating point weirdness
Benjamin Niemann
b.niemann at betternet.de
Wed Aug 25 11:44:58 EDT 2004
Joshua Ginsberg wrote:
> WTF, mate?
>
>
>>>>import sys
>>>>sys.version
>
> '2.3.3 (#1, May 7 2004, 10:31:40) \n[GCC 3.3.3 20040412 (Red Hat Linux
> 3.3.3-7)]'
>
>>>>float('19.95')
>
> 19.949999999999999
>
>>>>round(19.94999999999999999, 2)
>
> 19.949999999999999
>
>>>>round(19.949, 1)
>
> 19.899999999999999
>
> Why can't I just get 19.95?
floats are represented as 64 (or 128?) bit values and there's no value
that exactly represents 19.95 or 19.9 (=round(19.949, 1)). The last
example results in the closest value to 19.9, but not exactly. Python
prints this value with maximum precision. If you want a string
representation of a float with e.g. 2 digits precision, use
"%.2f" % 19.949
More information about the Python-list
mailing list