Skip to content

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

@StevenMaude

Description

@StevenMaude

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions