# [Tutor] Is something wrong with my round() function?

hcohen2 hcohen2 at comcast.net
Tue Jan 20 13:09:24 EST 2004

Lloyd Kvam wrote:

> This is not a Python issue.  Floating Point numbers are normally stored
> in a base 2 format.  This means that only those fraactions that have
> denominators that are powers of two can be stored exactly.  Python's
> repr function shows a floating point number as exactly as it can (in
> a decimal format).  the str function will do sensible rounding to show
> what you expect.
>
> >>> x = .125
> >>> x
> 0.125
> >>> x = .3
> >>> x
> 0.29999999999999999
> >>> print x
> 0.3
>
> .125 works exactly because it is 1/8 and 8 is a power of 2.
> print uses the str function and displays what you would expect.
> The underlying binary representation is not exactly equal to .3
> because it can't hold it exactly.  It is the same problem we face
> when trying to express 1/3 as a decimal.  We can't do it exactly.
>
> Raymond Hettinger recently published a Python Cookbook recipe for
> examining floating point arithmatic and tracking the accumulated
> errors.
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/265894
>
> hcohen2 wrote:
>
>> The obvious answer is 'YES', but what's causing this strange behaviour?
>>
>>  >>> ans = 48.936
>>  >>> round(ans, 1)
>> 48.899999999999999
>>  >>> round(ans, 2)
>> 48.939999999999998
>>  >>> round(ans, 3)
>> 48.936
>>  >>> round(ans, 4)
>> 48.936
>>  >>> round(ans, 2)
>> 48.939999999999998
>>  >>> round(ans, 1)
>> 48.899999999999999
>>  >
>>
>> I have another example were I was using a class to compute the total
>> room rates that were supposed to be rounded to the nearest cent and
>> they looked like the above sample, however, using the round(<week
>> rate>, 1) gave it properly to the nearest dime.
>>
>> Using python ver 2.2.2 on Linux (Mandrake 9.1) on an IBM laptop.
>>
>> TIA
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
Lloyd,

>>> str(round(ans, 2))
'48.94'

Now that's nicely shown, thanks!

Herschel