【问题标题】:Python: How do I output my float values with two digits after the decimal with new .format()? [duplicate]Python:如何使用 new .format() 输出小数点后两位的浮点值? [复制]
【发布时间】:2017-11-05 14:02:18
【问题描述】:

我正在自学一些 Python 以获得工作机会。我刚刚开始,我似乎无法调和如何使用 print"".format() 输出小数点后只有两位数的浮点数。

我试过把 .2f 放在不同的地方;没运气。

这就是我所拥有的:

def displayEmployeeData(self):
    print "Name: {:<10} ID: {:<10} Team: {:<10} salary: ${:<10} tenure: {:<10} months".format(self.name, self.ID, self.team, self.salary, self.tenure)

【问题讨论】:

  • 使用这个{:.2f}

标签: python python-3.x formatting


【解决方案1】:

它遵循格式

print '{arg_num: format} string".format(<tuple of args>)

所以在你的情况下,它会像:

def displayEmployeeData(self):
    print "Name: {0} ID: {1} Team: {2} salary: ${3:.2f} tenure: {4} months".format(self.name, self.ID, self.team, self.salary, self.tenure)

【讨论】:

  • 如果我已经有 {:
【解决方案2】:

您需要使用{0:.xf},其中 0 是参数编号,x 是您想要的位数。

>>> print "{0:.3f} something".format(2.234234239)
>>> 2.234 something

请通过documentation了解更多格式细节。

【讨论】:

  • 如果我已经有 {:
  • 在这种情况下你可以使用{0:&lt;10.3f}
【解决方案3】:

你有这两种方式:

print("{0:.3f} something".format(2.234234239))
print("{0:<10.3f} something".format(2.234234239))

或者,或者:

data = 2.234234239
print(f"{data:.3f} something")
print(f"{data:<10.3f} something")

输出:

2.234 something
2.234      something

【讨论】:

  • 我的 :
  • 查看对答案的修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2011-01-18
  • 2012-06-30
相关资源
最近更新 更多