27

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?

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

10 Answers10

27

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
  • 507,862
  • 82
  • 626
  • 550
  • 3
    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 Oct 08 '10 at 05:05
  • The decimal option is the one to take. I'd make a 2 cents joke but it's late. – Andrew H Jul 28 '15 at 12:52
16

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
Amar
  • 231
  • 3
  • 3
  • 3
    This is the only answer that takes into account the possibility of commas as thousands separators, but it also converts to a float instead of a Decimal which causes a loss of precision. – sherbang Dec 18 '13 at 15:26
8

There's an easy approach:

dollar_dec = float(dollars[1:])
lllluuukke
  • 1,304
  • 2
  • 13
  • 17
  • 15
    It's usually a bad idea to store currency as a float. You can lose precision and expose your data to rounding errors quite easily. Now, if you're looking to Superman III some extra money and funnel it into a side account you own... – Jordan Jul 03 '13 at 16:19
  • 2
    AKA Office Space; if you're lucky you won't end up having to burn down the building. – Chinasaur Mar 20 '14 at 22:44
7

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 */
Brian Powell
  • 3,336
  • 4
  • 34
  • 60
5

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
  • 5,732
  • 2
  • 27
  • 35
3

Through decimal package

>>> dollars = '$5.99'
>>> import decimal
>>> decimal.Decimal(dollars[1:])
Decimal('5.99')
>>> 
pyfunc
  • 65,343
  • 15
  • 148
  • 136
2

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.

new name
  • 15,861
  • 19
  • 68
  • 114
0

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
  • 299,747
  • 42
  • 398
  • 622
0

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
  • 5,447
  • 23
  • 31
0

Here's another example of converting a messy currency string into a decimal rounded down to the cent:

from decimal import Decimal, ROUND_DOWN

messy = ',   $1, 111.2199  ,,,'

less_messy = Decimal(''.join(messy.replace(',','').split()).replace('$',''))
converted = less_messy.quantize(Decimal(".01"), rounding=ROUND_DOWN)

print(converted)
1111.21

Other rounding options include: ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_UP

jmunsch
  • 22,771
  • 11
  • 93
  • 114