Random Currency Conversion with Babel Library

  • Share this:

Code introduction


The function uses Babel library's currency parsing and formatting capabilities to convert an amount from one currency to another. The function first parses the input currency codes, then formats the original amount, generates a random exchange rate for conversion, and finally formats the converted amount.


Technology Stack : Babel

Code Type : Function

Code Difficulty : Intermediate


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

def random_currency_converter(amount, from_currency, to_currency):
    """
    Converts an amount from one currency to another using Babel library.
    """
    # Parse the input currency codes to ensure they are valid
    try:
        from_curr = parse_currency(from_currency)
        to_curr = parse_currency(to_currency)
    except ValueError:
        return "Invalid currency code provided."

    # Format the amount with the original currency
    formatted_amount = format_currency(amount, from_curr, locale='en_US')
    
    # Convert the amount using a random exchange rate
    random_rate = random.uniform(0.5, 1.5)  # Random exchange rate between 0.5 and 1.5
    converted_amount = amount * random_rate

    # Format the converted amount with the target currency
    converted_formatted_amount = format_currency(converted_amount, to_curr, locale='en_US')
    
    return f"{formatted_amount} {from_currency} converts to {converted_formatted_amount} {to_currency}."                
              
Tags: