将浮点数舍入并以 Python2 和 Python3 兼容的方式将其转换为整数 [英] Round a float and convert it to an integer in a Python2 and Python3 compatible manner

查看:40
本文介绍了将浮点数舍入并以 Python2 和 Python3 兼容的方式将其转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<预><代码>>>>回合(2.7)3.0

在 Python 3.5 中,返回一个 int:

<预><代码>>>>回合(2.7)3

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

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

解决方案

int(round(2.7)) 适用于两个版本.这里问了一个类似的问题,但只针对 Python 2.7:Python 2.7:四舍五入到最接近的整数- 所以我会使用 int(round(x))

For generating Numpy indexes, I need to round a float to an int.

In Python 2.7, rounding a float gives a float:

>>> round(2.7)
3.0

In Python 3.5, an int is returned:

>>> round(2.7)
3

np.round() always returns a float.

Is int(round(2.7)) the canonical approach to round to an integer in a Python 2/3 compatible way?

解决方案

int(round(2.7)) works for both versions. A similar question but only for Python 2.7 was asked here: Python 2.7: round number to nearest integer - so I would use int(round(x))

这篇关于将浮点数舍入并以 Python2 和 Python3 兼容的方式将其转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