CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-num2words

Modules to convert numbers to words in multiple languages with support for 50+ locales.

Pending
Overview
Eval results
Files

currency-conversion.mddocs/

Currency Conversion

Specialized functionality for converting numbers to properly localized currency representations. The num2words library provides comprehensive currency support with language-specific formatting, pluralization rules, and cultural conventions.

Capabilities

Currency Conversion Function

Convert numeric values to currency word representations with extensive customization options.

def to_currency(val, currency='EUR', cents=True, separator=',', adjective=False):
    """
    Convert number to currency word representation.
    
    Parameters:
    - val: int/float/Decimal - Currency value to convert
    - currency: str - Currency code (default: 'EUR')
    - cents: bool - Use verbose cents representation (default: True)
    - separator: str - Separator between currency and cents (default: ',')
    - adjective: bool - Include currency adjective prefix (default: False)
    
    Returns:
    str - Formatted currency string with proper localization
    
    Raises:
    NotImplementedError - If currency not supported for language
    """

Usage Examples:

from num2words import num2words

# Basic currency conversion (EUR default)
result = num2words(42.50, to='currency')
# "forty-two euros, fifty cents"

# Different currencies
result = num2words(42.50, to='currency', currency='USD')
# "forty-two dollars, fifty cents"

result = num2words(42.50, to='currency', currency='GBP')
# "forty-two pounds, fifty pence"

# Different languages
result = num2words(42.50, to='currency', lang='fr')
# "quarante-deux euros, cinquante centimes"

result = num2words(42.50, to='currency', lang='es')
# "cuarenta y dos euros, cincuenta céntimos"

Currency Formatting Options

Control various aspects of currency formatting.

Cents Representation:

# Verbose cents (default)
num2words(42.50, to='currency', cents=True)
# "forty-two euros, fifty cents"

# Numeric cents
num2words(42.50, to='currency', cents=False)
# "forty-two euros, 50"

# Zero cents handling
num2words(42.00, to='currency')
# "forty-two euros"  (no cents when zero)

num2words(42.00, to='currency', cents=False)
# "forty-two euros, 00"  (explicit numeric format)

Separator Customization:

# Default comma separator
num2words(42.50, to='currency')
# "forty-two euros, fifty cents"

# Custom separators
num2words(42.50, to='currency', separator=' and ')
# "forty-two euros and fifty cents"

num2words(42.50, to='currency', separator=' with ')
# "forty-two euros with fifty cents"

num2words(42.50, to='currency', separator='/')
# "forty-two euros/fifty cents"

Currency Adjectives:

# Standard currency names
num2words(42.50, to='currency', currency='EUR')
# "forty-two euros, fifty cents"

# With adjective prefix (when supported)
num2words(42.50, to='currency', currency='EUR', adjective=True)
# "forty-two European euros, fifty European cents"  (if supported)

Currency Parsing and Processing

Internal functions for handling currency value parsing.

def parse_currency_parts(value, is_int_with_cents=True):
    """
    Parse currency value into integer and cents components.
    
    Parameters:
    - value: int/float/Decimal - Currency value
    - is_int_with_cents: bool - Treat integers as cents (default: True)
    
    Returns:
    tuple - (integer_part, cents_part, is_negative)
    
    Raises:
    ValueError - For invalid currency values
    """

Usage Examples:

from num2words.currency import parse_currency_parts

# Float input
integer, cents, negative = parse_currency_parts(42.50)
# (42, 50, False)

# Integer input (treated as cents by default)
integer, cents, negative = parse_currency_parts(4250)
# (42, 50, False)

# Integer input (treated as whole units)
integer, cents, negative = parse_currency_parts(42, is_int_with_cents=False)
# (42, 0, False)

# Negative values
integer, cents, negative = parse_currency_parts(-42.50)
# (42, 50, True)

# String input
integer, cents, negative = parse_currency_parts("42.50")
# (42, 50, False)

Currency Internal Processing Methods

Internal methods used by the currency conversion system for formatting currency components.

