簡體   English   中英

將float變量轉換為字符串

[英]Converting a float variable to string

我正在嘗試轉換其值更改的變量,但是該值通常為小數點后一位,例如0.5。 我正在嘗試將此變量更改為0.50。 我正在使用此代碼,但是在運行程序時顯示TypeError: Can't convert 'float' object to str implicitly

這是我的代碼:

while topup == 2:
    credit = credit + 0.5
    credit = str(credit)
    credit = '%.2f' % credit
    print("You now have this much credit £", credit)
    vending(credit)
while topup == 2:
    credit = float(credit) + 0.5
    credit = '%.2f' % credit
    print("You now have this much credit £", credit)
    vending(credit)

問題是您不能浮點格式設置字符串

"%0.2f"%"3.45"  # raises error

相反,它期望一個數字

"%0.2f"%3.45   # 0k
"%0.2f"%5   # also ok

因此,當您調用str(credit)它會破壞下面的格式字符串(順便說一句,也會將功勞轉換回字符串)

順便說一句,您應該只在打印時才這樣做

credit = 1234.3
print("You Have : £%0.2f"%credit)

通常,您希望您的信用是數字類型,以便您可以用它進行數學運算

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM