我正在研究一个需要我从用户那里获取浮点值的类项目.此浮点值必须在十进制后正好有两个数字才能成为有效输入.这就是我到目前为止所拥有的.
while True:
try:
cost = float(input("Enter the price: "))
if cost % 1 == 0:
print("Invalid input for price.")
else:
if cost > 0:
return cost
except ValueError:
print("Invalid input for price.")
Run Code Online (Sandbox Code Playgroud)
相比cost % 1
于0
排除了整数和.00花车结束,但我不知道我怎么会小数(iexxx)后,限制接受输入到浮动恰好与2号.另外我相信我需要接受像5.00一样的浮动,所以我的方法不会削减它.我已经尝试过转换cost
为str并设置长度限制,但这仍然让它容易出错.有什么建议?
您可以在转换为float之前检查它:
cost = input("Enter the price: ")
if len(cost.rsplit('.')[-1]) == 2:
print('2 digits after decimal point')
Run Code Online (Sandbox Code Playgroud)