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

2024-01-10

为了生成 Numpy 索引,我需要舍入float to an int.

在 Python 2.7 中,舍入 afloat给出一个float:

>>> round(2.7)
3.0

在 Python 3.5 中,int返回:

>>> round(2.7)
3

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

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


int(round(2.7))适用于两个版本。这里提出了类似的问题,但仅适用于 Python 2.7:Python 2.7:将数字四舍五入到最接近的整数 https://stackoverflow.com/questions/31818050/python-2-7-round-number-to-nearest-integer- 所以我会用int(round(x))

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对浮点数进行舍入并以 Python2 和 Python3 兼容的方式将其转换为整数 的相关文章

随机推荐