Skip to main content
 首页 » 编程设计

python之我如何在 Python2 中对 `round` 函数进行 future 验证

2024年09月07日11emanlee

当 round 从 future 导入时,它的行为与 Python3 round 函数不同。具体来说,它不支持负数舍入。

在 Python3 中:

>>> round(4781, -2) 
4800 

在 Python2 中:

>>> from builtins import round 
>>> round(4781, -2) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/usr/lib/python2.7/dist-packages/future/builtins/newround.py", line 33, in newround 
    raise NotImplementedError('negative ndigits not supported yet') 
NotImplementedError: negative ndigits not supported yet 

可能的解决方案包括负舍入的错误处理、编写我自己的 round 函数等。应该如何处理? (含蓄地,我要求最佳实践,大多数 Pythonic,被社区接受等)

请您参考如下方法:

我打算建议您的自定义函数想法,这样您就可以确保它始终按照您的意愿行事,但这似乎是一个特殊(奇怪)的情况,如果我不使用future.builtin.round() 我明白了

python 3.6:

>>> round(4781, -2) 
4800 

和 Python 2.7:

>>> round(4781, -2) 
4800.0 

似乎只是 future.builtins 以某种方式损坏了;在这种情况下,您应该避免使用 future.builtins.round() 函数。请注意,py3 round() 返回一个整数,而 py2 round() 返回一个 float ,但这似乎是两种股票实现之间的唯一区别(对于简单的舍入操作例如给出的示例)。