The behavior of the
round() function is different in Python 2 and Python 3. In Python 2, it rounds off numbers away from 0 when the number to be rounded off is exactly halfway through. round(0.5) is 1 and round(-0.5) is -1 whereas in Python 3, it rounds off numbers towards nearest even number when the number to be rounded off is exactly halfway through. See the below output.
Here’s the runtime output for Python version 2.7 interpreter.
$ python
Python 2.7.17 (default, Nov 7 2019, 10:07:09)
>>> round(0.5)
1.0
>>> round(-0.5)
-1.0
>>>
In the above output, you can see that the round() functions on 0.5 and -0.5 are moving away from 0 and hence “round(0.5) – (round(-0.5)) = 1 – (-1) = 2”
Here’s the runtime output for Python version 3.6 interpreter.
$ python3
Python 3.6.8 (default, Oct 7 2019, 12:59:55)
>>> round(0.5)
0
>>> round(-0.5)
0
>>> round(2.5)
2
>>> round(3.5)
4
>>>
In the above output, you can see that the round() functions on 0.5 and -0.5 are moving towards 0 and hence “round(0.5) – (round(-0.5)) = 0 – 0 = 0“. Also note that the round(2.5) is 2 (which is an even number) whereas round(3.5) is 4 (which is an even number).