Skip to content Skip to sidebar Skip to footer

Python: How To Convert Currency To Decimal?

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?

Solution 1:

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


Solution 2:

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

Solution 3:

There's an easy approach:

dollar_dec = float(dollars[1:])

Solution 4:

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

Solution 5:

I know this an old question, but this is a very simple approach to your problem that's easily readable:

for:

dollars = '$5.99'
dollars = dollars.replace("$","").replace(",","")
/* 5.99 */

It also works with a larger number that might have a comma in it:

dollars = '1,425,232.99'
dollars = dollars.replace("$","").replace(",","")
/* 1425232.99 */

Post a Comment for "Python: How To Convert Currency To Decimal?"