如何让python将字符串更改为2dcp

2024-09-30 16:27:56 发布

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

我可以说这个问题已经得到了某种程度的解决,但我找不到解决办法。 问题是,我正在尝试将变量“price”更改为str,并将其格式化为有2个小数位。 代码如下:

def fin():
    while True:
        global price
        wantdrink = input("Would you like a drink? (We only server Coke): ")
        if wantdrink not in "Yes" "yes" "No" "no" "Yeah" "yeah" "Nah" "nah":
            wrong()
        elif wantdrink in "Yes" "yes" "Yeah" "yeah":
            print("Got to stay hydrated!")
            price = price + 0.50
            price = str(price)
            "{0:.2f}".format(price)
            print("Your order is complete! The total price is", price , "pounds")
            time.sleep(3)
            print("Your order numbmer is:", num1 + num2 + num3 + num4 + num5)
            time.sleep(3)
            print("Your food will be delivered in", timnum1 + timnum2, "minuites!")
            time.sleep(3)
            print("Thanks for ordering from Hungry Horse(TM)!")
            time.sleep(3)
            sys.exit()
        elif wantdrink in "No" "no" "Nah" "nah":
            print("Don't get too thirsty!")
            price = str(price)
            "{0:.2f}".format(price)
            print("Your order is complete! The total price is", price, "pounds")
            time.sleep(3)
            print("Your order numbmer is:", num1 + num2 + num3 + num4 + num5)
            time.sleep(3)
            print("Your food will be delivered in", timnum1 + timnum2, "minuites!")
            time.sleep(3)
            print("Thanks for ordering from Hungry Horse(TM)!")
            time.sleep(3)
            sys.exit()

这只是程序的一部分,展示完整的东西会有帮助吗?你知道吗

无论如何,在运行程序时,python只显示:

ValueError: Unknown format code 'f' for object of type 'str'

有办法解决这个问题吗?我只是在装傻吗?请帮忙。。。你知道吗


Tags: noinformatforyourtimeisorder
3条回答

您正在使用str预转换为字符串。format已经帮你做了。重新调整空间

price = str(price)
"{0:.2f}".format(price)

只是

price = "{0:0.2f}".format(price)

当然,不能打印具有两位浮点精度的字符串。你知道吗

ValueError: Unknown format code 'f' for object of type 'str'

问题是你没有号码。你已经有一个字符串了。你知道吗

演示:

>>> price = 1
>>> type(price)
<class 'int'>
>>> "{0:.2f}".format(price)
'1.00'
>>> 
>>> price = 1.5
>>> type(price)
<class 'float'>
>>> "{0:.2f}".format(price)
'1.50'
>>> 
>>> price = '1.5'
>>> type(price)
<class 'str'>
>>> "{0:.2f}".format(price)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
>>> 

仔细检查您的代码后:

price = str(price)
"{0:.2f}".format(price)

您将数字转换为字符串,但未指定任何格式:str(price)。然后您尝试格式化一个字符串,但没有对返回值执行任何操作。你知道吗

要修复它:

price = "{0:.2f}".format(price)


顺便说一句,使用浮点数据来计算价格是非常糟糕的做法。如果您想要精确的货币处理,您需要使用十进制或定点类型。原因是碱基-2和碱基-10的分数并不完全一致。这一点在网上有很好的记录和解释。你知道吗

根据疯狂物理学家的答案,您可以将格式化后的价格带入订单完成的行中:

print("Your order is complete! The total price is {0:.2f} pounds.".format(price))

相关问题 更多 >