supporting-python-3
supporting-python-3 copied to clipboard
Python 2-style `round()` implementation is not always correct
Thanks for this guide, I've found it a really useful resource when porting some old Python 2 code :heart:
One thing I did notice: the round()
substitute given for Python 2-like behaviour in Python 3 is close, but fails to give the exact Python 2 behaviour in a few cases.
For example:
Python 2.7.18 (default, Jul 1 2022, 12:27:04)
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> def my_round(x, d=0):
... p = 10 ** d
... if x > 0:
... return float(math.floor((x * p) + 0.5))/p
... else:
... return float(math.ceil((x * p) - 0.5))/p
...
>>> my_round(353.765, 2)
353.77
>>> round(353.765, 2)
353.76
Another implementation that I found seems to be a slight improvement. It is also tested against examples taken from the Python 2 test suite.
>>> round2(353.765, 2)
353.76
OK, thanks for noticing.