i have dollars in a string variable
dollars = '$5.99'
how do i convert this to a decimal instead of a string so that i can do operations with it like adding dollars to it?
See Question&Answers more detail:osi have dollars in a string variable
dollars = '$5.99'
how do i convert this to a decimal instead of a string so that i can do operations with it like adding dollars to it?
See Question&Answers more detail:osIf you'd prefer just an integer number of cents:
cents_int = int(round(float(dollars.strip('$'))*100))
If you want a Decimal, just use...
from decimal import Decimal
dollars_dec = Decimal(dollars.strip('$'))
If you know that the dollar sign will always be there, you could use dollars[1:]
instead of dollars.strip('$')
, but using strip()
lets you also handle strings that omit the dollar sign (5.99
instead of $5.99
).