def _money_verbose(self, number, currency):
    """
    Convert currency major unit to verbose word representation.
    
    Internal method used by to_currency() for the main currency amount.
    
    Parameters:
    - number: int - Major currency unit amount
    - currency: str - Currency code
    
    Returns:
    str - Verbose word representation of major currency unit
    """

def _cents_verbose(self, number, currency):
    """
    Convert currency minor unit to verbose word representation.
    
    Internal method used by to_currency() for cents/minor units when cents=True.
    
    Parameters:
    - number: int - Minor currency unit amount (cents)
    - currency: str - Currency code
    
    Returns:
    str - Verbose word representation of minor currency unit
    """

def _cents_terse(self, number, currency):
    """
    Convert currency minor unit to terse numeric representation.
    
    Internal method used by to_currency() for cents/minor units when cents=False.
    
    Parameters:
    - number: int - Minor currency unit amount (cents)
    - currency: str - Currency code
    
    Returns:
    str - Terse numeric representation (e.g., "05", "50")
    """

Usage Examples:

from num2words import CONVERTER_CLASSES

# These are internal methods used by to_currency()
en_converter = CONVERTER_CLASSES['en']

# Internal currency processing
money_part = en_converter._money_verbose(42, 'EUR')      # "forty-two"
cents_part = en_converter._cents_verbose(50, 'EUR')     # "fifty"
cents_terse = en_converter._cents_terse(50, 'EUR')      # "50"

# These methods are combined by to_currency() for final output
# "forty-two euros, fifty cents" (verbose)
# "forty-two euros, 50" (terse)

Currency Forms and Localization

Each language defines its own currency forms and pluralization rules.

# Currency forms structure (language-specific)
CURRENCY_FORMS = {
    'EUR': (('euro', 'euros'), ('cent', 'cents')),
    'USD': (('dollar', 'dollars'), ('cent', 'cents')),
    'GBP': (('pound', 'pounds'), ('penny', 'pence')),
    'JPY': (('yen', 'yen'), ('sen', 'sen')),
    # ... more currencies per language
}

# Currency adjectives (when supported)
CURRENCY_ADJECTIVES = {
    'EUR': 'European',
    'USD': 'American',
    'GBP': 'British',
    # ... more adjectives per language
}

Language-Specific Currency Examples:

# English currency forms
num2words(42.50, to='currency', lang='en', currency='USD')
# "forty-two dollars, fifty cents"

num2words(42.50, to='currency', lang='en', currency='GBP')
# "forty-two pounds, fifty pence"

# French currency forms
num2words(42.50, to='currency', lang='fr', currency='EUR')
# "quarante-deux euros, cinquante centimes"

# Spanish currency forms
num2words(42.50, to='currency', lang='es', currency='EUR')
# "cuarenta y dos euros, cincuenta céntimos"

# German currency forms
num2words(42.50, to='currency', lang='de', currency='EUR')
# "zweiundvierzig Euro, fünfzig Cent"

Pluralization Rules

Currency conversion uses language-specific pluralization rules.

def pluralize(self, n, forms):
    """
    Apply language-specific pluralization to currency forms.
    
    Parameters:
    - n: int - Number for pluralization decision
    - forms: tuple - (singular, plural) forms
    
    Returns:
    str - Correctly pluralized form
    """

Pluralization Examples:

# English pluralization
num2words(1.00, to='currency', currency='USD')
# "one dollar"  (singular)

num2words(2.00, to='currency', currency='USD')
# "two dollars"  (plural)

num2words(1.01, to='currency', currency='USD')
# "one dollar, one cent"  (singular forms)

num2words(1.02, to='currency', currency='USD')
# "one dollar, two cents"  (mixed singular/plural)

# Special cases in different languages
num2words(1.00, to='currency', lang='fr', currency='EUR')
# "un euro"  (French singular)

num2words(2.00, to='currency', lang='fr', currency='EUR')
# "deux euros"  (French plural)

Supported Currencies by Language

Different languages support different sets of currencies.

Common Currency Codes:

