如何确保用户输入为$XX.XX格式?也可以是$XX格式,但程序会将其转换为2十进制浮点

2024-10-03 11:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想确保用户输入的是$XX或$XX.XX格式。如果是$XX,那么程序会将$XX更改为$XX.00。基本上,我想从用户那里获得一个美元和美分的金额,确保它是一个带小数的浮点(如果不是,返回一条错误消息并再次请求输入),然后向用户确认金额是正确的。我才刚刚开始,所以欢迎使用多种技术,并解释哪种技术最好。提前谢谢你

def收入(公司):

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

Tags: 用户fromfalseinputfloat金额技术company
1条回答
网友
1楼 · 发布于 2024-10-03 11:22:39

您可以使用"{:.2f}".format(total)以XX.XX(或X.XX或XXX.XX等)格式打印总额。这会将其格式化为小数点后两位的浮点值。您不需要将此格式应用于任何数学,只需打印即可

检查输入是否为有效数字可以用

try:
   val = float(userInput)
except ValueError:
   # your code here

相关问题 更多 >