Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/babel/numbers.py: 15%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2babel.numbers
3~~~~~~~~~~~~~
5Locale dependent formatting and parsing of numeric data.
7The default locale for the functions in this module is determined by the
8following environment variables, in that order:
10 * ``LC_MONETARY`` for currency related functions,
11 * ``LC_NUMERIC``, and
12 * ``LC_ALL``, and
13 * ``LANG``
15:copyright: (c) 2013-2026 by the Babel Team.
16:license: BSD, see LICENSE for more details.
17"""
19# TODO:
20# Padding and rounding increments in pattern:
21# - https://www.unicode.org/reports/tr35/ (Appendix G.6)
22from __future__ import annotations
24import datetime
25import decimal
26import re
27import warnings
28from typing import Any, Literal, cast, overload
30from babel.core import Locale, default_locale, get_global
31from babel.localedata import LocaleDataDict
33LC_MONETARY = default_locale(('LC_MONETARY', 'LC_NUMERIC'))
34LC_NUMERIC = default_locale('LC_NUMERIC')
37class UnknownCurrencyError(Exception):
38 """Exception thrown when a currency is requested for which no data is available."""
40 def __init__(self, identifier: str) -> None:
41 """Create the exception.
42 :param identifier: the identifier string of the unsupported currency
43 """
44 Exception.__init__(self, f"Unknown currency {identifier!r}.")
46 #: The identifier of the locale that could not be found.
47 self.identifier = identifier
50def list_currencies(locale: Locale | str | None = None) -> set[str]:
51 """Return a `set` of normalized currency codes.
53 .. versionadded:: 2.5.0
55 :param locale: filters returned currency codes by the provided locale.
56 Expected to be a locale instance or code. If no locale is
57 provided, returns the list of all currencies from all
58 locales.
59 """
60 # Get locale-scoped currencies.
61 if locale:
62 return set(Locale.parse(locale).currencies)
63 return set(get_global('all_currencies'))
66def validate_currency(currency: str, locale: Locale | str | None = None) -> None:
67 """Check the currency code is recognized by Babel.
69 Accepts a ``locale`` parameter for fined-grained validation, working as
70 the one defined above in ``list_currencies()`` method.
72 Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel.
73 """
74 if currency not in list_currencies(locale):
75 raise UnknownCurrencyError(currency)
78def is_currency(currency: str, locale: Locale | str | None = None) -> bool:
79 """Returns `True` only if a currency is recognized by Babel.
81 This method always return a Boolean and never raise.
82 """
83 if not currency or not isinstance(currency, str):
84 return False
85 try:
86 validate_currency(currency, locale)
87 except UnknownCurrencyError:
88 return False
89 return True
92def normalize_currency(currency: str, locale: Locale | str | None = None) -> str | None:
93 """Returns the normalized identifier of any currency code.
95 Accepts a ``locale`` parameter for fined-grained validation, working as
96 the one defined above in ``list_currencies()`` method.
98 Returns None if the currency is unknown to Babel.
99 """
100 if isinstance(currency, str):
101 currency = currency.upper()
102 if not is_currency(currency, locale):
103 return None
104 return currency
107def get_currency_name(
108 currency: str,
109 count: float | decimal.Decimal | None = None,
110 locale: Locale | str | None = None,
111) -> str:
112 """Return the name used by the locale for the specified currency.
114 >>> get_currency_name('USD', locale='en_US')
115 'US Dollar'
117 .. versionadded:: 0.9.4
119 :param currency: the currency code.
120 :param count: the optional count. If provided the currency name
121 will be pluralized to that number if possible.
122 :param locale: the `Locale` object or locale identifier.
123 Defaults to the system currency locale or numeric locale.
124 """
125 loc = Locale.parse(locale or LC_MONETARY)
126 if count is not None:
127 try:
128 plural_form = loc.plural_form(count)
129 except (OverflowError, ValueError):
130 plural_form = 'other'
131 plural_names = loc._data['currency_names_plural']
132 if currency in plural_names:
133 currency_plural_names = plural_names[currency]
134 if plural_form in currency_plural_names:
135 return currency_plural_names[plural_form]
136 if 'other' in currency_plural_names:
137 return currency_plural_names['other']
138 return loc.currencies.get(currency, currency)
141def get_currency_symbol(currency: str, locale: Locale | str | None = None) -> str:
142 """Return the symbol used by the locale for the specified currency.
144 >>> get_currency_symbol('USD', locale='en_US')
145 '$'
147 :param currency: the currency code.
148 :param locale: the `Locale` object or locale identifier.
149 Defaults to the system currency locale or numeric locale.
150 """
151 return Locale.parse(locale or LC_MONETARY).currency_symbols.get(currency, currency)
154def get_currency_precision(currency: str) -> int:
155 """Return currency's precision.
157 Precision is the number of decimals found after the decimal point in the
158 currency's format pattern.
160 .. versionadded:: 2.5.0
162 :param currency: the currency code.
163 """
164 precisions = get_global('currency_fractions')
165 return precisions.get(currency, precisions['DEFAULT'])[0]
168def get_currency_unit_pattern(
169 currency: str, # TODO: unused?!
170 count: float | decimal.Decimal | None = None,
171 locale: Locale | str | None = None,
172) -> str:
173 """
174 Return the unit pattern used for long display of a currency value
175 for a given locale.
176 This is a string containing ``{0}`` where the numeric part
177 should be substituted and ``{1}`` where the currency long display
178 name should be substituted.
180 >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
181 '{0} {1}'
183 .. versionadded:: 2.7.0
185 :param currency: the currency code.
186 :param count: the optional count. If provided the unit
187 pattern for that number will be returned.
188 :param locale: the `Locale` object or locale identifier.
189 Defaults to the system currency locale or numeric locale.
190 """
191 loc = Locale.parse(locale or LC_MONETARY)
192 if count is not None:
193 plural_form = loc.plural_form(count)
194 try:
195 return loc._data['currency_unit_patterns'][plural_form]
196 except LookupError:
197 # Fall back to 'other'
198 pass
200 return loc._data['currency_unit_patterns']['other']
203@overload
204def get_territory_currencies(
205 territory: str,
206 start_date: datetime.date | None = ...,
207 end_date: datetime.date | None = ...,
208 tender: bool = ...,
209 non_tender: bool = ...,
210 include_details: Literal[False] = ...,
211) -> list[str]: ... # pragma: no cover
214@overload
215def get_territory_currencies(
216 territory: str,
217 start_date: datetime.date | None = ...,
218 end_date: datetime.date | None = ...,
219 tender: bool = ...,
220 non_tender: bool = ...,
221 include_details: Literal[True] = ...,
222) -> list[dict[str, Any]]: ... # pragma: no cover
225def get_territory_currencies(
226 territory: str,
227 start_date: datetime.date | None = None,
228 end_date: datetime.date | None = None,
229 tender: bool = True,
230 non_tender: bool = False,
231 include_details: bool = False,
232) -> list[str] | list[dict[str, Any]]:
233 """Returns the list of currencies for the given territory that are valid for
234 the given date range. In addition to that the currency database
235 distinguishes between tender and non-tender currencies. By default only
236 tender currencies are returned.
238 The return value is a list of all currencies roughly ordered by the time
239 of when the currency became active. The longer the currency is being in
240 use the more to the left of the list it will be.
242 The start date defaults to today. If no end date is given it will be the
243 same as the start date. Otherwise a range can be defined. For instance
244 this can be used to find the currencies in use in Austria between 1995 and
245 2011:
247 >>> from datetime import date
248 >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
249 ['ATS', 'EUR']
251 Likewise it's also possible to find all the currencies in use on a
252 single date:
254 >>> get_territory_currencies('AT', date(1995, 1, 1))
255 ['ATS']
256 >>> get_territory_currencies('AT', date(2011, 1, 1))
257 ['EUR']
259 By default the return value only includes tender currencies. This
260 however can be changed:
262 >>> get_territory_currencies('US')
263 ['USD']
264 >>> get_territory_currencies('US', tender=False, non_tender=True,
265 ... start_date=date(2014, 1, 1))
266 ['USN', 'USS']
268 .. versionadded:: 2.0
270 :param territory: the name of the territory to find the currency for.
271 :param start_date: the start date. If not given today is assumed.
272 :param end_date: the end date. If not given the start date is assumed.
273 :param tender: controls whether tender currencies should be included.
274 :param non_tender: controls whether non-tender currencies should be
275 included.
276 :param include_details: if set to `True`, instead of returning currency
277 codes the return value will be dictionaries
278 with detail information. In that case each
279 dictionary will have the keys ``'currency'``,
280 ``'from'``, ``'to'``, and ``'tender'``.
281 """
282 currencies = get_global('territory_currencies')
283 if start_date is None:
284 start_date = datetime.date.today()
285 elif isinstance(start_date, datetime.datetime):
286 start_date = start_date.date()
287 if end_date is None:
288 end_date = start_date
289 elif isinstance(end_date, datetime.datetime):
290 end_date = end_date.date()
292 curs = currencies.get(territory.upper(), ())
293 # TODO: validate that the territory exists
295 def _is_active(start, end):
296 return (start is None or start <= end_date) and (end is None or end >= start_date)
298 result = []
299 for currency_code, start, end, is_tender in curs:
300 if start:
301 start = datetime.date(*start)
302 if end:
303 end = datetime.date(*end)
304 if ((is_tender and tender) or (not is_tender and non_tender)) and _is_active(
305 start,
306 end,
307 ):
308 if include_details:
309 result.append(
310 {
311 'currency': currency_code,
312 'from': start,
313 'to': end,
314 'tender': is_tender,
315 },
316 )
317 else:
318 result.append(currency_code)
320 return result
323def _get_numbering_system(
324 locale: Locale,
325 numbering_system: Literal["default"] | str = "latn",
326) -> str:
327 if numbering_system == "default":
328 return locale.default_numbering_system
329 else:
330 return numbering_system
333def _get_number_symbols(
334 locale: Locale,
335 *,
336 numbering_system: Literal["default"] | str = "latn",
337) -> LocaleDataDict:
338 numbering_system = _get_numbering_system(locale, numbering_system)
339 try:
340 return locale.number_symbols[numbering_system]
341 except KeyError as error:
342 raise UnsupportedNumberingSystemError(
343 f"Unknown numbering system {numbering_system} for Locale {locale}.",
344 ) from error
347class UnsupportedNumberingSystemError(Exception):
348 """Exception thrown when an unsupported numbering system is requested for the given Locale."""
350 pass
353def get_decimal_symbol(
354 locale: Locale | str | None = None,
355 *,
356 numbering_system: Literal["default"] | str = "latn",
357) -> str:
358 """Return the symbol used by the locale to separate decimal fractions.
360 >>> get_decimal_symbol('en_US')
361 '.'
362 >>> get_decimal_symbol('ar_EG', numbering_system='default')
363 '٫'
364 >>> get_decimal_symbol('ar_EG', numbering_system='latn')
365 '.'
367 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
368 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
369 The special value "default" will use the default numbering system of the locale.
370 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
371 """
372 locale = Locale.parse(locale or LC_NUMERIC)
373 return _get_number_symbols(locale, numbering_system=numbering_system).get('decimal', '.')
376def get_plus_sign_symbol(
377 locale: Locale | str | None = None,
378 *,
379 numbering_system: Literal["default"] | str = "latn",
380) -> str:
381 """Return the plus sign symbol used by the current locale.
383 >>> get_plus_sign_symbol('en_US')
384 '+'
385 >>> get_plus_sign_symbol('ar_EG', numbering_system='default')
386 '\\u061c+'
387 >>> get_plus_sign_symbol('ar_EG', numbering_system='latn')
388 '\\u200e+'
390 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
391 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
392 The special value "default" will use the default numbering system of the locale.
393 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
394 """
395 locale = Locale.parse(locale or LC_NUMERIC)
396 return _get_number_symbols(locale, numbering_system=numbering_system).get('plusSign', '+')
399def get_minus_sign_symbol(
400 locale: Locale | str | None = None,
401 *,
402 numbering_system: Literal["default"] | str = "latn",
403) -> str:
404 """Return the plus sign symbol used by the current locale.
406 >>> get_minus_sign_symbol('en_US')
407 '-'
408 >>> get_minus_sign_symbol('ar_EG', numbering_system='default')
409 '\\u061c-'
410 >>> get_minus_sign_symbol('ar_EG', numbering_system='latn')
411 '\\u200e-'
413 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
414 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
415 The special value "default" will use the default numbering system of the locale.
416 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
417 """
418 locale = Locale.parse(locale or LC_NUMERIC)
419 return _get_number_symbols(locale, numbering_system=numbering_system).get('minusSign', '-')
422def get_exponential_symbol(
423 locale: Locale | str | None = None,
424 *,
425 numbering_system: Literal["default"] | str = "latn",
426) -> str:
427 """Return the symbol used by the locale to separate mantissa and exponent.
429 >>> get_exponential_symbol('en_US')
430 'E'
431 >>> get_exponential_symbol('ar_EG', numbering_system='default')
432 'أس'
433 >>> get_exponential_symbol('ar_EG', numbering_system='latn')
434 'E'
436 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
437 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
438 The special value "default" will use the default numbering system of the locale.
439 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
440 """
441 locale = Locale.parse(locale or LC_NUMERIC)
442 return _get_number_symbols(locale, numbering_system=numbering_system).get('exponential', 'E') # fmt: skip
445def get_group_symbol(
446 locale: Locale | str | None = None,
447 *,
448 numbering_system: Literal["default"] | str = "latn",
449) -> str:
450 """Return the symbol used by the locale to separate groups of thousands.
452 >>> get_group_symbol('en_US')
453 ','
454 >>> get_group_symbol('ar_EG', numbering_system='default')
455 '٬'
456 >>> get_group_symbol('ar_EG', numbering_system='latn')
457 ','
459 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
460 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
461 The special value "default" will use the default numbering system of the locale.
462 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
463 """
464 locale = Locale.parse(locale or LC_NUMERIC)
465 return _get_number_symbols(locale, numbering_system=numbering_system).get('group', ',')
468def get_infinity_symbol(
469 locale: Locale | str | None = None,
470 *,
471 numbering_system: Literal["default"] | str = "latn",
472) -> str:
473 """Return the symbol used by the locale to represent infinity.
475 >>> get_infinity_symbol('en_US')
476 '∞'
477 >>> get_infinity_symbol('ar_EG', numbering_system='default')
478 '∞'
479 >>> get_infinity_symbol('ar_EG', numbering_system='latn')
480 '∞'
482 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
483 :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
484 The special value "default" will use the default numbering system of the locale.
485 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
486 """
487 locale = Locale.parse(locale or LC_NUMERIC)
488 return _get_number_symbols(locale, numbering_system=numbering_system).get('infinity', '∞')
491def format_number(
492 number: float | decimal.Decimal | str,
493 locale: Locale | str | None = None,
494) -> str:
495 """Return the given number formatted for a specific locale.
497 >>> format_number(1099, locale='en_US') # doctest: +SKIP
498 '1,099'
499 >>> format_number(1099, locale='de_DE') # doctest: +SKIP
500 '1.099'
502 .. deprecated:: 2.6.0
504 Use babel.numbers.format_decimal() instead.
506 :param number: the number to format
507 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
510 """
511 warnings.warn(
512 'Use babel.numbers.format_decimal() instead.',
513 DeprecationWarning,
514 stacklevel=2,
515 )
516 return format_decimal(number, locale=locale)
519def get_decimal_precision(number: decimal.Decimal) -> int:
520 """Return maximum precision of a decimal instance's fractional part.
522 Precision is extracted from the fractional part only.
523 """
524 # Copied from: https://github.com/mahmoud/boltons/pull/59
525 assert isinstance(number, decimal.Decimal)
526 decimal_tuple = number.normalize().as_tuple()
527 # Note: DecimalTuple.exponent can be 'n' (qNaN), 'N' (sNaN), or 'F' (Infinity)
528 if not isinstance(decimal_tuple.exponent, int) or decimal_tuple.exponent >= 0:
529 return 0
530 return abs(decimal_tuple.exponent)
533def get_decimal_quantum(precision: int | decimal.Decimal) -> decimal.Decimal:
534 """Return minimal quantum of a number, as defined by precision."""
535 assert isinstance(precision, (int, decimal.Decimal))
536 return decimal.Decimal(10) ** (-precision)
539def format_decimal(
540 number: float | decimal.Decimal | str,
541 format: str | NumberPattern | None = None,
542 locale: Locale | str | None = None,
543 decimal_quantization: bool = True,
544 group_separator: bool = True,
545 *,
546 numbering_system: Literal["default"] | str = "latn",
547) -> str:
548 """Return the given decimal number formatted for a specific locale.
550 >>> format_decimal(1.2345, locale='en_US')
551 '1.234'
552 >>> format_decimal(1.2346, locale='en_US')
553 '1.235'
554 >>> format_decimal(-1.2346, locale='en_US')
555 '-1.235'
556 >>> format_decimal(1.2345, locale='sv_SE')
557 '1,234'
558 >>> format_decimal(1.2345, locale='de')
559 '1,234'
560 >>> format_decimal(1.2345, locale='ar_EG', numbering_system='default')
561 '1٫234'
562 >>> format_decimal(1.2345, locale='ar_EG', numbering_system='latn')
563 '1.234'
565 The appropriate thousands grouping and the decimal separator are used for
566 each locale:
568 >>> format_decimal(12345.5, locale='en_US')
569 '12,345.5'
571 By default the locale is allowed to truncate and round a high-precision
572 number by forcing its format pattern onto the decimal part. You can bypass
573 this behavior with the `decimal_quantization` parameter:
575 >>> format_decimal(1.2346, locale='en_US')
576 '1.235'
577 >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
578 '1.2346'
579 >>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
580 '12345,67'
581 >>> format_decimal(12345.67, locale='en_US', group_separator=True)
582 '12,345.67'
584 :param number: the number to format
585 :param format:
586 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
587 :param decimal_quantization: Truncate and round high-precision numbers to
588 the format pattern. Defaults to `True`.
589 :param group_separator: Boolean to switch group separator on/off in a locale's
590 number format.
591 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
592 The special value "default" will use the default numbering system of the locale.
593 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
594 """
595 locale = Locale.parse(locale or LC_NUMERIC)
596 if format is None:
597 format = locale.decimal_formats[format]
598 pattern = parse_pattern(format)
599 return pattern.apply(
600 number,
601 locale,
602 decimal_quantization=decimal_quantization,
603 group_separator=group_separator,
604 numbering_system=numbering_system,
605 )
608def format_compact_decimal(
609 number: float | decimal.Decimal | str,
610 *,
611 format_type: Literal["short", "long"] = "short",
612 locale: Locale | str | None = None,
613 fraction_digits: int = 0,
614 numbering_system: Literal["default"] | str = "latn",
615) -> str:
616 """Return the given decimal number formatted for a specific locale in compact form.
618 >>> format_compact_decimal(12345, format_type="short", locale='en_US')
619 '12K'
620 >>> format_compact_decimal(12345, format_type="long", locale='en_US')
621 '12 thousand'
622 >>> format_compact_decimal(12345, format_type="short", locale='en_US', fraction_digits=2)
623 '12.34K'
624 >>> format_compact_decimal(1234567, format_type="short", locale="ja_JP")
625 '123万'
626 >>> format_compact_decimal(2345678, format_type="long", locale="mk")
627 '2 милиони'
628 >>> format_compact_decimal(21000000, format_type="long", locale="mk")
629 '21 милион'
630 >>> format_compact_decimal(12345, format_type="short", locale='ar_EG', fraction_digits=2, numbering_system='default')
631 '12٫34\\xa0ألف'
633 :param number: the number to format
634 :param format_type: Compact format to use ("short" or "long")
635 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
636 :param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
637 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
638 The special value "default" will use the default numbering system of the locale.
639 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
640 """
641 locale = Locale.parse(locale or LC_NUMERIC)
642 compact_format = locale.compact_decimal_formats[format_type]
643 number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
644 # Did not find a format, fall back.
645 if format is None:
646 format = locale.decimal_formats[None]
647 pattern = parse_pattern(format)
648 return pattern.apply(
649 number,
650 locale,
651 decimal_quantization=False,
652 numbering_system=numbering_system,
653 )
656def _get_compact_format(
657 number: float | decimal.Decimal | str,
658 compact_format: LocaleDataDict,
659 locale: Locale,
660 fraction_digits: int,
661) -> tuple[decimal.Decimal, NumberPattern | None]:
662 """Returns the number after dividing by the unit and the format pattern to use.
663 The algorithm is described here:
664 https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats.
665 """
666 if not isinstance(number, decimal.Decimal):
667 number = decimal.Decimal(str(number))
668 if number.is_nan() or number.is_infinite():
669 return number, None
670 format = None
671 magnitudes = sorted([int(m) for m in compact_format["other"]], reverse=True)
672 abs_number = abs(number)
673 for index, magnitude in enumerate(magnitudes):
674 if abs_number < magnitude:
675 continue
676 # check the pattern using "other" as the amount
677 format = compact_format["other"][str(magnitude)]
678 pattern = parse_pattern(format).pattern
679 # if the pattern is "0", we do not divide the number
680 if pattern == "0":
681 break
682 # otherwise, we need to divide the number by the magnitude but remove zeros
683 # equal to the number of 0's in the pattern minus 1
684 divisor = magnitude // (10 ** (pattern.count("0") - 1))
685 scaled = cast(decimal.Decimal, number / divisor)
686 # round to the number of fraction digits requested
687 rounded = round(scaled, fraction_digits)
688 # Rounding can carry the value up into the next magnitude, e.g.
689 # 999_999 would otherwise render as "1000K". The CLDR algorithm
690 # selects the pattern from the rounded value, so redo the lookup
691 # one magnitude up to get "1M" instead.
692 if index > 0 and abs(rounded) * divisor >= magnitudes[index - 1]:
693 bumped = decimal.Decimal(magnitudes[index - 1]).copy_sign(number)
694 return _get_compact_format(bumped, compact_format, locale, fraction_digits)
695 # Select the plural form from the displayed number. Optional trailing
696 # fractional zeros are not rendered by the compact pattern.
697 plural_number = abs(rounded).normalize()
698 plural_form = locale.plural_form(plural_number)
699 if plural_form not in compact_format:
700 plural_form = "other"
701 if rounded == 1 and str(magnitude) in compact_format.get("1", {}):
702 plural_form = "1"
703 if str(magnitude) not in compact_format[plural_form]:
704 plural_form = "other" # fall back to other as the implicit default
705 format = compact_format[plural_form][str(magnitude)]
706 number = rounded
707 break
708 return number, format
711class UnknownCurrencyFormatError(KeyError):
712 """Exception raised when an unknown currency format is requested."""
715def format_currency(
716 number: float | decimal.Decimal | str,
717 currency: str,
718 format: str | NumberPattern | None = None,
719 locale: Locale | str | None = None,
720 currency_digits: bool = True,
721 format_type: Literal["name", "standard", "accounting"] = "standard",
722 decimal_quantization: bool = True,
723 group_separator: bool = True,
724 *,
725 numbering_system: Literal["default"] | str = "latn",
726) -> str:
727 """Return formatted currency value.
729 >>> format_currency(1099.98, 'USD', locale='en_US')
730 '$1,099.98'
731 >>> format_currency(1099.98, 'USD', locale='es_CO')
732 'US$1.099,98'
733 >>> format_currency(1099.98, 'EUR', locale='de_DE')
734 '1.099,98\\xa0\\u20ac'
735 >>> format_currency(1099.98, 'EGP', locale='ar_EG', numbering_system='default')
736 '\\u200f1٬099٫98\\xa0ج.م.\\u200f'
738 The format can also be specified explicitly. The currency is
739 placed with the '¤' sign. As the sign gets repeated the format
740 expands (¤ being the symbol, ¤¤ is the currency abbreviation and
741 ¤¤¤ is the full name of the currency):
743 >>> format_currency(1099.98, 'EUR', '\\xa4\\xa4 #,##0.00', locale='en_US')
744 'EUR 1,099.98'
745 >>> format_currency(1099.98, 'EUR', '#,##0.00 \\xa4\\xa4\\xa4', locale='en_US')
746 '1,099.98 euros'
748 Currencies usually have a specific number of decimal digits. This function
749 favours that information over the given format:
751 >>> format_currency(1099.98, 'JPY', locale='en_US')
752 '\\xa51,100'
753 >>> format_currency(1099.98, 'COP', '#,##0.00', locale='es_ES')
754 '1.100'
756 However, the number of decimal digits can be overridden from the currency
757 information, by setting the last parameter to ``False``:
759 >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
760 '\\xa51,099.98'
761 >>> format_currency(1099.98, 'COP', '#,##0.00', locale='es_ES', currency_digits=False)
762 '1.099,98'
764 If a format is not specified the type of currency format to use
765 from the locale can be specified:
767 >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
768 '\\u20ac1,099.98'
770 When the given currency format type is not available, an exception is
771 raised:
773 >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
774 Traceback (most recent call last):
775 ...
776 UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
778 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
779 '$101299.98'
781 >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
782 '$101,299.98'
784 You can also pass format_type='name' to use long display names. The order of
785 the number and currency name, along with the correct localized plural form
786 of the currency name, is chosen according to locale:
788 >>> format_currency(1, 'USD', locale='en_US', format_type='name')
789 '1.00 US dollar'
790 >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
791 '1,099.98 US dollars'
792 >>> format_currency(1099.98, 'USD', locale='my', format_type='name')
793 'အမေရိကန် ဒေါ်လာ 1,099.98'
795 By default the locale is allowed to truncate and round a high-precision
796 number by forcing its format pattern onto the decimal part. You can bypass
797 this behavior with the `decimal_quantization` parameter:
799 >>> format_currency(1099.9876, 'USD', locale='en_US')
800 '$1,099.99'
801 >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
802 '$1,099.9876'
804 :param number: the number to format
805 :param currency: the currency code
806 :param format: the format string to use
807 :param locale: the `Locale` object or locale identifier.
808 Defaults to the system currency locale or numeric locale.
809 :param currency_digits: use the currency's natural number of decimal digits
810 :param format_type: the currency format type to use
811 :param decimal_quantization: Truncate and round high-precision numbers to
812 the format pattern. Defaults to `True`.
813 :param group_separator: Boolean to switch group separator on/off in a locale's
814 number format.
815 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
816 The special value "default" will use the default numbering system of the locale.
817 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
818 """
819 locale = Locale.parse(locale or LC_MONETARY)
821 if format_type == 'name':
822 return _format_currency_long_name(
823 number,
824 currency,
825 locale=locale,
826 format=format,
827 currency_digits=currency_digits,
828 decimal_quantization=decimal_quantization,
829 group_separator=group_separator,
830 numbering_system=numbering_system,
831 )
833 if format:
834 pattern = parse_pattern(format)
835 else:
836 try:
837 pattern = locale.currency_formats[format_type]
838 except KeyError:
839 raise UnknownCurrencyFormatError(
840 f"{format_type!r} is not a known currency format type",
841 ) from None
843 return pattern.apply(
844 number,
845 locale,
846 currency=currency,
847 currency_digits=currency_digits,
848 decimal_quantization=decimal_quantization,
849 group_separator=group_separator,
850 numbering_system=numbering_system,
851 )
854def _format_currency_long_name(
855 number: float | decimal.Decimal | str,
856 currency: str,
857 *,
858 locale: Locale,
859 format: str | NumberPattern | None,
860 currency_digits: bool,
861 decimal_quantization: bool,
862 group_separator: bool,
863 numbering_system: Literal["default"] | str,
864) -> str:
865 # Algorithm described here:
866 # https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
868 # Step 1.
869 # There are no examples of items with explicit count (0 or 1) in current
870 # locale data. So there is no point implementing that.
871 # Step 2.
873 # Correct number to numeric type, important for looking up plural rules:
874 number_n = float(number) if isinstance(number, str) else number
876 # Step 3.
877 unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
879 # Step 4.
880 display_name = get_currency_name(currency, count=number_n, locale=locale)
882 # Step 5.
883 if not format:
884 format = locale.decimal_formats[None]
886 pattern = parse_pattern(format)
888 number_part = pattern.apply(
889 number,
890 locale,
891 currency=currency,
892 currency_digits=currency_digits,
893 decimal_quantization=decimal_quantization,
894 group_separator=group_separator,
895 numbering_system=numbering_system,
896 )
898 return unit_pattern.format(number_part, display_name)
901def format_compact_currency(
902 number: float | decimal.Decimal | str,
903 currency: str,
904 *,
905 format_type: Literal["short"] = "short",
906 locale: Locale | str | None = None,
907 fraction_digits: int = 0,
908 numbering_system: Literal["default"] | str = "latn",
909) -> str:
910 """Format a number as a currency value in compact form.
912 >>> format_compact_currency(12345, 'USD', locale='en_US')
913 '$12K'
914 >>> format_compact_currency(123456789, 'USD', locale='en_US', fraction_digits=2)
915 '$123.46M'
916 >>> format_compact_currency(123456789, 'EUR', locale='de_DE', fraction_digits=1)
917 '123,5\\xa0Mio.\\xa0€'
919 :param number: the number to format
920 :param currency: the currency code
921 :param format_type: the compact format type to use. Defaults to "short".
922 :param locale: the `Locale` object or locale identifier.
923 Defaults to the system currency locale or numeric locale.
924 :param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
925 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
926 The special value "default" will use the default numbering system of the locale.
927 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
928 """
929 locale = Locale.parse(locale or LC_MONETARY)
930 try:
931 compact_format = locale.compact_currency_formats[format_type]
932 except KeyError as error:
933 raise UnknownCurrencyFormatError(
934 f"{format_type!r} is not a known compact currency format type",
935 ) from error
936 number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
937 # Did not find a format, fall back.
938 if format is None or "¤" not in str(format):
939 # find first format that has a currency symbol
940 for magnitude in compact_format['other']:
941 format = compact_format['other'][magnitude].pattern
942 if '¤' not in format:
943 continue
944 # remove characters that are not the currency symbol, 0's or spaces
945 format = re.sub(r'[^0\s\¤]', '', format)
946 # compress adjacent spaces into one
947 format = re.sub(r'(\s)\s+', r'\1', format).strip()
948 break
949 if format is None:
950 raise ValueError('No compact currency format found for the given number and locale.')
951 pattern = parse_pattern(format)
952 return pattern.apply(
953 number,
954 locale,
955 currency=currency,
956 currency_digits=False,
957 decimal_quantization=False,
958 numbering_system=numbering_system,
959 )
962def format_percent(
963 number: float | decimal.Decimal | str,
964 format: str | NumberPattern | None = None,
965 locale: Locale | str | None = None,
966 decimal_quantization: bool = True,
967 group_separator: bool = True,
968 *,
969 numbering_system: Literal["default"] | str = "latn",
970) -> str:
971 """Return formatted percent value for a specific locale.
973 >>> format_percent(0.34, locale='en_US')
974 '34%'
975 >>> format_percent(25.1234, locale='en_US')
976 '2,512%'
977 >>> format_percent(25.1234, locale='sv_SE')
978 '2\\xa0512\\xa0%'
979 >>> format_percent(25.1234, locale='ar_EG', numbering_system='default')
980 '2٬512%'
982 The format pattern can also be specified explicitly:
984 >>> format_percent(25.1234, '#,##0\\u2030', locale='en_US')
985 '25,123‰'
987 By default the locale is allowed to truncate and round a high-precision
988 number by forcing its format pattern onto the decimal part. You can bypass
989 this behavior with the `decimal_quantization` parameter:
991 >>> format_percent(23.9876, locale='en_US')
992 '2,399%'
993 >>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
994 '2,398.76%'
996 >>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
997 '22929112%'
999 >>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
1000 '22.929.112%'
1002 :param number: the percent number to format
1003 :param format:
1004 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
1005 :param decimal_quantization: Truncate and round high-precision numbers to
1006 the format pattern. Defaults to `True`.
1007 :param group_separator: Boolean to switch group separator on/off in a locale's
1008 number format.
1009 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
1010 The special value "default" will use the default numbering system of the locale.
1011 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
1012 """
1013 locale = Locale.parse(locale or LC_NUMERIC)
1014 if not format:
1015 format = locale.percent_formats[None]
1016 pattern = parse_pattern(format)
1017 return pattern.apply(
1018 number,
1019 locale,
1020 decimal_quantization=decimal_quantization,
1021 group_separator=group_separator,
1022 numbering_system=numbering_system,
1023 )
1026def format_scientific(
1027 number: float | decimal.Decimal | str,
1028 format: str | NumberPattern | None = None,
1029 locale: Locale | str | None = None,
1030 decimal_quantization: bool = True,
1031 *,
1032 numbering_system: Literal["default"] | str = "latn",
1033) -> str:
1034 """Return value formatted in scientific notation for a specific locale.
1036 >>> format_scientific(10000, locale='en_US')
1037 '1E4'
1038 >>> format_scientific(10000, locale='ar_EG', numbering_system='default')
1039 '1أس4'
1041 The format pattern can also be specified explicitly:
1043 >>> format_scientific(1234567, '##0.##E00', locale='en_US')
1044 '1.23E06'
1046 By default the locale is allowed to truncate and round a high-precision
1047 number by forcing its format pattern onto the decimal part. You can bypass
1048 this behavior with the `decimal_quantization` parameter:
1050 >>> format_scientific(1234.9876, '#.##E0', locale='en_US')
1051 '1.23E3'
1052 >>> format_scientific(1234.9876, '#.##E0', locale='en_US', decimal_quantization=False)
1053 '1.2349876E3'
1055 :param number: the number to format
1056 :param format:
1057 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
1058 :param decimal_quantization: Truncate and round high-precision numbers to
1059 the format pattern. Defaults to `True`.
1060 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
1061 The special value "default" will use the default numbering system of the locale.
1062 :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
1063 """
1064 locale = Locale.parse(locale or LC_NUMERIC)
1065 if not format:
1066 format = locale.scientific_formats[None]
1067 pattern = parse_pattern(format)
1068 return pattern.apply(
1069 number,
1070 locale,
1071 decimal_quantization=decimal_quantization,
1072 numbering_system=numbering_system,
1073 )
1076class NumberFormatError(ValueError):
1077 """Exception raised when a string cannot be parsed into a number."""
1079 def __init__(self, message: str, suggestions: list[str] | None = None) -> None:
1080 super().__init__(message)
1081 #: a list of properly formatted numbers derived from the invalid input
1082 self.suggestions = suggestions
1085SPACE_CHARS = {
1086 ' ', # space
1087 '\xa0', # no-break space
1088 '\u202f', # narrow no-break space
1089}
1091SPACE_CHARS_RE = re.compile('|'.join(SPACE_CHARS))
1094def parse_number(
1095 string: str,
1096 locale: Locale | str | None = None,
1097 *,
1098 numbering_system: Literal["default"] | str = "latn",
1099) -> int:
1100 """Parse localized number string into an integer.
1102 >>> parse_number('1,099', locale='en_US')
1103 1099
1104 >>> parse_number('1.099', locale='de_DE')
1105 1099
1107 When the given string cannot be parsed, an exception is raised:
1109 >>> parse_number('1.099,98', locale='de')
1110 Traceback (most recent call last):
1111 ...
1112 NumberFormatError: '1.099,98' is not a valid number
1114 :param string: the string to parse
1115 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
1116 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
1117 The special value "default" will use the default numbering system of the locale.
1118 :return: the parsed number
1119 :raise `NumberFormatError`: if the string can not be converted to a number
1120 :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
1121 """
1122 group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
1124 if (
1125 # if the grouping symbol is a kind of space,
1126 group_symbol in SPACE_CHARS
1127 # and the string to be parsed does not contain it,
1128 and group_symbol not in string
1129 # but it does contain any other kind of space instead,
1130 and SPACE_CHARS_RE.search(string)
1131 ):
1132 # ... it's reasonable to assume it is taking the place of the grouping symbol.
1133 string = SPACE_CHARS_RE.sub(group_symbol, string)
1135 try:
1136 return int(string.replace(group_symbol, ''))
1137 except ValueError as ve:
1138 raise NumberFormatError(f"{string!r} is not a valid number") from ve
1141def parse_decimal(
1142 string: str,
1143 locale: Locale | str | None = None,
1144 strict: bool = False,
1145 *,
1146 numbering_system: Literal["default"] | str = "latn",
1147) -> decimal.Decimal:
1148 """Parse localized decimal string into a decimal.
1150 >>> parse_decimal('1,099.98', locale='en_US')
1151 Decimal('1099.98')
1152 >>> parse_decimal('1.099,98', locale='de')
1153 Decimal('1099.98')
1154 >>> parse_decimal('12 345,123', locale='ru')
1155 Decimal('12345.123')
1156 >>> parse_decimal('1٬099٫98', locale='ar_EG', numbering_system='default')
1157 Decimal('1099.98')
1159 When the given string cannot be parsed, an exception is raised:
1161 >>> parse_decimal('2,109,998', locale='de')
1162 Traceback (most recent call last):
1163 ...
1164 NumberFormatError: '2,109,998' is not a valid decimal number
1166 If `strict` is set to `True` and the given string contains a number
1167 formatted in an irregular way, an exception is raised:
1169 >>> parse_decimal('30.00', locale='de', strict=True)
1170 Traceback (most recent call last):
1171 ...
1172 NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
1174 >>> parse_decimal('0.00', locale='de', strict=True)
1175 Traceback (most recent call last):
1176 ...
1177 NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
1179 :param string: the string to parse
1180 :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
1181 :param strict: controls whether numbers formatted in a weird way are
1182 accepted or rejected
1183 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
1184 The special value "default" will use the default numbering system of the locale.
1185 :raise NumberFormatError: if the string can not be converted to a
1186 decimal number
1187 :raise UnsupportedNumberingSystemError: if the numbering system is not supported by the locale.
1188 """
1189 locale = Locale.parse(locale or LC_NUMERIC)
1190 group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
1191 decimal_symbol = get_decimal_symbol(locale, numbering_system=numbering_system)
1193 if not strict and (
1194 group_symbol in SPACE_CHARS # if the grouping symbol is a kind of space,
1195 and group_symbol not in string # and the string to be parsed does not contain it,
1196 # but it does contain any other kind of space instead,
1197 and SPACE_CHARS_RE.search(string)
1198 ):
1199 # ... it's reasonable to assume it is taking the place of the grouping symbol.
1200 string = SPACE_CHARS_RE.sub(group_symbol, string)
1202 try:
1203 parsed = decimal.Decimal(string.replace(group_symbol, '').replace(decimal_symbol, '.'))
1204 except decimal.InvalidOperation as exc:
1205 raise NumberFormatError(f"{string!r} is not a valid decimal number") from exc
1206 if strict and group_symbol in string:
1207 proper = format_decimal(
1208 parsed,
1209 locale=locale,
1210 decimal_quantization=False,
1211 numbering_system=numbering_system,
1212 )
1213 if string != proper and proper != _remove_trailing_zeros_after_decimal(string, decimal_symbol): # fmt: skip
1214 try:
1215 parsed_alt = decimal.Decimal(
1216 string.replace(decimal_symbol, '').replace(group_symbol, '.'),
1217 )
1218 except decimal.InvalidOperation as exc:
1219 raise NumberFormatError(
1220 f"{string!r} is not a properly formatted decimal number. "
1221 f"Did you mean {proper!r}?",
1222 suggestions=[proper],
1223 ) from exc
1224 else:
1225 proper_alt = format_decimal(
1226 parsed_alt,
1227 locale=locale,
1228 decimal_quantization=False,
1229 numbering_system=numbering_system,
1230 )
1231 if proper_alt == proper:
1232 raise NumberFormatError(
1233 f"{string!r} is not a properly formatted decimal number. "
1234 f"Did you mean {proper!r}?",
1235 suggestions=[proper],
1236 )
1237 else:
1238 raise NumberFormatError(
1239 f"{string!r} is not a properly formatted decimal number. "
1240 f"Did you mean {proper!r}? Or maybe {proper_alt!r}?",
1241 suggestions=[proper, proper_alt],
1242 )
1243 return parsed
1246def _remove_trailing_zeros_after_decimal(string: str, decimal_symbol: str) -> str:
1247 """
1248 Remove trailing zeros from the decimal part of a numeric string.
1250 This function takes a string representing a numeric value and a decimal symbol.
1251 It removes any trailing zeros that appear after the decimal symbol in the number.
1252 If the decimal part becomes empty after removing trailing zeros, the decimal symbol
1253 is also removed. If the string does not contain the decimal symbol, it is returned unchanged.
1255 :param string: The numeric string from which to remove trailing zeros.
1256 :param decimal_symbol: The symbol used to denote the decimal point.
1257 :return: The numeric string with trailing zeros removed from its decimal part.
1259 Example:
1260 >>> _remove_trailing_zeros_after_decimal("123.4500", ".")
1261 '123.45'
1262 >>> _remove_trailing_zeros_after_decimal("100.000", ".")
1263 '100'
1264 >>> _remove_trailing_zeros_after_decimal("100", ".")
1265 '100'
1266 """
1267 integer_part, _, decimal_part = string.partition(decimal_symbol)
1269 if decimal_part:
1270 decimal_part = decimal_part.rstrip("0")
1271 if decimal_part:
1272 return integer_part + decimal_symbol + decimal_part
1273 return integer_part
1275 return string
1278_number_pattern_re = re.compile(
1279 r"(?P<prefix>(?:[^'0-9@#.,]|'[^']*')*)"
1280 r"(?P<number>[0-9@#.,E+]*)"
1281 r"(?P<suffix>.*)",
1282)
1285def parse_grouping(p: str) -> tuple[int, int]:
1286 """Parse primary and secondary digit grouping
1288 >>> parse_grouping('##')
1289 (1000, 1000)
1290 >>> parse_grouping('#,###')
1291 (3, 3)
1292 >>> parse_grouping('#,####,###')
1293 (3, 4)
1294 """
1295 width = len(p)
1296 g1 = p.rfind(',')
1297 if g1 == -1:
1298 return 1000, 1000
1299 g1 = width - g1 - 1
1300 g2 = p[: -g1 - 1].rfind(',')
1301 if g2 == -1:
1302 return g1, g1
1303 g2 = width - g1 - g2 - 2
1304 return g1, g2
1307def parse_pattern(pattern: NumberPattern | str) -> NumberPattern:
1308 """Parse number format patterns"""
1309 if isinstance(pattern, NumberPattern):
1310 return pattern
1312 def _match_number(pattern):
1313 rv = _number_pattern_re.search(pattern)
1314 if rv is None:
1315 raise ValueError(f"Invalid number pattern {pattern!r}")
1316 return rv.groups()
1318 pos_pattern = pattern
1320 # Do we have a negative subpattern?
1321 if ';' in pattern:
1322 pos_pattern, neg_pattern = pattern.split(';', 1)
1323 pos_prefix, number, pos_suffix = _match_number(pos_pattern)
1324 neg_prefix, _, neg_suffix = _match_number(neg_pattern)
1325 else:
1326 pos_prefix, number, pos_suffix = _match_number(pos_pattern)
1327 neg_prefix = f"-{pos_prefix}"
1328 neg_suffix = pos_suffix
1329 if 'E' in number:
1330 number, exp = number.split('E', 1)
1331 else:
1332 exp = None
1333 if '@' in number and '.' in number and '0' in number:
1334 raise ValueError('Significant digit patterns can not contain "@" or "0"')
1335 if '.' in number:
1336 integer, fraction = number.rsplit('.', 1)
1337 else:
1338 integer = number
1339 fraction = ''
1341 def parse_precision(p):
1342 """Calculate the min and max allowed digits"""
1343 min = max = 0
1344 for c in p:
1345 if c in '@0':
1346 min += 1
1347 max += 1
1348 elif c == '#':
1349 max += 1
1350 elif c == ',':
1351 continue
1352 else:
1353 break
1354 return min, max
1356 int_prec = parse_precision(integer)
1357 frac_prec = parse_precision(fraction)
1358 if exp:
1359 exp_plus = exp.startswith('+')
1360 exp = exp.lstrip('+')
1361 exp_prec = parse_precision(exp)
1362 else:
1363 exp_plus = None
1364 exp_prec = None
1365 grouping = parse_grouping(integer)
1366 return NumberPattern(
1367 pattern,
1368 (pos_prefix, neg_prefix),
1369 (pos_suffix, neg_suffix),
1370 grouping,
1371 int_prec,
1372 frac_prec,
1373 exp_prec,
1374 exp_plus,
1375 number,
1376 )
1379class NumberPattern:
1380 def __init__(
1381 self,
1382 pattern: str,
1383 prefix: tuple[str, str],
1384 suffix: tuple[str, str],
1385 grouping: tuple[int, int],
1386 int_prec: tuple[int, int],
1387 frac_prec: tuple[int, int],
1388 exp_prec: tuple[int, int] | None,
1389 exp_plus: bool | None,
1390 number_pattern: str | None = None,
1391 ) -> None:
1392 # Metadata of the decomposed parsed pattern.
1393 self.pattern = pattern
1394 self.prefix = prefix
1395 self.suffix = suffix
1396 self.number_pattern = number_pattern
1397 self.grouping = grouping
1398 self.int_prec = int_prec
1399 self.frac_prec = frac_prec
1400 self.exp_prec = exp_prec
1401 self.exp_plus = exp_plus
1402 self.scale = self.compute_scale()
1404 def __repr__(self) -> str:
1405 return f"<{type(self).__name__} {self.pattern!r}>"
1407 def compute_scale(self) -> Literal[0, 2, 3]:
1408 """Return the scaling factor to apply to the number before rendering.
1410 Auto-set to a factor of 2 or 3 if presence of a ``%`` or ``‰`` sign is
1411 detected in the prefix or suffix of the pattern. Default is to not mess
1412 with the scale at all and keep it to 0.
1413 """
1414 scale = 0
1415 if '%' in ''.join(self.prefix + self.suffix):
1416 scale = 2
1417 elif '‰' in ''.join(self.prefix + self.suffix):
1418 scale = 3
1419 return scale
1421 def scientific_notation_elements(
1422 self,
1423 value: decimal.Decimal,
1424 locale: Locale | str | None,
1425 *,
1426 numbering_system: Literal["default"] | str = "latn",
1427 ) -> tuple[decimal.Decimal, int, str]:
1428 """Returns normalized scientific notation components of a value."""
1429 # Normalize value to only have one lead digit.
1430 exp = value.adjusted()
1431 value = value * get_decimal_quantum(exp)
1432 assert value.adjusted() == 0
1434 # Shift exponent and value by the minimum number of leading digits
1435 # imposed by the rendering pattern. And always make that number
1436 # greater or equal to 1.
1437 lead_shift = max([1, min(self.int_prec)]) - 1
1438 exp = exp - lead_shift
1439 value = value * get_decimal_quantum(-lead_shift)
1441 # Get exponent sign symbol.
1442 exp_sign = ''
1443 if exp < 0:
1444 exp_sign = get_minus_sign_symbol(locale, numbering_system=numbering_system)
1445 elif self.exp_plus:
1446 exp_sign = get_plus_sign_symbol(locale, numbering_system=numbering_system)
1448 # Normalize exponent value now that we have the sign.
1449 exp = abs(exp)
1451 return value, exp, exp_sign
1453 def apply(
1454 self,
1455 value: float | decimal.Decimal | str,
1456 locale: Locale | str | None,
1457 currency: str | None = None,
1458 currency_digits: bool = True,
1459 decimal_quantization: bool = True,
1460 force_frac: tuple[int, int] | None = None,
1461 group_separator: bool = True,
1462 *,
1463 numbering_system: Literal["default"] | str = "latn",
1464 ):
1465 """Renders into a string a number following the defined pattern.
1467 Forced decimal quantization is active by default so we'll produce a
1468 number string that is strictly following CLDR pattern definitions.
1470 :param value: The value to format. If this is not a Decimal object,
1471 it will be cast to one.
1472 :param locale: The locale to use for formatting.
1473 :param currency: Which currency, if any, to format as.
1474 :param currency_digits: Whether or not to use the currency's precision.
1475 If false, the pattern's precision is used.
1476 :param decimal_quantization: Whether decimal numbers should be forcibly
1477 quantized to produce a formatted output
1478 strictly matching the CLDR definition for
1479 the locale.
1480 :param force_frac: DEPRECATED - a forced override for `self.frac_prec`
1481 for a single formatting invocation.
1482 :param group_separator: Whether to use the locale's number group separator.
1483 :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
1484 The special value "default" will use the default numbering system of the locale.
1485 :return: Formatted decimal string.
1486 :rtype: str
1487 :raise UnsupportedNumberingSystemError: If the numbering system is not supported by the locale.
1488 """
1489 if not isinstance(value, decimal.Decimal):
1490 value = decimal.Decimal(str(value))
1492 value = value.scaleb(self.scale)
1494 # Separate the absolute value from its sign.
1495 is_negative = int(value.is_signed())
1496 value = abs(value).normalize()
1498 # Prepare scientific notation metadata.
1499 if self.exp_prec:
1500 value, exp, exp_sign = self.scientific_notation_elements(
1501 value,
1502 locale,
1503 numbering_system=numbering_system,
1504 )
1506 # Adjust the precision of the fractional part and force it to the
1507 # currency's if necessary.
1508 if force_frac:
1509 # TODO (3.x?): Remove this parameter
1510 warnings.warn(
1511 'The force_frac parameter to NumberPattern.apply() is deprecated.',
1512 DeprecationWarning,
1513 stacklevel=2,
1514 )
1515 frac_prec = force_frac
1516 elif currency and currency_digits:
1517 frac_prec = (get_currency_precision(currency),) * 2
1518 else:
1519 frac_prec = self.frac_prec
1521 # Bump decimal precision to the natural precision of the number if it
1522 # exceeds the one we're about to use. This adaptative precision is only
1523 # triggered if the decimal quantization is disabled or if a scientific
1524 # notation pattern has a missing mandatory fractional part (as in the
1525 # default '#E0' pattern). This special case has been extensively
1526 # discussed at https://github.com/python-babel/babel/pull/494#issuecomment-307649969 .
1527 if not decimal_quantization or (self.exp_prec and frac_prec == (0, 0)):
1528 frac_prec = (frac_prec[0], max([frac_prec[1], get_decimal_precision(value)]))
1530 # Render scientific notation.
1531 if self.exp_prec:
1532 number = ''.join([
1533 self._quantize_value(value, locale, frac_prec, group_separator, numbering_system=numbering_system),
1534 get_exponential_symbol(locale, numbering_system=numbering_system),
1535 exp_sign, # type: ignore # exp_sign is always defined here
1536 self._format_int(str(exp), self.exp_prec[0], self.exp_prec[1], locale, numbering_system=numbering_system), # type: ignore # exp is always defined here
1537 ]) # fmt: skip
1539 # Is it a significant digits pattern?
1540 elif '@' in self.pattern:
1541 text = self._format_significant(value, self.int_prec[0], self.int_prec[1])
1542 a, sep, b = text.partition(".")
1543 number = self._format_int(a, 0, 1000, locale, numbering_system=numbering_system)
1544 if sep:
1545 number += get_decimal_symbol(locale, numbering_system=numbering_system) + b
1547 # A normal number pattern.
1548 else:
1549 number = self._quantize_value(
1550 value,
1551 locale,
1552 frac_prec,
1553 group_separator,
1554 numbering_system=numbering_system,
1555 )
1557 retval = ''.join(
1558 (
1559 self.prefix[is_negative],
1560 number if self.number_pattern != '' else '',
1561 self.suffix[is_negative],
1562 ),
1563 )
1565 if '¤' in retval and currency is not None:
1566 retval = retval.replace('¤¤¤', get_currency_name(currency, value, locale))
1567 retval = retval.replace('¤¤', currency.upper())
1568 retval = retval.replace('¤', get_currency_symbol(currency, locale))
1570 # remove single quotes around text, except for doubled single quotes
1571 # which are replaced with a single quote
1572 retval = re.sub(r"'([^']*)'", lambda m: m.group(1) or "'", retval)
1574 return retval
1576 #
1577 # This is one tricky piece of code. The idea is to rely as much as possible
1578 # on the decimal module to minimize the amount of code.
1579 #
1580 # Conceptually, the implementation of this method can be summarized in the
1581 # following steps:
1582 #
1583 # - Move or shift the decimal point (i.e. the exponent) so the maximum
1584 # amount of significant digits fall into the integer part (i.e. to the
1585 # left of the decimal point)
1586 #
1587 # - Round the number to the nearest integer, discarding all the fractional
1588 # part which contained extra digits to be eliminated
1589 #
1590 # - Convert the rounded integer to a string, that will contain the final
1591 # sequence of significant digits already trimmed to the maximum
1592 #
1593 # - Restore the original position of the decimal point, potentially
1594 # padding with zeroes on either side
1595 #
1596 def _format_significant(self, value: decimal.Decimal, minimum: int, maximum: int) -> str:
1597 exp = value.adjusted()
1598 scale = maximum - 1 - exp
1599 digits = str(value.scaleb(scale).quantize(decimal.Decimal(1)))
1600 if scale <= 0:
1601 result = digits + '0' * -scale
1602 else:
1603 intpart = digits[:-scale]
1604 i = len(intpart)
1605 j = i + max(minimum - i, 0)
1606 result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format(
1607 intpart=intpart or '0',
1608 pad='',
1609 fill=-min(exp + 1, 0),
1610 fracpart=digits[i:j],
1611 fracextra=digits[j:].rstrip('0'),
1612 ).rstrip('.')
1613 return result
1615 def _format_int(
1616 self,
1617 value: str,
1618 min: int,
1619 max: int,
1620 locale: Locale | str | None,
1621 *,
1622 numbering_system: Literal["default"] | str,
1623 ) -> str:
1624 width = len(value)
1625 if width < min:
1626 value = '0' * (min - width) + value
1627 gsize = self.grouping[0]
1628 ret = ''
1629 symbol = get_group_symbol(locale, numbering_system=numbering_system)
1630 while len(value) > gsize:
1631 ret = symbol + value[-gsize:] + ret
1632 value = value[:-gsize]
1633 gsize = self.grouping[1]
1634 return value + ret
1636 def _quantize_value(
1637 self,
1638 value: decimal.Decimal,
1639 locale: Locale | str | None,
1640 frac_prec: tuple[int, int],
1641 group_separator: bool,
1642 *,
1643 numbering_system: Literal["default"] | str,
1644 ) -> str:
1645 # If the number is +/-Infinity, we can't quantize it
1646 if value.is_infinite():
1647 return get_infinity_symbol(locale, numbering_system=numbering_system)
1648 quantum = get_decimal_quantum(frac_prec[1])
1649 rounded = value.quantize(quantum)
1650 a, sep, b = f"{rounded:f}".partition(".")
1651 integer_part = a
1652 if group_separator:
1653 integer_part = self._format_int(
1654 a,
1655 self.int_prec[0],
1656 self.int_prec[1],
1657 locale,
1658 numbering_system=numbering_system,
1659 )
1660 number = integer_part + self._format_frac(
1661 b or '0',
1662 locale=locale,
1663 force_frac=frac_prec,
1664 numbering_system=numbering_system,
1665 )
1666 return number
1668 def _format_frac(
1669 self,
1670 value: str,
1671 locale: Locale | str | None,
1672 force_frac: tuple[int, int] | None = None,
1673 *,
1674 numbering_system: Literal["default"] | str,
1675 ) -> str:
1676 min, max = force_frac or self.frac_prec
1677 if len(value) < min:
1678 value += '0' * (min - len(value))
1679 if max == 0 or (min == 0 and int(value) == 0):
1680 return ''
1681 while len(value) > min and value[-1] == '0':
1682 value = value[:-1]
1683 return get_decimal_symbol(locale, numbering_system=numbering_system) + value