舍入浮点数并将其转换为Python2和Python3兼容方式的整数

时间:2016-04-02 09:18:14

标签: python python-2.7 python-3.x

为了生成Numpy索引,我需要将float舍入为int

在Python 2.7中,舍入float会得到float

>>> round(2.7)
3.0

在Python 3.5中,返回int

>>> round(2.7)
3

np.round()总是返回一个浮点数。

int(round(2.7))是否以Python 2/3兼容方式舍入为整数的规范方法?

1 个答案:

答案 0 :(得分:0)

int(round(2.7))适用于这两个版本。这里有一个类似的问题,但仅针对Python 2.7: Python 2.7: round number to nearest integer - 所以我会使用int(round(x))