[ python-Bugs-1456775 ] round not rounding correctly

SourceForge.net noreply at sourceforge.net
Thu Mar 23 10:33:34 CET 2006


Bugs item #1456775, was opened at 2006-03-23 08:53
Message generated for change (Comment added) made by gbrandl
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1456775&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Library
Group: Python 2.4
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Norbert Sebok (seboknorbi)
Assigned to: Nobody/Anonymous (nobody)
Summary: round not rounding correctly

Initial Comment:
For example:
print 72.805, round(72.805,2)
print 72.815, round(72.815,2)
print 72.825, round(72.825,2)
print 72.835, round(72.835,2)
print 72.845, round(72.845,2)
print 72.855, round(72.855,2)
print 72.865, round(72.865,2)
print 72.875, round(72.875,2)
print 72.885, round(72.885,2)
print 72.895, round(72.895,2)

The results:
72.805 72.81
72.815 72.82
72.825 72.83
72.835 72.83 !!! not 72.84
72.845 72.85
72.855 72.86
72.865 72.86 !!! not 72.87
72.875 72.88
72.885 72.89
72.895 72.9

The problem seems to exists with numbers ending with 5.
Another examples:
round(0.015,2) == 0.01 != 0.02
round(0.045,2) == 0.04 != 0.05
round(0.075,2) == 0.07 != 0.08
round(0.105,2) == 0.1 != 0.11
round(0.145,2) == 0.14 != 0.15
round(0.155,2) == 0.15 != 0.16
round(0.175,2) == 0.17 != 0.18
round(0.185,2) == 0.18 != 0.19
round(0.205,2) == 0.2 != 0.21
round(0.215,2) == 0.21 != 0.22
round(0.235,2) == 0.23 != 0.24
round(0.245,2) == 0.24 != 0.25
round(0.285,2) == 0.28 != 0.29
round(0.295,2) == 0.29 != 0.3
round(0.305,2) == 0.3 != 0.31
round(0.345,2) == 0.34 != 0.35

It's the same on Linux and Win32.

----------------------------------------------------------------------

>Comment By: Georg Brandl (gbrandl)
Date: 2006-03-23 09:33

Message:
Logged In: YES 
user_id=849994

Actually:
>>> 72.835
72.834999999999994
>>> 

This is due to the computer's internal floating point
representation, which is not decimal, but binary. So round()
behaves correctly. See
http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate
for more information.

If you need these calculations to be exact, use Decimals,
available in the decimal module.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1456775&group_id=5470


More information about the Python-bugs-list mailing list