如何确保用户输入为 $XX.XX 格式?也可以是 $XX 格式,但程序会将其转换为 2 位小数浮点数
How to make sure user input is in $XX.XX format? Could also be in $XX format but program will convert it to a 2 decimal float
我想确保用户输入的格式为 $XX 或 $XX.XX。如果它在 $XX 中,则程序会将 $XX 更改为 $XX.00。基本上我想从用户那里得到一个美元和美分的金额,确保它是一个带小数点的浮点数(如果不是,return 一条错误消息并再次要求输入)然后确认金额是正确的用户。我才刚刚开始,所以欢迎使用多种技术,并解释哪种技术最好。提前致谢!!!
默认收入(公司):
print("Do you have any income from", company, "today?")
ans = confirm()
delay(0.45)
if ans == True:
total = input('What was your income from ' + company + ' today?\nIncome: $')
while isinstance(total, (float, int)):
print("Invalid amount! Please enter in $XX.XX format.")
total = input('Income: $')
if isinstance(total, (float, int)):
return total
print('Is $', total ,'correct?')
totalconfirm = confirm()
while totalconfirm == False:
total = float(input('Enter the correct amount: $'))
totalconfirm = confirm()
elif ans == False:
return False
您可以使用 "{:.2f}".format(total)
以 XX.XX(或 X.XX 或 XXX.XX 等格式)打印总数。这会将其格式化为小数点后两位的浮点数。您不需要将此格式应用于任何数学运算,只需打印即可。
检查输入是否为有效数字可以用
完成
try:
val = float(userInput)
except ValueError:
# your code here
我想确保用户输入的格式为 $XX 或 $XX.XX。如果它在 $XX 中,则程序会将 $XX 更改为 $XX.00。基本上我想从用户那里得到一个美元和美分的金额,确保它是一个带小数点的浮点数(如果不是,return 一条错误消息并再次要求输入)然后确认金额是正确的用户。我才刚刚开始,所以欢迎使用多种技术,并解释哪种技术最好。提前致谢!!!
默认收入(公司):
print("Do you have any income from", company, "today?")
ans = confirm()
delay(0.45)
if ans == True:
total = input('What was your income from ' + company + ' today?\nIncome: $')
while isinstance(total, (float, int)):
print("Invalid amount! Please enter in $XX.XX format.")
total = input('Income: $')
if isinstance(total, (float, int)):
return total
print('Is $', total ,'correct?')
totalconfirm = confirm()
while totalconfirm == False:
total = float(input('Enter the correct amount: $'))
totalconfirm = confirm()
elif ans == False:
return False
您可以使用 "{:.2f}".format(total)
以 XX.XX(或 X.XX 或 XXX.XX 等格式)打印总数。这会将其格式化为小数点后两位的浮点数。您不需要将此格式应用于任何数学运算,只需打印即可。
检查输入是否为有效数字可以用
完成try:
val = float(userInput)
except ValueError:
# your code here