This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: round not rounding correctly
Type: Stage:
Components: Library (Lib) Versions: Python 2.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, seboknorbi
Priority: normal Keywords:

Created on 2006-03-23 08:53 by seboknorbi, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg27854 - (view) Author: Norbert Sebok (seboknorbi) Date: 2006-03-23 08:53
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.
msg27855 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2006-03-23 09:33
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.
History
Date User Action Args
2022-04-11 14:56:16adminsetgithub: 43075
2006-03-23 08:53:59seboknorbicreate