module documentation

Locale dependent formatting and parsing of numeric data.

The default locale for the functions in this module is determined by the following environment variables, in that order:

  • LC_NUMERIC,
  • LC_ALL, and
  • LANG
Unknown Field: copyright
  1. 2013-2021 by the Babel Team.
Unknown Field: license
BSD, see LICENSE for more details.
Class ​Number​Format​Error Exception raised when a string cannot be parsed into a number.
Function format​_currency Return formatted currency value.
Function format​_decimal Return the given decimal number formatted for a specific locale.
Function format​_number Return the given number formatted for a specific locale.
Function format​_percent Return formatted percent value for a specific locale.
Function format​_scientific Return value formatted in scientific notation for a specific locale.
Function get​_currency​_name Return the name used by the locale for the specified currency.
Function get​_currency​_symbol Return the symbol used by the locale for the specified currency.
Function get​_currency​_unit​_pattern No summary
Function get​_decimal​_symbol Return the symbol used by the locale to separate decimal fractions.
Function get​_minus​_sign​_symbol Return the plus sign symbol used by the current locale.
Function get​_plus​_sign​_symbol Return the plus sign symbol used by the current locale.
Function get​_territory​_currencies No summary
Function parse​_decimal Parse localized decimal string into a decimal.
Function parse​_number Parse localized number string into an integer.
Constant LC​_NUMERIC Undocumented
Constant NUMBER​_PATTERN Undocumented
Constant NUMBER​_TOKEN Undocumented
Constant PREFIX​_END Undocumented
Constant PREFIX​_PATTERN Undocumented
Constant SUFFIX​_PATTERN Undocumented
Variable number​_re Undocumented
Class ​Number​Pattern No class docstring; 0/9 instance variable, 3/9 methods documented
Class ​Unknown​Currency​Error Exception thrown when a currency is requested for which no data is available.
Class ​Unknown​Currency​Format​Error Exception raised when an unknown currency format is requested.
Function ​_format​_currency​_long​_name Undocumented
Function get​_currency​_precision Return currency's precision.
Function get​_decimal​_precision Return maximum precision of a decimal instance's fractional part.
Function get​_decimal​_quantum Return minimal quantum of a number, as defined by precision.
Function get​_exponential​_symbol Return the symbol used by the locale to separate mantissa and exponent.
Function get​_group​_symbol Return the symbol used by the locale to separate groups of thousands.
Function is​_currency Returns True only if a currency is recognized by Babel.
Function list​_currencies Return a set of normalized currency codes.
Function normalize​_currency Returns the normalized sting of any currency code.
Function parse​_grouping Parse primary and secondary digit grouping
Function parse​_pattern Parse number format patterns
Function validate​_currency Check the currency code is recognized by Babel.
def format_currency(number, currency, format=None, locale=LC_NUMERIC, currency_digits=True, format_type='standard', decimal_quantization=True, group_separator=True):

Return formatted currency value.

>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'US$\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\xa0\u20ac'

The format can also be specified explicitly. The currency is placed with the '¤' sign. As the sign gets repeated the format expands (¤ being the symbol, ¤¤ is the currency abbreviation and ¤¤¤ is the full name of the currency):

>>> format_currency(1099.98, 'EUR', u'¤¤ #,##0.00', locale='en_US')
u'EUR 1,099.98'
>>> format_currency(1099.98, 'EUR', u'#,##0.00 ¤¤¤', locale='en_US')
u'1,099.98 euros'

Currencies usually have a specific number of decimal digits. This function favours that information over the given format:

>>> format_currency(1099.98, 'JPY', locale='en_US')
u'\xa51,100'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
u'1.099,98'

However, the number of decimal digits can be overriden from the currency information, by setting the last parameter to False:

>>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
u'\xa51,099.98'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
u'1.099,98'

If a format is not specified the type of currency format to use from the locale can be specified:

>>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
u'\u20ac1,099.98'

When the given currency format type is not available, an exception is raised:

>>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
    ...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
>>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
u'$101299.98'
>>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
u'$101,299.98'

You can also pass format_type='name' to use long display names. The order of the number and currency name, along with the correct localized plural form of the currency name, is chosen according to locale:

>>> format_currency(1, 'USD', locale='en_US', format_type='name')
u'1.00 US dollar'
>>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
u'1,099.98 US dollars'
>>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
u'us ga dollar 1,099.98'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the decimal_quantization parameter:

>>> format_currency(1099.9876, 'USD', locale='en_US')
u'$1,099.99'
>>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
u'$1,099.9876'
Parameters
numberthe number to format
currencythe currency code
formatthe format string to use
localethe Locale object or locale identifier
currency​_digitsuse the currency's natural number of decimal digits
format​_typethe currency format type to use
decimal​_quantizationTruncate and round high-precision numbers to the format pattern. Defaults to True.
group​_separatorBoolean to switch group separator on/off in a locale's number format.
def format_decimal(number, format=None, locale=LC_NUMERIC, decimal_quantization=True, group_separator=True):

Return the given decimal number formatted for a specific locale.

