working of round()
Steven Bethard
steven.bethard at gmail.com
Sun Apr 15 20:36:18 EDT 2007
Krishna.K.1900 at gmail.com wrote:
> Does round() always perfectly return the output expected or are there
> some artifacts which don't allow perfect functionality
>
> Using python 2.5:
>>>> round(12.234, 2)
> 12.23
>>>> round(12.234, 3)
> 12.234
>>>> round(12.234, 1)
> 12.199999999999999
>
> but was expecting 12.2
>
> Also, for round(x,n), can't 'x' be an expression
>
> round(5.25/2, 2)
>
> was expecting 2.62 , but
>
>>>> round(5.25/2, 2)
> 2.6299999999999999
You're running into floating-point issues (e.g. it's impossible to
represent 2.63 perfectly in binary). What are you really trying to do?
If you just want to format these with only two decimal places, use
string formatting::
>>> '%.2f' % 12.234
'12.23'
>>> '%.2f' % (5.25 / 2)
'2.63'
I'm not sure why you would have expected 2.62 for the latter when::
>>> 5.25 / 2
2.625
STeVe
More information about the Python-list
mailing list