Currency Conversion Function with Babel Library

  • Share this:

Code introduction


The function takes an amount and two currency codes as input and returns the converted amount in the target currency. It uses the Babel library to parse and format currency values.


Technology Stack : Babel, currency parsing, currency formatting

Code Type : Currency Converter

Code Difficulty : Intermediate


                
                    
import random
from babel.numbers import format_currency, parse_currency
from babel.dates import format_date, parse_date

def currency_converter(amount, from_currency, to_currency):
    try:
        parsed_amount, parsed_from_currency = parse_currency(amount, locale='en_US')
        parsed_to_currency = parse_currency(to_currency, locale='en_US')
        converted_amount = format_currency(parsed_amount, parsed_from_currency, parsed_to_currency, locale='en_US')
        return converted_amount
    except Exception as e:
        return f"Error: {str(e)}"

# JSON Explanation