>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(-1.2346, locale='en_US')
u'-1.235'
>>> format_decimal(1.2345, locale='sv_SE')
u'1,234'
>>> format_decimal(1.2345, locale='de')
u'1,234'

The appropriate thousands grouping and the decimal separator are used for each locale:

>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the decimal_quantization parameter:

>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
u'1.2346'
>>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
u'12345,67'
>>> format_decimal(12345.67, locale='en_US', group_separator=True)
u'12,345.67'
Parameters
numberthe number to format
format
localethe Locale object or locale identifier
decimal​_quantizationTruncate and round high-precision numbers to the format pattern. Defaults to True.
group​_separatorBoolean to switch group separator on/off in a locale's number format.
def format_number(number, locale=LC_NUMERIC):

Return the given number formatted for a specific locale.

>>> format_number(1099, locale='en_US')
u'1,099'
>>> format_number(1099, locale='de_DE')
u'1.099'
Deprecated since version 2.6.0: Use babel.numbers.format_decimal() instead.
Parameters
numberthe number to format
localethe Locale object or locale identifier
def format_percent(number, format=None, locale=LC_NUMERIC, decimal_quantization=True, group_separator=True):

Return formatted percent value for a specific locale.

>>> format_percent(0.34, locale='en_US')
u'34%'
>>> format_percent(25.1234, locale='en_US')
u'2,512%'
>>> format_percent(25.1234, locale='sv_SE')
u'2\xa0512\xa0%'

The format pattern can also be specified explicitly:

>>> format_percent(25.1234, u'#,##0‰', locale='en_US')
u'25,123‰'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the decimal_quantization parameter:

>>> format_percent(23.9876, locale='en_US')
u'2,399%'
>>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
u'2,398.76%'
>>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
u'22929112%'
>>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
u'22.929.112%'
Parameters
numberthe percent number to format
format
localethe Locale object or locale identifier
decimal​_quantizationTruncate and round high-precision numbers to the format pattern. Defaults to True.
group​_separatorBoolean to switch group separator on/off in a locale's number format.
def format_scientific(number, format=None, locale=LC_NUMERIC, decimal_quantization=True):

Return value formatted in scientific notation for a specific locale.

>>> format_scientific(10000, locale='en_US')
u'1E4'

The format pattern can also be specified explicitly:

>>> format_scientific(1234567, u'##0.##E00', locale='en_US')
u'1.23E06'

By default the locale is allowed to truncate and round a high-precision number by forcing its format pattern onto the decimal part. You can bypass this behavior with the decimal_quantization parameter:

>>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
u'1.23E3'
>>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
u'1.2349876E3'
Parameters
numberthe number to format
format
localethe Locale object or locale identifier
decimal​_quantizationTruncate and round high-precision numbers to the format pattern. Defaults to True.
def get_currency_name(currency, count=None, locale=LC_NUMERIC):

Return the name used by the locale for the specified currency.

>>> get_currency_name('USD', locale='en_US')
u'US Dollar'
New in version 0.9.4.
Parameters
currencythe currency code.
countthe optional count. If provided the currency name will be pluralized to that number if possible.
localethe Locale object or locale identifier.
def get_currency_symbol(currency, locale=LC_NUMERIC):

Return the symbol used by the locale for the specified currency.

>>> get_currency_symbol('USD', locale='en_US')
u'$'
Parameters
currencythe currency code.
localethe Locale object or locale identifier.
def get_currency_unit_pattern(currency, count=None, locale=LC_NUMERIC):

Return the unit pattern used for long display of a currency value for a given locale. This is a string containing {0} where the numeric part should be substituted and {1} where the currency long display name should be substituted.

>>> get_currency_unit_pattern('USD', locale='en_US', count=10)
u'{0} {1}'
New in version 2.7.0.
Parameters
currencythe currency code.
countthe optional count. If provided the unit pattern for that number will be returned.
localethe Locale object or locale identifier.
def get_decimal_symbol(locale=LC_NUMERIC):

Return the symbol used by the locale to separate decimal fractions.

>>> get_decimal_symbol('en_US')
u'.'
Parameters
localethe Locale object or locale identifier
def get_minus_sign_symbol(locale=LC_NUMERIC):

Return the plus sign symbol used by the current locale.

>>> get_minus_sign_symbol('en_US')
u'-'
Parameters
localethe Locale object or locale identifier
def get_plus_sign_symbol(locale=LC_NUMERIC):

Return the plus sign symbol used by the current locale.

>>> get_plus_sign_symbol('en_US')
u'+'
Parameters
localethe Locale object or locale identifier
def get_territory_currencies(territory, start_date=None, end_date=None, tender=True, non_tender=False, include_details=False):

Returns the list of currencies for the given territory that are valid for the given date range. In addition to that the currency database distinguishes between tender and non-tender currencies. By default only tender currencies are returned.

The return value is a list of all currencies roughly ordered by the time of when the currency became active. The longer the currency is being in use the more to the left of the list it will be.

The start date defaults to today. If no end date is given it will be the same as the start date. Otherwise a range can be defined. For instance this can be used to find the currencies in use in Austria between 1995 and 2011:

>>> from datetime import date
>>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
['ATS', 'EUR']

