Python:允许浮点数前有"$"符号
我想让用户输入一个带有“$”符号的浮点数,比如他们可以输入“$4.25”,也可以输入“4.25”。
另外,当我在计算器里输入“4.35”时,计算出的提示金额是“0.6”。而我家里的计算器算出来的是0.6525。我该怎么才能得到完整的答案呢?
input ('Please Enter to begin')
while True:
print('This calculator will display the tip you owe for your meal price.')
mealPrice = int(float(input('Enter your meal price:')))
asw = mealPrice * 0.15
print('The tip you owe is: $',asw)
endProgram = input ('Do you want to restart the program?')
if endProgram in ('no', 'No', 'NO', 'false', 'False', 'FALSE'):
break
1 个回答
5
把
mealPrice = int(float(input('Enter your meal price:')))
改成
mealPrice = float(input('Enter your meal price:').lstrip("$"))
lstrip("$")
这个方法会把字符串左边的所有“$”符号去掉。你还需要去掉 int
,因为它会把价格截断到最接近的整数(这也是你有时候得到错误答案的原因)。