Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to convert currency to decimal?

Tags:

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?

like image 426
Alex Gordon Avatar asked Oct 08 '10 03:10

Alex Gordon


People also ask

How do you convert to a Decimal in Python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you convert currency in Python?

The Forex-Python library provides the most direct way to get a currency conversion rate through API calls. It has different functions, which take the currency codes you want to convert from one currency to another and then return the current value. In this Python program, we are converting USD to INR.


1 Answers

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

like image 123
Amber Avatar answered Nov 09 '22 23:11

Amber