数字为0时如何在python中显示舍入数字?

时间:2014-08-31 17:37:34

标签: python rounding

这是我目前所拥有的并且它正确地计算数学但是当我使用5作为输入时,数字出现为165.1但我需要它显示165.10。

print("This program converts from feet and inches to centimeters.")
feet = float(input("Enter feet: "))
inches = float(input("Enter inches: "))
n1 = float(feet * 30.48)
n2 = float(inches * 2.54)
n3 = float(n1 + n2)
n4 = round(n3,2)
print("\nThe length is", n4, "cm.")

2 个答案:

答案 0 :(得分:1)

使用Python format string syntaxdocs for 2.7):

number = 10.1
print("{:.2f}".format(number))

关于您的代码的一般评论:您不需要围绕算术运算float()强制转换(但您可能需要input(…)左右,因为input(…)可能会返回一个字符串,具体取决于在你的python版本上)。对数字进行算术运算会给出数字(浮动,在你的情况下)。

答案 1 :(得分:0)

In [3]: "%.2f" % 160.1
Out[3]: '160.10'

也会工作

更多http://floating-point-gui.de/languages/python/