【问题标题】:float to integer in python在python中浮动到整数
【发布时间】:2011-10-01 17:49:23
【问题描述】:

如果我想在 Python 中将浮点数转换为整数,我应该使用什么函数?

问题是我必须使用通过函数math.fabs(绝对值)传递的变量作为列表的索引,所以它必须是int,而函数math.fabs返回一个@ 987654324@.

【问题讨论】:

    标签: python floating-point integer absolute-value


    【解决方案1】:

    使用int() 构造函数:

    >>> foo = 7.6
    >>> int(foo)
    7
    

    请注意,如果您将 built-in abs() function 与整数参数一起使用,您首先会得到一个整数结果:

    >>> type(abs(-7))
    <type 'int'>
    

    【讨论】:

      【解决方案2】:

      您可能正在寻找roundint

      >>> foo = 1.9
      >>> int(foo)
      1
      >>> int(round(foo))
      2
      

      【讨论】:

        猜你喜欢
        • 2020-07-26
        • 2016-12-25
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 2018-05-18
        相关资源
        最近更新 更多