简体   繁体   English

将float变量转换为字符串

[英]Converting a float variable to string

I'm trying to convert a variable whose value changes however the value is usually to one decimal place eg 0.5. 我正在尝试转换其值更改的变量,但是该值通常为小数点后一位,例如0.5。 I'm trying to change this variable to 0.50. 我正在尝试将此变量更改为0.50。 I'm using this code but when I run the program it says TypeError: Can't convert 'float' object to str implicitly 我正在使用此代码,但是在运行程序时显示TypeError: Can't convert 'float' object to str implicitly

Here is my code: 这是我的代码:

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)

the problem is you cannot float format a string 问题是您不能浮点格式设置字符串

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

instead it expects a number 相反,它期望一个数字

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

so when you call str(credit) it breaks the format string right below (that incidentally also casts credit back to a string) 因此,当您调用str(credit)它会破坏下面的格式字符串(顺便说一句,也会将功劳转换回字符串)

incidentally you should really only do this when you print 顺便说一句,您应该只在打印时才这样做

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

in general you want your credit to be a numeric type so that you can do math with it 通常,您希望您的信用是数字类型,以便您可以用它进行数学运算

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM