return pattern.apply(number, locale)
-def format_currency(number, currency, format='standard', locale=LC_NUMERIC, currency_digits=True):
+class UnknownCurrencyFormatError(KeyError):
+ """Exception raised when an unknown currency format is requested."""
+
+
+def format_currency(number, currency, format=None, locale=LC_NUMERIC,
+ currency_digits=True, format_type='standard'):
u"""Return formatted currency value.
>>> format_currency(1099.98, 'USD', locale='en_US')
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
- The pattern can also be specified explicitly. The currency is
+ 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, '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"
+
:param number: the number to format
:param currency: the currency code
+ :param format: the format string to use
:param locale: the `Locale` object or locale identifier
:param currency_digits: use the currency's number of decimal digits
+ :param format_type: the currency format type to use
"""
locale = Locale.parse(locale)
- pattern = parse_pattern(locale.currency_formats.get(format, format))
+ if format:
+ pattern = parse_pattern(format)
+ else:
+ try:
+ pattern = locale.currency_formats[format_type]
+ except KeyError:
+ raise UnknownCurrencyFormatError("%r is not a known currency format"
+ " type" % format_type)
if currency_digits:
fractions = get_global('currency_fractions')
try:
== u'EUR 1,099.98')
assert (numbers.format_currency(1099.98, 'EUR', locale='nl_NL')
!= numbers.format_currency(-1099.98, 'EUR', locale='nl_NL'))
+ assert (numbers.format_currency(1099.98, 'USD', format=None,
+ locale='en_US')
+ == u'$1,099.98')
+
+
+def test_format_currency_format_type():
+ assert (numbers.format_currency(1099.98, 'USD', locale='en_US',
+ format_type="standard")
+ == u'$1,099.98')
+
+ assert (numbers.format_currency(1099.98, 'USD', locale='en_US',
+ format_type="accounting")
+ == u'$1,099.98')
+
+ with pytest.raises(numbers.UnknownCurrencyFormatError) as excinfo:
+ numbers.format_currency(1099.98, 'USD', locale='en_US',
+ format_type='unknown')
+ assert excinfo.value.args[0] == "'unknown' is not a known currency format type"
assert (numbers.format_currency(1099.98, 'JPY', locale='en_US')
== u'\xa51,100')