Python2 round isn’t what you think

The usual wisdom is that python2 “rounding of halfway cases was away from zero”.

Does that mean that

Python 2.7.12 (default, Mar  1 2021, 11:38:31) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(100.215, 2)
100.22

Right ? Away from zero.

Then, explain this:

>>> round(2.675, 2)
2.67

The problem seems to come from the underlying floating point representation (no way to represent exactly 2.675 for example).

Utterly annoying when porting code from python2 to python3, especially with a ton of tests that will break.

By the way

>>> round(56.805, 2)
56.8
>>> round(-2.675, 2)
-2.67

Be the first to comment

Leave a Reply

Your email address will not be published.