tags:

views:

86

answers:

6

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?

+5  A: 

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).

Amber
If you prefer an integer number of cents, keep it integral all the way: `d, c = dollars.strip('$').split('.', 2); cents = int(d) * 100 + int(c.strip()[:2])`. Of course, this assumes you want to round fractional cents toward 0 (insert Superman III joke of choice here).
Mike DeSimone
+3  A: 

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
Tim
A: 

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:])
Mark Ransom
+1  A: 

Through decimal package

>>> dollars = '$5.99'
>>> import decimal
>>> decimal.Decimal(dollars[1:])
Decimal('5.99')
>>> 
pyfunc
+1  A: 

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.

Jeff
A: 

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))
Tony Veijalainen