【问题标题】:Using .format to turn a float to an integer [duplicate]使用 .format 将浮点数转换为整数 [重复]
【发布时间】:2017-03-01 00:01:27
【问题描述】:

非常快速的问题。

x = 10
print("value is {:d}".format(x))

返回

value is 10

另一方面:

x = 10.0
print("value is {:d}".format(x))

返回

ValueError: Unknown format code 'd' for object of type 'float'

为什么这不起作用?

【问题讨论】:

标签: python


【解决方案1】:

您将使用 f 而不是 d 来表示浮点数。然后指定精度宽度为0:

>>> print("value is {:.0f}".format(x))
value is 10

【讨论】:

    【解决方案2】:

    来自 Python 文档:'d' Decimal Integer. Outputs the number in base 10. 它将以 10 为基数输出数字,这就是为什么你会得到 ValueError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多