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

当数字为0时,如何在python中显示舍入的数字?,python,rounding,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 =

这是我目前拥有的,它的计算正确,但当我使用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.")
也会起作用

更多

请使用():



关于代码的一般说明:您不需要在算术运算中使用
float()
强制转换(但可能需要在
input(…)
中使用它,因为
input(…)
可能会返回字符串,具体取决于您的python版本)。再次对数字进行算术运算会给出数字(在您的情况下是浮点数)。

是否需要固定数量的有效数字(即应
12
输出
12.000
)或者小数点后有固定数量的数字就足够了吗?我需要它在小数点后显示2个点,不管数字是什么。我不知道为什么删除了正确的答案。我尝试过使用它,但它所做的只是给我一个无效的snytix。你能告诉我们你到底在尝试什么吗?,必须为单个替换传递一个值以格式化函数-有时
format(number,.2f')
读取效果更好。当我使用您的函数时,会出现以下错误:ValueError:Unknown format code“f”用于类型为'str'@AmandaC的对象。那你不是在传递一个号码。对于原始代码,它将起作用(将
number
替换为
n4
)。
In [3]: "%.2f" % 160.1
Out[3]: '160.10'
number = 10.1
print("{:.2f}".format(number))