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?
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?
If 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
).
If you want to use Decimal:
from decimal import Decimal
dollars = Decimal(dollars.strip('$'))
From there adding is pretty simple
dollars += 1 # Would add 1 to your decimal
First, strip off the '$' character. If it's always consistently the first character, that's easy:
dollars[1:]
To keep the cents perfect without worrying about the non-perfect representation of cents in floating point, you'll want to use Decimal values:
from decimal import *
Decimal(dollars[1:])
Through decimal package
>>> dollars = '$5.99'
>>> import decimal
>>> decimal.Decimal(dollars[1:])
Decimal('5.99')
>>>
If you are only going to be adding (and not multiplying or dividing) consider just storing cents instead of dollars and not using the decimal package. I suggest using the simplest tool for the job, and decimal doesn't provide any value if you are just adding dollars and cents.
If you want to keep moneys in cents for easy rounding and sometimes '$' is missing:
for dollars in ('$5.99','6.77'):
cents = int(float((dollars[1:] if dollars.startswith('$') else dollars))*100)
print '%s = %i cents = %i dollars and %i cents' % ((dollars, cents)+divmod(cents, 100))