round function error???

Mark Dickinson dickinsm at gmail.com
Fri Jul 18 18:32:53 EDT 2008


On Jul 18, 11:15 pm, Terry Reedy <tjre... at udel.edu> wrote:
> No, round() return binary floats that, in general, cannot represent
> decimal floats exactly.  Formatted printing gives what you expect.
>  >>> '%8.2f' % x
> ' 3499.35'

Sure.  But it's still true that the second printed value
(printed as 3499.3499999999999) is strictly less than 3499.35,
so when rounding to 1 decimal place an ideal rounding routine
would round it *down* to 3499.3 instead of up to 3499.4.  This
is what '%.1f' does, for example, on a platform where printf
does correct rounding:

Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 3499.35
>>> x
3499.3499999999999
>>> print '%.1f' % x
3499.3
>>> print round(x, 1)
3499.4

Mark



More information about the Python-list mailing list