Likewise it's also possible to find all the currencies in use on a single date:

>>> get_territory_currencies('AT', date(1995, 1, 1))
['ATS']
>>> get_territory_currencies('AT', date(2011, 1, 1))
['EUR']

By default the return value only includes tender currencies. This however can be changed:

>>> get_territory_currencies('US')
['USD']
>>> get_territory_currencies('US', tender=False, non_tender=True,
...                          start_date=date(2014, 1, 1))
['USN', 'USS']
New in version 2.0.
Parameters
territorythe name of the territory to find the currency for.
start​_datethe start date. If not given today is assumed.
end​_datethe end date. If not given the start date is assumed.
tendercontrols whether tender currencies should be included.
non​_tendercontrols whether non-tender currencies should be included.
include​_detailsif set to True, instead of returning currency codes the return value will be dictionaries with detail information. In that case each dictionary will have the keys 'currency', 'from', 'to', and 'tender'.
def parse_decimal(string, locale=LC_NUMERIC, strict=False):

Parse localized decimal string into a decimal.

>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')
>>> parse_decimal('12 345,123', locale='ru')
Decimal('12345.123')

When the given string cannot be parsed, an exception is raised:

>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
    ...
NumberFormatError: '2,109,998' is not a valid decimal number

If strict is set to True and the given string contains a number formatted in an irregular way, an exception is raised:

>>> parse_decimal('30.00', locale='de', strict=True)
Traceback (most recent call last):
    ...
NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
>>> parse_decimal('0.00', locale='de', strict=True)
Traceback (most recent call last):
    ...
NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
Parameters
stringthe string to parse
localethe Locale object or locale identifier
strictcontrols whether numbers formatted in a weird way are accepted or rejected
Raises
NumberFormatErrorif the string can not be converted to a decimal number
def parse_number(string, locale=LC_NUMERIC):

Parse localized number string into an integer.

>>> parse_number('1,099', locale='en_US')
1099
>>> parse_number('1.099', locale='de_DE')
1099

When the given string cannot be parsed, an exception is raised:

>>> parse_number('1.099,98', locale='de')
Traceback (most recent call last):
    ...
NumberFormatError: '1.099,98' is not a valid number
Parameters
stringthe string to parse
localethe Locale object or locale identifier
Returns
the parsed number
Raises
NumberFormatErrorif the string can not be converted to a number
LC_NUMERIC =

Undocumented

Value
default_locale('LC_NUMERIC')
NUMBER_PATTERN =

Undocumented

Value
'(?P<number>%s*)'%NUMBER_TOKEN
NUMBER_TOKEN: str =

Undocumented

Value
'[0-9@#.,E+]'
PREFIX_END: str =

Undocumented

Value
'[^0-9@#.,]'
PREFIX_PATTERN =

Undocumented

Value
'(?P<prefix>(?:\'[^\']*\'|%s)*)'%PREFIX_END
SUFFIX_PATTERN: str =

Undocumented

Value
'(?P<suffix>.*)'
number_re =

Undocumented

def _format_currency_long_name(number, currency, format=None, locale=LC_NUMERIC, currency_digits=True, format_type='standard', decimal_quantization=True, group_separator=True):

Undocumented

def get_currency_precision(currency):

Return currency's precision.

Precision is the number of decimals found after the decimal point in the currency's format pattern.

New in version 2.5.0.
Parameters
currencythe currency code.
def get_decimal_precision(number):

Return maximum precision of a decimal instance's fractional part.

Precision is extracted from the fractional part only.

def get_decimal_quantum(precision):
Return minimal quantum of a number, as defined by precision.
def get_exponential_symbol(locale=LC_NUMERIC):

Return the symbol used by the locale to separate mantissa and exponent.

>>> get_exponential_symbol('en_US')
u'E'
Parameters
localethe Locale object or locale identifier
def get_group_symbol(locale=LC_NUMERIC):

Return the symbol used by the locale to separate groups of thousands.

>>> get_group_symbol('en_US')
u','
Parameters
localethe Locale object or locale identifier
def is_currency(currency, locale=None):

Returns True only if a currency is recognized by Babel.

This method always return a Boolean and never raise.

def list_currencies(locale=None):

Return a set of normalized currency codes.

New in version 2.5.0.
Parameters
localefilters returned currency codes by the provided locale. Expected to be a locale instance or code. If no locale is provided, returns the list of all currencies from all locales.
def normalize_currency(currency, locale=None):

Returns the normalized sting of any currency code.

Accepts a locale parameter for fined-grained validation, working as the one defined above in list_currencies() method.

Returns None if the currency is unknown to Babel.

def parse_grouping(p):

Parse primary and secondary digit grouping

>>> parse_grouping('##')
(1000, 1000)
>>> parse_grouping('#,###')
(3, 3)
>>> parse_grouping('#,####,###')
(3, 4)
def parse_pattern(pattern):
Parse number format patterns
def validate_currency(currency, locale=None):

Check the currency code is recognized by Babel.

Accepts a locale parameter for fined-grained validation, working as the one defined above in list_currencies() method.

Raises a UnknownCurrencyError exception if the currency is unknown to Babel.