【问题标题】:Round a float and convert it to an integer in a Python2 and Python3 compatible manner以 Python2 和 Python3 兼容的方式对浮点数进行舍入并将其转换为整数
【发布时间】:2016-04-02 09:18:14
【问题描述】:

为了生成 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 兼容的方式舍入为整数的规范方法吗?

【问题讨论】:

  • 不知道是不是规范,但这是我会做的。
  • 如果给出单个参数,Python 3 将返回一个整数。否则类型匹配第一个参数的类型。例如,在 Python 3 中尝试 round(2.7, 0)

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 2018-08-15
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多