Internationalization utilities for Python providing locale data, date/time/number formatting, and message catalog management
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Locale-aware number, decimal, currency, and percentage formatting with support for different numbering systems, compact notation, and precision control. Babel's number formatting leverages CLDR data to provide culturally appropriate number representations.
Format decimal numbers according to locale-specific conventions.
def format_decimal(
number,
format=None,
locale=None,
decimal_quantization=True,
group_separator=True,
*,
numbering_system='latn'
):
"""
Format a decimal number according to locale conventions.
Args:
number (int|float|Decimal|str): Number to format
format (str|NumberPattern, optional): Number format pattern or None for default
locale (Locale|str, optional): Target locale
decimal_quantization (bool): Whether to quantize decimal precision
group_separator (bool): Whether to include group separators
numbering_system (str): Numbering system ('latn', 'arab', etc.)
Returns:
str: Formatted decimal number
"""
def format_number(number, locale=None):
"""
Format a number according to locale (alias for format_decimal).
Args:
number (int|float|Decimal): Number to format
locale (Locale|str): Target locale
Returns:
str: Formatted number
"""Usage example:
from babel.numbers import format_decimal, format_number
from babel import Locale
from decimal import Decimal
# Basic number formatting
print(format_number(1234.56, Locale('en_US'))) # "1,234.56"
print(format_number(1234.56, Locale('de_DE'))) # "1.234,56"
print(format_number(1234.56, Locale('fr_FR'))) # "1 234,56"
# High precision decimals
decimal_num = Decimal('123456.789123')
print(format_decimal(decimal_num, locale='en_US')) # "123,456.789123"Format currency amounts with locale-appropriate symbols and positioning.
def format_currency(
number,
currency,
format=None,
locale=None,
currency_digits=True,
format_type='standard',
decimal_quantization=True,
group_separator=True,
*,
numbering_system='latn'
):
"""
Format a currency amount according to locale conventions.
Args:
number (int|float|Decimal|str): Amount to format
currency (str): Currency code (ISO 4217, e.g. 'USD', 'EUR')
format (str|NumberPattern, optional): Currency format pattern
locale (Locale|str, optional): Target locale
currency_digits (bool): Whether to use currency-specific decimal places
format_type (str): Format type ('standard', 'accounting', 'name')
decimal_quantization (bool): Whether to quantize to currency precision
group_separator (bool): Whether to include group separators
numbering_system (str): Numbering system
Returns:
str: Formatted currency amount
"""Usage example:
from babel.numbers import format_currency
from babel import Locale
amount = 1234.56
# Different locales and currencies
print(format_currency(amount, 'USD', locale='en_US')) # "$1,234.56"
print(format_currency(amount, 'EUR', locale='de_DE')) # "1.234,56 €"
print(format_currency(amount, 'JPY', locale='ja_JP')) # "¥1,235" (rounded to yen precision)
print(format_currency(amount, 'GBP', locale='en_GB')) # "£1,234.56"
# Accounting format (parentheses for negative)
print(format_currency(-123.45, 'USD', format_type='accounting', locale='en_US')) # "(123.45)"Format percentages with appropriate symbols and decimal places.
def format_percent(number, format=None, locale=None, numbering_system='latn'):
"""
Format a percentage according to locale conventions.
Args:
number (int|float|Decimal): Number to format as percentage (0.25 = 25%)
format (str, optional): Percent format pattern
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Formatted percentage
"""Usage example:
from babel.numbers import format_percent
print(format_percent(0.1234, locale='en_US')) # "12%"
print(format_percent(0.1234, locale='de_DE')) # "12 %"
print(format_percent(1.2345, locale='en_US')) # "123%"Format numbers in scientific notation according to locale conventions.
def format_scientific(number, format=None, locale=None, numbering_system='latn'):
"""
Format a number in scientific notation.
Args:
number (int|float|Decimal): Number to format
format (str, optional): Scientific format pattern
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Number in scientific notation
"""Usage example:
from babel.numbers import format_scientific
print(format_scientific(1234567, locale='en_US')) # "1.234567E6"
print(format_scientific(0.000123, locale='en_US')) # "1.23E-4"Format numbers in compact notation (e.g., 1.2K, 1.5M) for display in limited space.
def format_compact_decimal(number, format_type='short', fraction_digits=0,
locale=default_locale(), numbering_system="latn"):
"""
Format a number in compact notation.
Args:
number (int|float|Decimal): Number to format
format_type (str): Format type ('short', 'long')
fraction_digits (int): Number of fraction digits to display
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Compact formatted number
"""
def format_compact_currency(number, currency, format_type='short', fraction_digits=0,
locale=default_locale(), numbering_system="latn"):
"""
Format a currency amount in compact notation.
Args:
number (int|float|Decimal): Amount to format
currency (str): Currency code
format_type (str): Format type ('short', 'long')
fraction_digits (int): Number of fraction digits
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Compact formatted currency
"""Usage example:
from babel.numbers import format_compact_decimal, format_compact_currency
# Compact decimal formatting
print(format_compact_decimal(1234, locale='en_US')) # "1K"
print(format_compact_decimal(1234567, locale='en_US')) # "1M"
print(format_compact_decimal(1234, format_type='long', locale='en_US')) # "1 thousand"
# Compact currency formatting
print(format_compact_currency(1234567, 'USD', locale='en_US')) # "$1M"Access currency-related metadata and validation.
def list_currencies(locale=default_locale()):
"""
Get set of currency codes valid for locale.
Args:
locale (Locale|str): Target locale
Returns:
set[str]: Set of currency codes
"""
def validate_currency(currency, locale=default_locale()):
"""
Validate currency code for locale.
Args:
currency (str): Currency code to validate
locale (Locale|str): Target locale
Raises:
UnknownCurrencyError: If currency is invalid for locale
"""
def is_currency(currency, locale=default_locale()):
"""
Check if currency code is valid for locale.
Args:
currency (str): Currency code to check
locale (Locale|str): Target locale
Returns:
bool: True if currency is valid for locale
"""
def normalize_currency(currency, locale=default_locale()):
"""
Normalize currency code for locale.
Args:
currency (str): Currency code to normalize
locale (Locale|str): Target locale
Returns:
str|None: Normalized currency code or None if invalid
"""
def get_currency_name(currency, count=None, locale=default_locale()):
"""
Get display name for currency.
Args:
currency (str): Currency code
count (int|float, optional): Count for plural forms
locale (Locale|str): Target locale
Returns:
str: Currency display name
"""
def get_currency_symbol(currency, locale=default_locale()):
"""
Get currency symbol.
Args:
currency (str): Currency code
locale (Locale|str): Target locale
Returns:
str: Currency symbol
"""
def get_currency_precision(currency):
"""
Get default decimal precision for currency.
Args:
currency (str): Currency code
Returns:
int: Number of decimal places (e.g., 2 for USD, 0 for JPY)
"""
def get_currency_unit_pattern(currency, count=None, locale=default_locale()):
"""
Get currency unit pattern for count.
Args:
currency (str): Currency code
count (int|float, optional): Count for plural forms
locale (Locale|str): Target locale
Returns:
str: Currency unit pattern
"""Usage example:
from babel.numbers import (get_currency_name, get_currency_symbol,
get_currency_precision, is_currency)
print(get_currency_name('USD', locale='en_US')) # "US Dollar"
print(get_currency_symbol('USD', locale='en_US')) # "$"
print(get_currency_precision('USD')) # 2
print(get_currency_precision('JPY')) # 0
print(is_currency('USD', locale='en_US')) # TrueGet currencies used in specific territories/countries.
def get_territory_currencies(territory, start_date=None, end_date=None,
tender=True, non_tender=False, include_details=False):
"""
Get currencies used in territory.
Args:
territory (str): Territory code (e.g. 'US', 'DE')
start_date (datetime.date, optional): Start date filter
end_date (datetime.date, optional): End date filter
tender (bool): Include legal tender currencies
non_tender (bool): Include non-tender currencies
include_details (bool): Include detailed currency information
Returns:
list|dict: Currency codes or detailed currency information
"""Get locale-specific number formatting symbols.
def get_decimal_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get decimal separator symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Decimal separator (e.g., "." or ",")
"""
def get_group_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get thousands separator symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Group separator (e.g., "," or "." or " ")
"""
def get_plus_sign_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get plus sign symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Plus sign symbol
"""
def get_minus_sign_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get minus sign symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Minus sign symbol
"""
def get_exponential_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get exponential notation symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Exponential symbol (e.g., "E")
"""
def get_infinity_symbol(locale=default_locale(), numbering_system="latn"):
"""
Get infinity symbol.
Args:
locale (Locale|str): Target locale
numbering_system (str): Numbering system
Returns:
str: Infinity symbol (e.g., "∞")
"""Parse formatted number strings back to numeric values.
def parse_number(string, locale=default_locale()):
"""
Parse a formatted number string.
Args:
string (str): Formatted number string
locale (Locale|str): Source locale for parsing
Returns:
int|float: Parsed numeric value
Raises:
NumberFormatError: If parsing fails
"""
def parse_decimal(string, locale=default_locale(), strict=False):
"""
Parse a formatted decimal string.
Args:
string (str): Formatted decimal string
locale (Locale|str): Source locale for parsing
strict (bool): Whether to use strict parsing
Returns:
Decimal: Parsed decimal value
Raises:
NumberFormatError: If parsing fails
"""Utilities for working with decimal precision and quantization.
def get_decimal_precision(number):
"""
Get precision of a decimal number.
Args:
number (Decimal): Decimal number
Returns:
int: Number of decimal places
"""
def get_decimal_quantum(precision):
"""
Get quantum for decimal precision.
Args:
precision (int|Decimal): Precision value
Returns:
Decimal: Quantum for the precision
"""Parse and work with number format patterns.
def parse_pattern(pattern):
"""
Parse a number format pattern.
Args:
pattern (str): Number format pattern
Returns:
NumberPattern: Parsed pattern object
"""
def parse_grouping(pattern):
"""
Parse grouping information from pattern.
Args:
pattern (str): Number format pattern
Returns:
tuple[int, int]: Primary and secondary grouping sizes
"""
class NumberPattern:
"""
Represents a parsed number format pattern.
"""
def apply(self, value, locale, currency=None, numbering_system="latn",
decimal_quantization=True, group_separator=True):
"""
Apply this pattern to format a number.
Args:
value (int|float|Decimal): Number to format
locale (Locale|str): Target locale
currency (str, optional): Currency code for currency patterns
numbering_system (str): Numbering system
decimal_quantization (bool): Whether to quantize decimals
group_separator (bool): Whether to include group separators
Returns:
str: Formatted number
"""class UnknownCurrencyError(Exception):
"""Raised when an unknown currency code is used."""
class UnsupportedNumberingSystemError(Exception):
"""Raised when an unsupported numbering system is used."""
class UnknownCurrencyFormatError(Exception):
"""Raised when an unknown currency format type is used."""
class NumberFormatError(Exception):
"""Raised when number formatting or parsing fails."""LC_NUMERIC: str
"""Default numeric locale category constant."""Install with Tessl CLI
npx tessl i tessl/pypi-babel