Sunday 15 March 2015

python - Converting a float variable to string -



python - Converting a float variable to string -

i'm trying convert variable value changes value 1 decimal place e.g. 0.5. i'm trying alter variable 0.50. i'm using code when run programme says typeerror: can't convert 'float' object str implicitly

here code:

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

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

the problem cannot float format string

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

instead expects number

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

so when phone call str(credit) breaks format string right below (that incidentally casts credit string)

incidentally should when print

credit = 1234.3 print("you have : £%0.2f"%credit)

in general want credit numeric type can math it

python string-formatting

No comments:

Post a Comment