在Python 2.7中实现Python 3的round函数

3

我在我的Google-App-Engine项目中使用一些用Python 3编写的旧代码,该项目使用Python 2.7。 Python 3和Python 2中不同的round()算法让我很头痛。是否有方便的方法在Python 2.7中实现Python 3的round()方法?

更进一步的问题:Python 2和Python 3处理整数操作的方式非常不同。例如,以下语句在Python 2和3中具有不同的输出:

2/4   # 0 in Python 2, 0.5 in Python 3
round(3/2)  
math.ceil(0.5)   # 1.0 in Python 2, 1 in Python 3

有没有一种简单的方法将Python 3的代码转换为Python 2,同时保持行为完全相同?谢谢!

使用 from __future__ import division 可以在 Python 2.x 中获得 Python 3.x 的除法行为。 - Ashwini Chaudhary
1个回答

4

银行家舍入已经在future中实现。可以通过__future__导入使浮点除法成为默认设置。

from __future__ import division
from future.modified_builtins import round

2
我在Python 2.7中尝试使用"from future.modified_builtins import round",但是出现了ImportError错误,显示没有找到future.modified_builtins模块。我无法获取有关此“future.modified_builtins”库的有用结果。这里有什么问题吗? - Tao Chen
你先尝试安装了吗? - Ignacio Vazquez-Abrams
1
我没有特别安装它。只安装了标准的Python 2.7和GAE库。 - Tao Chen
1
谢谢。我在这里找到了:https://github.com/edschofield/python-future/blob/master/future/modified_builtins/newround.py 我曾经认为它包含在标准的2.7发行版中。 - Tao Chen
@DakshShah:__future__是stdlib的一部分。 - Ignacio Vazquez-Abrams
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接