python: how to convert currency to decimal?

Viewed 51423

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?

10 Answers

There's an easy approach:

dollar_dec = float(dollars[1:])

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

Related