将float变量转换为string

时间:2014-10-09 17:43:22

标签: python string-formatting

我尝试转换其值发生变化的变量,但该值通常为一位小数,例如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)

1 个答案:

答案 0 :(得分:1)

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)

一般来说,你希望你的信用是一种数字类型,这样你就可以用它做数学