Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 2-style round() implementation is not always correct #32

Open
StevenMaude opened this issue Oct 8, 2022 · 1 comment
Open

Python 2-style round() implementation is not always correct #32

StevenMaude opened this issue Oct 8, 2022 · 1 comment

Comments

@StevenMaude
Copy link

StevenMaude commented Oct 8, 2022

Thanks for this guide, I've found it a really useful resource when porting some old Python 2 code ❤️

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
@regebro
Copy link
Owner

regebro commented Oct 9, 2022

OK, thanks for noticing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants