Reputation: 11
I'm trying to convert a variable whose value changes however the value is usually to one decimal place e.g. 0.5. I'm trying to change this variable to 0.50. I'm using this code but when I run the program it says 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)
Upvotes: 0
Views: 2660
Reputation: 114098
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)
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
Upvotes: 1