Last modified: March 08, 2021

Currency conversion in python

In this post, I'll show you how to convert currency in python by using forex-python library.

1. forex-python installation

To install forex-python via pip, you need to follow this command.

pip install forex-python

2 syntax

c.get_rate(local_Currency, to_Currency)

3. Convert USD to EURO

in the first example, we'll convert USD to EURO.


from forex_python.converter import CurrencyRates 

c = CurrencyRates()
Currency = c.get_rate('USD', 'EUR')  #convert USD to EURO
print(Currency)

Output

0.9048136084

To print the specified number of decimals, we need to use the road() built-function.


print(round(Currency, 3))

Output

0.905

4. list of all currency rates for "USD"

In this second example, we'll get a list of all currency rates for USD.


from forex_python.converter import CurrencyRates

c = CurrencyRates()
c.get_rates('USD')

output

{u'IDR': 13625.0, u'BGN': 1.7433, u'ILS': 3.8794, u'GBP': 0.68641, u'DKK': 6.6289, u'CAD': 1.3106, u'JPY': 110.36, u'HUF': 282.36, u'RON': 4.0162, u'MYR': 4.081, u'SEK': 8.3419, u'SGD': 1.3815, u'HKD': 7.7673, u'AUD': 1.3833, u'CHF': 0.99144, u'KRW': 1187.3, u'CNY': 6.5475, u'TRY': 2.9839, u'HRK': 6.6731, u'NZD': 1.4777, u'THB': 35.73, u'EUR': 0.89135, u'NOK': 8.3212, u'RUB': 66.774, u'INR': 67.473, u'MXN': 18.41, u'CZK': 24.089, u'BRL': 3.5473, u'PLN': 3.94, u'PHP': 46.775, u'ZAR': 15.747}

3. Convert USD to BITCOIN

The Forex-python library also supports bitcoin Currency.
Let's convert 1 bitcoin to USD.


from forex_python.bitcoin import BtcConverter
b = BtcConverter() # force_decimal=True to get Decimal rates
b.get_latest_price('USD')


output

533.913

as you can see, 1 BITCOIN = 533.913$

for more options, please visit forex-python