python: how to convert currency to decimal?

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


Assuming the string stored in the variable dollars was generated using python's locale module. A potentially cleaner way to convert it back to float (decimal) is to use the atof function from the same module. It should work as long as you use the same setlocale parameters in both directions (from currency to string and vice-versa).

for instance:

import locale
locale.setlocale(locale.LC_ALL, '')
value = 122445.56
value_s = locale.currency(value, grouping=True)
#generates $122,445.56

to convert it back:

value2 = locale.atof(value_s[1:])
#value2 = 122445.56 
value == value2 #True

Tags:

Python