# Major world currencies
'EUR'  # Euro
'USD'  # US Dollar
'GBP'  # British Pound
'JPY'  # Japanese Yen
'CAD'  # Canadian Dollar
'AUD'  # Australian Dollar
'CHF'  # Swiss Franc
'CNY'  # Chinese Yuan
'SEK'  # Swedish Krona
'NOK'  # Norwegian Krone
'DKK'  # Danish Krone
'PLN'  # Polish Zloty
'CZK'  # Czech Koruna
'HUF'  # Hungarian Forint
'RUB'  # Russian Ruble
'INR'  # Indian Rupee
'BRL'  # Brazilian Real
'MXN'  # Mexican Peso
'ZAR'  # South African Rand
'KRW'  # South Korean Won

Testing Currency Support:

def test_currency_support(lang, currency):
    """Test if a currency is supported for a language."""
    try:
        result = num2words(42.50, to='currency', lang=lang, currency=currency)
        return True, result
    except NotImplementedError as e:
        return False, str(e)

# Test various combinations
support, result = test_currency_support('en', 'USD')
support, result = test_currency_support('fr', 'EUR')
support, result = test_currency_support('ja', 'JPY')

Currency Prefix Utilities

Helper functions for handling currency adjectives and prefixes.

def prefix_currency(prefix, base):
    """
    Add prefix to currency forms.
    
    Parameters:
    - prefix: str - Prefix to add (e.g., "European")
    - base: tuple - Base currency forms (singular, plural)
    
    Returns:
    tuple - Prefixed currency forms
    """

Usage Examples:

from num2words.currency import prefix_currency

# Add adjective prefix
base_forms = ('euro', 'euros')
prefixed = prefix_currency('European', base_forms)
# ('European euro', 'European euros')

# Use in currency conversion
num2words(42.50, to='currency', adjective=True)
# Uses prefixed forms when adjectives are defined

Integer vs. Float Currency Handling

Different handling for integer and float currency inputs.

# Integer inputs (interpreted as cents by default)
num2words(4250, to='currency')  # 4250 cents = 42.50 currency units
# "forty-two euros, fifty cents"

# Float inputs (direct value interpretation)
num2words(42.50, to='currency')
# "forty-two euros, fifty cents"

# Force integer interpretation as whole units
from num2words.currency import parse_currency_parts
integer, cents, negative = parse_currency_parts(42, is_int_with_cents=False)
# Then use with currency conversion

# Decimal precision handling
num2words(42.567, to='currency')  # Rounded to 2 decimal places
# "forty-two euros, fifty-seven cents"

Negative Currency Values

Handling of negative currency amounts.

# Negative amounts
num2words(-42.50, to='currency')
# "minus forty-two euros, fifty cents"

num2words(-42.50, to='currency', lang='fr')
# French negative prefix with currency

# Zero and negative cents
num2words(-0.50, to='currency')
# "minus fifty cents"

Error Handling

Currency conversion provides specific error handling for various scenarios.

# Unsupported currency for language
try:
    num2words(42.50, to='currency', lang='en', currency='UNSUPPORTED')
except NotImplementedError as e:
    print(f"Currency not supported: {e}")

# Invalid currency values
try:
    num2words("invalid", to='currency')
except ValueError as e:
    print(f"Invalid currency value: {e}")

# Check currency support before use
def safe_currency_convert(value, lang, currency):
    try:
        return num2words(value, to='currency', lang=lang, currency=currency)
    except NotImplementedError:
        # Fallback to default currency
        return num2words(value, to='currency', lang=lang, currency='EUR')

Advanced Currency Formatting

Custom formatting options for specific use cases.

# Long format with explicit separators
num2words(1234.56, to='currency', separator=' and ')
# "one thousand, two hundred and thirty-four euros and fifty-six cents"

# Terse format without verbose cents
num2words(1234.56, to='currency', cents=False)
# "one thousand, two hundred and thirty-four euros, 56"

# Cultural variations by language
num2words(1234.56, to='currency', lang='de')  # German formatting
num2words(1234.56, to='currency', lang='ja')  # Japanese formatting (if supported)
num2words(1234.56, to='currency', lang='ar')  # Arabic formatting (if supported)

Install with Tessl CLI

npx tessl i tessl/pypi-num2words

docs

base-converter.md

currency-conversion.md

index.md

language-support.md

number-conversion.md

utility-functions.md

tile.json