numbers.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  1. """
  2. babel.numbers
  3. ~~~~~~~~~~~~~
  4. Locale dependent formatting and parsing of numeric data.
  5. The default locale for the functions in this module is determined by the
  6. following environment variables, in that order:
  7. * ``LC_MONETARY`` for currency related functions,
  8. * ``LC_NUMERIC``, and
  9. * ``LC_ALL``, and
  10. * ``LANG``
  11. :copyright: (c) 2013-2025 by the Babel Team.
  12. :license: BSD, see LICENSE for more details.
  13. """
  14. # TODO:
  15. # Padding and rounding increments in pattern:
  16. # - https://www.unicode.org/reports/tr35/ (Appendix G.6)
  17. from __future__ import annotations
  18. import datetime
  19. import decimal
  20. import re
  21. import warnings
  22. from typing import Any, Literal, cast, overload
  23. from babel.core import Locale, default_locale, get_global
  24. from babel.localedata import LocaleDataDict
  25. LC_MONETARY = default_locale(('LC_MONETARY', 'LC_NUMERIC'))
  26. LC_NUMERIC = default_locale('LC_NUMERIC')
  27. class UnknownCurrencyError(Exception):
  28. """Exception thrown when a currency is requested for which no data is available.
  29. """
  30. def __init__(self, identifier: str) -> None:
  31. """Create the exception.
  32. :param identifier: the identifier string of the unsupported currency
  33. """
  34. Exception.__init__(self, f"Unknown currency {identifier!r}.")
  35. #: The identifier of the locale that could not be found.
  36. self.identifier = identifier
  37. def list_currencies(locale: Locale | str | None = None) -> set[str]:
  38. """ Return a `set` of normalized currency codes.
  39. .. versionadded:: 2.5.0
  40. :param locale: filters returned currency codes by the provided locale.
  41. Expected to be a locale instance or code. If no locale is
  42. provided, returns the list of all currencies from all
  43. locales.
  44. """
  45. # Get locale-scoped currencies.
  46. if locale:
  47. return set(Locale.parse(locale).currencies)
  48. return set(get_global('all_currencies'))
  49. def validate_currency(currency: str, locale: Locale | str | None = None) -> None:
  50. """ Check the currency code is recognized by Babel.
  51. Accepts a ``locale`` parameter for fined-grained validation, working as
  52. the one defined above in ``list_currencies()`` method.
  53. Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel.
  54. """
  55. if currency not in list_currencies(locale):
  56. raise UnknownCurrencyError(currency)
  57. def is_currency(currency: str, locale: Locale | str | None = None) -> bool:
  58. """ Returns `True` only if a currency is recognized by Babel.
  59. This method always return a Boolean and never raise.
  60. """
  61. if not currency or not isinstance(currency, str):
  62. return False
  63. try:
  64. validate_currency(currency, locale)
  65. except UnknownCurrencyError:
  66. return False
  67. return True
  68. def normalize_currency(currency: str, locale: Locale | str | None = None) -> str | None:
  69. """Returns the normalized identifier of any currency code.
  70. Accepts a ``locale`` parameter for fined-grained validation, working as
  71. the one defined above in ``list_currencies()`` method.
  72. Returns None if the currency is unknown to Babel.
  73. """
  74. if isinstance(currency, str):
  75. currency = currency.upper()
  76. if not is_currency(currency, locale):
  77. return None
  78. return currency
  79. def get_currency_name(
  80. currency: str,
  81. count: float | decimal.Decimal | None = None,
  82. locale: Locale | str | None = None,
  83. ) -> str:
  84. """Return the name used by the locale for the specified currency.
  85. >>> get_currency_name('USD', locale='en_US')
  86. u'US Dollar'
  87. .. versionadded:: 0.9.4
  88. :param currency: the currency code.
  89. :param count: the optional count. If provided the currency name
  90. will be pluralized to that number if possible.
  91. :param locale: the `Locale` object or locale identifier.
  92. Defaults to the system currency locale or numeric locale.
  93. """
  94. loc = Locale.parse(locale or LC_MONETARY)
  95. if count is not None:
  96. try:
  97. plural_form = loc.plural_form(count)
  98. except (OverflowError, ValueError):
  99. plural_form = 'other'
  100. plural_names = loc._data['currency_names_plural']
  101. if currency in plural_names:
  102. currency_plural_names = plural_names[currency]
  103. if plural_form in currency_plural_names:
  104. return currency_plural_names[plural_form]
  105. if 'other' in currency_plural_names:
  106. return currency_plural_names['other']
  107. return loc.currencies.get(currency, currency)
  108. def get_currency_symbol(currency: str, locale: Locale | str | None = None) -> str:
  109. """Return the symbol used by the locale for the specified currency.
  110. >>> get_currency_symbol('USD', locale='en_US')
  111. u'$'
  112. :param currency: the currency code.
  113. :param locale: the `Locale` object or locale identifier.
  114. Defaults to the system currency locale or numeric locale.
  115. """
  116. return Locale.parse(locale or LC_MONETARY).currency_symbols.get(currency, currency)
  117. def get_currency_precision(currency: str) -> int:
  118. """Return currency's precision.
  119. Precision is the number of decimals found after the decimal point in the
  120. currency's format pattern.
  121. .. versionadded:: 2.5.0
  122. :param currency: the currency code.
  123. """
  124. precisions = get_global('currency_fractions')
  125. return precisions.get(currency, precisions['DEFAULT'])[0]
  126. def get_currency_unit_pattern(
  127. currency: str, # TODO: unused?!
  128. count: float | decimal.Decimal | None = None,
  129. locale: Locale | str | None = None,
  130. ) -> str:
  131. """
  132. Return the unit pattern used for long display of a currency value
  133. for a given locale.
  134. This is a string containing ``{0}`` where the numeric part
  135. should be substituted and ``{1}`` where the currency long display
  136. name should be substituted.
  137. >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
  138. u'{0} {1}'
  139. .. versionadded:: 2.7.0
  140. :param currency: the currency code.
  141. :param count: the optional count. If provided the unit
  142. pattern for that number will be returned.
  143. :param locale: the `Locale` object or locale identifier.
  144. Defaults to the system currency locale or numeric locale.
  145. """
  146. loc = Locale.parse(locale or LC_MONETARY)
  147. if count is not None:
  148. plural_form = loc.plural_form(count)
  149. try:
  150. return loc._data['currency_unit_patterns'][plural_form]
  151. except LookupError:
  152. # Fall back to 'other'
  153. pass
  154. return loc._data['currency_unit_patterns']['other']
  155. @overload
  156. def get_territory_currencies(
  157. territory: str,
  158. start_date: datetime.date | None = ...,
  159. end_date: datetime.date | None = ...,
  160. tender: bool = ...,
  161. non_tender: bool = ...,
  162. include_details: Literal[False] = ...,
  163. ) -> list[str]:
  164. ... # pragma: no cover
  165. @overload
  166. def get_territory_currencies(
  167. territory: str,
  168. start_date: datetime.date | None = ...,
  169. end_date: datetime.date | None = ...,
  170. tender: bool = ...,
  171. non_tender: bool = ...,
  172. include_details: Literal[True] = ...,
  173. ) -> list[dict[str, Any]]:
  174. ... # pragma: no cover
  175. def get_territory_currencies(
  176. territory: str,
  177. start_date: datetime.date | None = None,
  178. end_date: datetime.date | None = None,
  179. tender: bool = True,
  180. non_tender: bool = False,
  181. include_details: bool = False,
  182. ) -> list[str] | list[dict[str, Any]]:
  183. """Returns the list of currencies for the given territory that are valid for
  184. the given date range. In addition to that the currency database
  185. distinguishes between tender and non-tender currencies. By default only
  186. tender currencies are returned.
  187. The return value is a list of all currencies roughly ordered by the time
  188. of when the currency became active. The longer the currency is being in
  189. use the more to the left of the list it will be.
  190. The start date defaults to today. If no end date is given it will be the
  191. same as the start date. Otherwise a range can be defined. For instance
  192. this can be used to find the currencies in use in Austria between 1995 and
  193. 2011:
  194. >>> from datetime import date
  195. >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
  196. ['ATS', 'EUR']
  197. Likewise it's also possible to find all the currencies in use on a
  198. single date:
  199. >>> get_territory_currencies('AT', date(1995, 1, 1))
  200. ['ATS']
  201. >>> get_territory_currencies('AT', date(2011, 1, 1))
  202. ['EUR']
  203. By default the return value only includes tender currencies. This
  204. however can be changed:
  205. >>> get_territory_currencies('US')
  206. ['USD']
  207. >>> get_territory_currencies('US', tender=False, non_tender=True,
  208. ... start_date=date(2014, 1, 1))
  209. ['USN', 'USS']
  210. .. versionadded:: 2.0
  211. :param territory: the name of the territory to find the currency for.
  212. :param start_date: the start date. If not given today is assumed.
  213. :param end_date: the end date. If not given the start date is assumed.
  214. :param tender: controls whether tender currencies should be included.
  215. :param non_tender: controls whether non-tender currencies should be
  216. included.
  217. :param include_details: if set to `True`, instead of returning currency
  218. codes the return value will be dictionaries
  219. with detail information. In that case each
  220. dictionary will have the keys ``'currency'``,
  221. ``'from'``, ``'to'``, and ``'tender'``.
  222. """
  223. currencies = get_global('territory_currencies')
  224. if start_date is None:
  225. start_date = datetime.date.today()
  226. elif isinstance(start_date, datetime.datetime):
  227. start_date = start_date.date()
  228. if end_date is None:
  229. end_date = start_date
  230. elif isinstance(end_date, datetime.datetime):
  231. end_date = end_date.date()
  232. curs = currencies.get(territory.upper(), ())
  233. # TODO: validate that the territory exists
  234. def _is_active(start, end):
  235. return (start is None or start <= end_date) and \
  236. (end is None or end >= start_date)
  237. result = []
  238. for currency_code, start, end, is_tender in curs:
  239. if start:
  240. start = datetime.date(*start)
  241. if end:
  242. end = datetime.date(*end)
  243. if ((is_tender and tender) or
  244. (not is_tender and non_tender)) and _is_active(start, end):
  245. if include_details:
  246. result.append({
  247. 'currency': currency_code,
  248. 'from': start,
  249. 'to': end,
  250. 'tender': is_tender,
  251. })
  252. else:
  253. result.append(currency_code)
  254. return result
  255. def _get_numbering_system(locale: Locale, numbering_system: Literal["default"] | str = "latn") -> str:
  256. if numbering_system == "default":
  257. return locale.default_numbering_system
  258. else:
  259. return numbering_system
  260. def _get_number_symbols(
  261. locale: Locale,
  262. *,
  263. numbering_system: Literal["default"] | str = "latn",
  264. ) -> LocaleDataDict:
  265. numbering_system = _get_numbering_system(locale, numbering_system)
  266. try:
  267. return locale.number_symbols[numbering_system]
  268. except KeyError as error:
  269. raise UnsupportedNumberingSystemError(f"Unknown numbering system {numbering_system} for Locale {locale}.") from error
  270. class UnsupportedNumberingSystemError(Exception):
  271. """Exception thrown when an unsupported numbering system is requested for the given Locale."""
  272. pass
  273. def get_decimal_symbol(
  274. locale: Locale | str | None = None,
  275. *,
  276. numbering_system: Literal["default"] | str = "latn",
  277. ) -> str:
  278. """Return the symbol used by the locale to separate decimal fractions.
  279. >>> get_decimal_symbol('en_US')
  280. u'.'
  281. >>> get_decimal_symbol('ar_EG', numbering_system='default')
  282. u'٫'
  283. >>> get_decimal_symbol('ar_EG', numbering_system='latn')
  284. u'.'
  285. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  286. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  287. The special value "default" will use the default numbering system of the locale.
  288. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  289. """
  290. locale = Locale.parse(locale or LC_NUMERIC)
  291. return _get_number_symbols(locale, numbering_system=numbering_system).get('decimal', '.')
  292. def get_plus_sign_symbol(
  293. locale: Locale | str | None = None,
  294. *,
  295. numbering_system: Literal["default"] | str = "latn",
  296. ) -> str:
  297. """Return the plus sign symbol used by the current locale.
  298. >>> get_plus_sign_symbol('en_US')
  299. u'+'
  300. >>> get_plus_sign_symbol('ar_EG', numbering_system='default')
  301. u'\u061c+'
  302. >>> get_plus_sign_symbol('ar_EG', numbering_system='latn')
  303. u'\u200e+'
  304. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  305. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  306. The special value "default" will use the default numbering system of the locale.
  307. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  308. """
  309. locale = Locale.parse(locale or LC_NUMERIC)
  310. return _get_number_symbols(locale, numbering_system=numbering_system).get('plusSign', '+')
  311. def get_minus_sign_symbol(
  312. locale: Locale | str | None = None,
  313. *,
  314. numbering_system: Literal["default"] | str = "latn",
  315. ) -> str:
  316. """Return the plus sign symbol used by the current locale.
  317. >>> get_minus_sign_symbol('en_US')
  318. u'-'
  319. >>> get_minus_sign_symbol('ar_EG', numbering_system='default')
  320. u'\u061c-'
  321. >>> get_minus_sign_symbol('ar_EG', numbering_system='latn')
  322. u'\u200e-'
  323. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  324. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  325. The special value "default" will use the default numbering system of the locale.
  326. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  327. """
  328. locale = Locale.parse(locale or LC_NUMERIC)
  329. return _get_number_symbols(locale, numbering_system=numbering_system).get('minusSign', '-')
  330. def get_exponential_symbol(
  331. locale: Locale | str | None = None,
  332. *,
  333. numbering_system: Literal["default"] | str = "latn",
  334. ) -> str:
  335. """Return the symbol used by the locale to separate mantissa and exponent.
  336. >>> get_exponential_symbol('en_US')
  337. u'E'
  338. >>> get_exponential_symbol('ar_EG', numbering_system='default')
  339. u'أس'
  340. >>> get_exponential_symbol('ar_EG', numbering_system='latn')
  341. u'E'
  342. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  343. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  344. The special value "default" will use the default numbering system of the locale.
  345. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  346. """
  347. locale = Locale.parse(locale or LC_NUMERIC)
  348. return _get_number_symbols(locale, numbering_system=numbering_system).get('exponential', 'E')
  349. def get_group_symbol(
  350. locale: Locale | str | None = None,
  351. *,
  352. numbering_system: Literal["default"] | str = "latn",
  353. ) -> str:
  354. """Return the symbol used by the locale to separate groups of thousands.
  355. >>> get_group_symbol('en_US')
  356. u','
  357. >>> get_group_symbol('ar_EG', numbering_system='default')
  358. u'٬'
  359. >>> get_group_symbol('ar_EG', numbering_system='latn')
  360. u','
  361. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  362. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  363. The special value "default" will use the default numbering system of the locale.
  364. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  365. """
  366. locale = Locale.parse(locale or LC_NUMERIC)
  367. return _get_number_symbols(locale, numbering_system=numbering_system).get('group', ',')
  368. def get_infinity_symbol(
  369. locale: Locale | str | None = None,
  370. *,
  371. numbering_system: Literal["default"] | str = "latn",
  372. ) -> str:
  373. """Return the symbol used by the locale to represent infinity.
  374. >>> get_infinity_symbol('en_US')
  375. u'∞'
  376. >>> get_infinity_symbol('ar_EG', numbering_system='default')
  377. u'∞'
  378. >>> get_infinity_symbol('ar_EG', numbering_system='latn')
  379. u'∞'
  380. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  381. :param numbering_system: The numbering system used for fetching the symbol. Defaults to "latn".
  382. The special value "default" will use the default numbering system of the locale.
  383. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  384. """
  385. locale = Locale.parse(locale or LC_NUMERIC)
  386. return _get_number_symbols(locale, numbering_system=numbering_system).get('infinity', '∞')
  387. def format_number(number: float | decimal.Decimal | str, locale: Locale | str | None = None) -> str:
  388. """Return the given number formatted for a specific locale.
  389. >>> format_number(1099, locale='en_US') # doctest: +SKIP
  390. u'1,099'
  391. >>> format_number(1099, locale='de_DE') # doctest: +SKIP
  392. u'1.099'
  393. .. deprecated:: 2.6.0
  394. Use babel.numbers.format_decimal() instead.
  395. :param number: the number to format
  396. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  397. """
  398. warnings.warn('Use babel.numbers.format_decimal() instead.', DeprecationWarning, stacklevel=2)
  399. return format_decimal(number, locale=locale)
  400. def get_decimal_precision(number: decimal.Decimal) -> int:
  401. """Return maximum precision of a decimal instance's fractional part.
  402. Precision is extracted from the fractional part only.
  403. """
  404. # Copied from: https://github.com/mahmoud/boltons/pull/59
  405. assert isinstance(number, decimal.Decimal)
  406. decimal_tuple = number.normalize().as_tuple()
  407. # Note: DecimalTuple.exponent can be 'n' (qNaN), 'N' (sNaN), or 'F' (Infinity)
  408. if not isinstance(decimal_tuple.exponent, int) or decimal_tuple.exponent >= 0:
  409. return 0
  410. return abs(decimal_tuple.exponent)
  411. def get_decimal_quantum(precision: int | decimal.Decimal) -> decimal.Decimal:
  412. """Return minimal quantum of a number, as defined by precision."""
  413. assert isinstance(precision, (int, decimal.Decimal))
  414. return decimal.Decimal(10) ** (-precision)
  415. def format_decimal(
  416. number: float | decimal.Decimal | str,
  417. format: str | NumberPattern | None = None,
  418. locale: Locale | str | None = None,
  419. decimal_quantization: bool = True,
  420. group_separator: bool = True,
  421. *,
  422. numbering_system: Literal["default"] | str = "latn",
  423. ) -> str:
  424. """Return the given decimal number formatted for a specific locale.
  425. >>> format_decimal(1.2345, locale='en_US')
  426. u'1.234'
  427. >>> format_decimal(1.2346, locale='en_US')
  428. u'1.235'
  429. >>> format_decimal(-1.2346, locale='en_US')
  430. u'-1.235'
  431. >>> format_decimal(1.2345, locale='sv_SE')
  432. u'1,234'
  433. >>> format_decimal(1.2345, locale='de')
  434. u'1,234'
  435. >>> format_decimal(1.2345, locale='ar_EG', numbering_system='default')
  436. u'1٫234'
  437. >>> format_decimal(1.2345, locale='ar_EG', numbering_system='latn')
  438. u'1.234'
  439. The appropriate thousands grouping and the decimal separator are used for
  440. each locale:
  441. >>> format_decimal(12345.5, locale='en_US')
  442. u'12,345.5'
  443. By default the locale is allowed to truncate and round a high-precision
  444. number by forcing its format pattern onto the decimal part. You can bypass
  445. this behavior with the `decimal_quantization` parameter:
  446. >>> format_decimal(1.2346, locale='en_US')
  447. u'1.235'
  448. >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
  449. u'1.2346'
  450. >>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
  451. u'12345,67'
  452. >>> format_decimal(12345.67, locale='en_US', group_separator=True)
  453. u'12,345.67'
  454. :param number: the number to format
  455. :param format:
  456. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  457. :param decimal_quantization: Truncate and round high-precision numbers to
  458. the format pattern. Defaults to `True`.
  459. :param group_separator: Boolean to switch group separator on/off in a locale's
  460. number format.
  461. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  462. The special value "default" will use the default numbering system of the locale.
  463. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  464. """
  465. locale = Locale.parse(locale or LC_NUMERIC)
  466. if format is None:
  467. format = locale.decimal_formats[format]
  468. pattern = parse_pattern(format)
  469. return pattern.apply(
  470. number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
  471. def format_compact_decimal(
  472. number: float | decimal.Decimal | str,
  473. *,
  474. format_type: Literal["short", "long"] = "short",
  475. locale: Locale | str | None = None,
  476. fraction_digits: int = 0,
  477. numbering_system: Literal["default"] | str = "latn",
  478. ) -> str:
  479. """Return the given decimal number formatted for a specific locale in compact form.
  480. >>> format_compact_decimal(12345, format_type="short", locale='en_US')
  481. u'12K'
  482. >>> format_compact_decimal(12345, format_type="long", locale='en_US')
  483. u'12 thousand'
  484. >>> format_compact_decimal(12345, format_type="short", locale='en_US', fraction_digits=2)
  485. u'12.34K'
  486. >>> format_compact_decimal(1234567, format_type="short", locale="ja_JP")
  487. u'123万'
  488. >>> format_compact_decimal(2345678, format_type="long", locale="mk")
  489. u'2 милиони'
  490. >>> format_compact_decimal(21000000, format_type="long", locale="mk")
  491. u'21 милион'
  492. >>> format_compact_decimal(12345, format_type="short", locale='ar_EG', fraction_digits=2, numbering_system='default')
  493. u'12٫34\xa0ألف'
  494. :param number: the number to format
  495. :param format_type: Compact format to use ("short" or "long")
  496. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  497. :param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
  498. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  499. The special value "default" will use the default numbering system of the locale.
  500. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  501. """
  502. locale = Locale.parse(locale or LC_NUMERIC)
  503. compact_format = locale.compact_decimal_formats[format_type]
  504. number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
  505. # Did not find a format, fall back.
  506. if format is None:
  507. format = locale.decimal_formats[None]
  508. pattern = parse_pattern(format)
  509. return pattern.apply(number, locale, decimal_quantization=False, numbering_system=numbering_system)
  510. def _get_compact_format(
  511. number: float | decimal.Decimal | str,
  512. compact_format: LocaleDataDict,
  513. locale: Locale,
  514. fraction_digits: int,
  515. ) -> tuple[decimal.Decimal, NumberPattern | None]:
  516. """Returns the number after dividing by the unit and the format pattern to use.
  517. The algorithm is described here:
  518. https://www.unicode.org/reports/tr35/tr35-45/tr35-numbers.html#Compact_Number_Formats.
  519. """
  520. if not isinstance(number, decimal.Decimal):
  521. number = decimal.Decimal(str(number))
  522. if number.is_nan() or number.is_infinite():
  523. return number, None
  524. format = None
  525. for magnitude in sorted([int(m) for m in compact_format["other"]], reverse=True):
  526. if abs(number) >= magnitude:
  527. # check the pattern using "other" as the amount
  528. format = compact_format["other"][str(magnitude)]
  529. pattern = parse_pattern(format).pattern
  530. # if the pattern is "0", we do not divide the number
  531. if pattern == "0":
  532. break
  533. # otherwise, we need to divide the number by the magnitude but remove zeros
  534. # equal to the number of 0's in the pattern minus 1
  535. number = cast(decimal.Decimal, number / (magnitude // (10 ** (pattern.count("0") - 1))))
  536. # round to the number of fraction digits requested
  537. rounded = round(number, fraction_digits)
  538. # if the remaining number is singular, use the singular format
  539. plural_form = locale.plural_form(abs(number))
  540. if plural_form not in compact_format:
  541. plural_form = "other"
  542. if number == 1 and "1" in compact_format:
  543. plural_form = "1"
  544. format = compact_format[plural_form][str(magnitude)]
  545. number = rounded
  546. break
  547. return number, format
  548. class UnknownCurrencyFormatError(KeyError):
  549. """Exception raised when an unknown currency format is requested."""
  550. def format_currency(
  551. number: float | decimal.Decimal | str,
  552. currency: str,
  553. format: str | NumberPattern | None = None,
  554. locale: Locale | str | None = None,
  555. currency_digits: bool = True,
  556. format_type: Literal["name", "standard", "accounting"] = "standard",
  557. decimal_quantization: bool = True,
  558. group_separator: bool = True,
  559. *,
  560. numbering_system: Literal["default"] | str = "latn",
  561. ) -> str:
  562. """Return formatted currency value.
  563. >>> format_currency(1099.98, 'USD', locale='en_US')
  564. '$1,099.98'
  565. >>> format_currency(1099.98, 'USD', locale='es_CO')
  566. u'US$1.099,98'
  567. >>> format_currency(1099.98, 'EUR', locale='de_DE')
  568. u'1.099,98\\xa0\\u20ac'
  569. >>> format_currency(1099.98, 'EGP', locale='ar_EG', numbering_system='default')
  570. u'\u200f1٬099٫98\xa0ج.م.\u200f'
  571. The format can also be specified explicitly. The currency is
  572. placed with the '¤' sign. As the sign gets repeated the format
  573. expands (¤ being the symbol, ¤¤ is the currency abbreviation and
  574. ¤¤¤ is the full name of the currency):
  575. >>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
  576. u'EUR 1,099.98'
  577. >>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
  578. u'1,099.98 euros'
  579. Currencies usually have a specific number of decimal digits. This function
  580. favours that information over the given format:
  581. >>> format_currency(1099.98, 'JPY', locale='en_US')
  582. u'\\xa51,100'
  583. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
  584. u'1.099,98'
  585. However, the number of decimal digits can be overridden from the currency
  586. information, by setting the last parameter to ``False``:
  587. >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
  588. u'\\xa51,099.98'
  589. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
  590. u'1.099,98'
  591. If a format is not specified the type of currency format to use
  592. from the locale can be specified:
  593. >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
  594. u'\\u20ac1,099.98'
  595. When the given currency format type is not available, an exception is
  596. raised:
  597. >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
  598. Traceback (most recent call last):
  599. ...
  600. UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
  601. >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
  602. u'$101299.98'
  603. >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
  604. u'$101,299.98'
  605. You can also pass format_type='name' to use long display names. The order of
  606. the number and currency name, along with the correct localized plural form
  607. of the currency name, is chosen according to locale:
  608. >>> format_currency(1, 'USD', locale='en_US', format_type='name')
  609. u'1.00 US dollar'
  610. >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
  611. u'1,099.98 US dollars'
  612. >>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
  613. u'us ga dollar 1,099.98'
  614. By default the locale is allowed to truncate and round a high-precision
  615. number by forcing its format pattern onto the decimal part. You can bypass
  616. this behavior with the `decimal_quantization` parameter:
  617. >>> format_currency(1099.9876, 'USD', locale='en_US')
  618. u'$1,099.99'
  619. >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
  620. u'$1,099.9876'
  621. :param number: the number to format
  622. :param currency: the currency code
  623. :param format: the format string to use
  624. :param locale: the `Locale` object or locale identifier.
  625. Defaults to the system currency locale or numeric locale.
  626. :param currency_digits: use the currency's natural number of decimal digits
  627. :param format_type: the currency format type to use
  628. :param decimal_quantization: Truncate and round high-precision numbers to
  629. the format pattern. Defaults to `True`.
  630. :param group_separator: Boolean to switch group separator on/off in a locale's
  631. number format.
  632. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  633. The special value "default" will use the default numbering system of the locale.
  634. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  635. """
  636. locale = Locale.parse(locale or LC_MONETARY)
  637. if format_type == 'name':
  638. return _format_currency_long_name(
  639. number,
  640. currency,
  641. locale=locale,
  642. format=format,
  643. currency_digits=currency_digits,
  644. decimal_quantization=decimal_quantization,
  645. group_separator=group_separator,
  646. numbering_system=numbering_system,
  647. )
  648. if format:
  649. pattern = parse_pattern(format)
  650. else:
  651. try:
  652. pattern = locale.currency_formats[format_type]
  653. except KeyError:
  654. raise UnknownCurrencyFormatError(f"{format_type!r} is not a known currency format type") from None
  655. return pattern.apply(
  656. number, locale, currency=currency, currency_digits=currency_digits,
  657. decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
  658. def _format_currency_long_name(
  659. number: float | decimal.Decimal | str,
  660. currency: str,
  661. *,
  662. locale: Locale,
  663. format: str | NumberPattern | None,
  664. currency_digits: bool,
  665. decimal_quantization: bool,
  666. group_separator: bool,
  667. numbering_system: Literal["default"] | str,
  668. ) -> str:
  669. # Algorithm described here:
  670. # https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
  671. # Step 1.
  672. # There are no examples of items with explicit count (0 or 1) in current
  673. # locale data. So there is no point implementing that.
  674. # Step 2.
  675. # Correct number to numeric type, important for looking up plural rules:
  676. number_n = float(number) if isinstance(number, str) else number
  677. # Step 3.
  678. unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
  679. # Step 4.
  680. display_name = get_currency_name(currency, count=number_n, locale=locale)
  681. # Step 5.
  682. if not format:
  683. format = locale.decimal_formats[None]
  684. pattern = parse_pattern(format)
  685. number_part = pattern.apply(
  686. number, locale, currency=currency, currency_digits=currency_digits,
  687. decimal_quantization=decimal_quantization, group_separator=group_separator, numbering_system=numbering_system)
  688. return unit_pattern.format(number_part, display_name)
  689. def format_compact_currency(
  690. number: float | decimal.Decimal | str,
  691. currency: str,
  692. *,
  693. format_type: Literal["short"] = "short",
  694. locale: Locale | str | None = None,
  695. fraction_digits: int = 0,
  696. numbering_system: Literal["default"] | str = "latn",
  697. ) -> str:
  698. """Format a number as a currency value in compact form.
  699. >>> format_compact_currency(12345, 'USD', locale='en_US')
  700. u'$12K'
  701. >>> format_compact_currency(123456789, 'USD', locale='en_US', fraction_digits=2)
  702. u'$123.46M'
  703. >>> format_compact_currency(123456789, 'EUR', locale='de_DE', fraction_digits=1)
  704. '123,5\xa0Mio.\xa0€'
  705. :param number: the number to format
  706. :param currency: the currency code
  707. :param format_type: the compact format type to use. Defaults to "short".
  708. :param locale: the `Locale` object or locale identifier.
  709. Defaults to the system currency locale or numeric locale.
  710. :param fraction_digits: Number of digits after the decimal point to use. Defaults to `0`.
  711. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  712. The special value "default" will use the default numbering system of the locale.
  713. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  714. """
  715. locale = Locale.parse(locale or LC_MONETARY)
  716. try:
  717. compact_format = locale.compact_currency_formats[format_type]
  718. except KeyError as error:
  719. raise UnknownCurrencyFormatError(f"{format_type!r} is not a known compact currency format type") from error
  720. number, format = _get_compact_format(number, compact_format, locale, fraction_digits)
  721. # Did not find a format, fall back.
  722. if format is None or "¤" not in str(format):
  723. # find first format that has a currency symbol
  724. for magnitude in compact_format['other']:
  725. format = compact_format['other'][magnitude].pattern
  726. if '¤' not in format:
  727. continue
  728. # remove characters that are not the currency symbol, 0's or spaces
  729. format = re.sub(r'[^0\s\¤]', '', format)
  730. # compress adjacent spaces into one
  731. format = re.sub(r'(\s)\s+', r'\1', format).strip()
  732. break
  733. if format is None:
  734. raise ValueError('No compact currency format found for the given number and locale.')
  735. pattern = parse_pattern(format)
  736. return pattern.apply(number, locale, currency=currency, currency_digits=False, decimal_quantization=False,
  737. numbering_system=numbering_system)
  738. def format_percent(
  739. number: float | decimal.Decimal | str,
  740. format: str | NumberPattern | None = None,
  741. locale: Locale | str | None = None,
  742. decimal_quantization: bool = True,
  743. group_separator: bool = True,
  744. *,
  745. numbering_system: Literal["default"] | str = "latn",
  746. ) -> str:
  747. """Return formatted percent value for a specific locale.
  748. >>> format_percent(0.34, locale='en_US')
  749. u'34%'
  750. >>> format_percent(25.1234, locale='en_US')
  751. u'2,512%'
  752. >>> format_percent(25.1234, locale='sv_SE')
  753. u'2\\xa0512\\xa0%'
  754. >>> format_percent(25.1234, locale='ar_EG', numbering_system='default')
  755. u'2٬512%'
  756. The format pattern can also be specified explicitly:
  757. >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
  758. u'25,123\u2030'
  759. By default the locale is allowed to truncate and round a high-precision
  760. number by forcing its format pattern onto the decimal part. You can bypass
  761. this behavior with the `decimal_quantization` parameter:
  762. >>> format_percent(23.9876, locale='en_US')
  763. u'2,399%'
  764. >>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
  765. u'2,398.76%'
  766. >>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
  767. u'22929112%'
  768. >>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
  769. u'22.929.112%'
  770. :param number: the percent number to format
  771. :param format:
  772. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  773. :param decimal_quantization: Truncate and round high-precision numbers to
  774. the format pattern. Defaults to `True`.
  775. :param group_separator: Boolean to switch group separator on/off in a locale's
  776. number format.
  777. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  778. The special value "default" will use the default numbering system of the locale.
  779. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  780. """
  781. locale = Locale.parse(locale or LC_NUMERIC)
  782. if not format:
  783. format = locale.percent_formats[None]
  784. pattern = parse_pattern(format)
  785. return pattern.apply(
  786. number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator,
  787. numbering_system=numbering_system,
  788. )
  789. def format_scientific(
  790. number: float | decimal.Decimal | str,
  791. format: str | NumberPattern | None = None,
  792. locale: Locale | str | None = None,
  793. decimal_quantization: bool = True,
  794. *,
  795. numbering_system: Literal["default"] | str = "latn",
  796. ) -> str:
  797. """Return value formatted in scientific notation for a specific locale.
  798. >>> format_scientific(10000, locale='en_US')
  799. u'1E4'
  800. >>> format_scientific(10000, locale='ar_EG', numbering_system='default')
  801. u'1أس4'
  802. The format pattern can also be specified explicitly:
  803. >>> format_scientific(1234567, u'##0.##E00', locale='en_US')
  804. u'1.23E06'
  805. By default the locale is allowed to truncate and round a high-precision
  806. number by forcing its format pattern onto the decimal part. You can bypass
  807. this behavior with the `decimal_quantization` parameter:
  808. >>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
  809. u'1.23E3'
  810. >>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
  811. u'1.2349876E3'
  812. :param number: the number to format
  813. :param format:
  814. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  815. :param decimal_quantization: Truncate and round high-precision numbers to
  816. the format pattern. Defaults to `True`.
  817. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  818. The special value "default" will use the default numbering system of the locale.
  819. :raise `UnsupportedNumberingSystemError`: If the numbering system is not supported by the locale.
  820. """
  821. locale = Locale.parse(locale or LC_NUMERIC)
  822. if not format:
  823. format = locale.scientific_formats[None]
  824. pattern = parse_pattern(format)
  825. return pattern.apply(
  826. number, locale, decimal_quantization=decimal_quantization, numbering_system=numbering_system)
  827. class NumberFormatError(ValueError):
  828. """Exception raised when a string cannot be parsed into a number."""
  829. def __init__(self, message: str, suggestions: list[str] | None = None) -> None:
  830. super().__init__(message)
  831. #: a list of properly formatted numbers derived from the invalid input
  832. self.suggestions = suggestions
  833. SPACE_CHARS = {
  834. ' ', # space
  835. '\xa0', # no-break space
  836. '\u202f', # narrow no-break space
  837. }
  838. SPACE_CHARS_RE = re.compile('|'.join(SPACE_CHARS))
  839. def parse_number(
  840. string: str,
  841. locale: Locale | str | None = None,
  842. *,
  843. numbering_system: Literal["default"] | str = "latn",
  844. ) -> int:
  845. """Parse localized number string into an integer.
  846. >>> parse_number('1,099', locale='en_US')
  847. 1099
  848. >>> parse_number('1.099', locale='de_DE')
  849. 1099
  850. When the given string cannot be parsed, an exception is raised:
  851. >>> parse_number('1.099,98', locale='de')
  852. Traceback (most recent call last):
  853. ...
  854. NumberFormatError: '1.099,98' is not a valid number
  855. :param string: the string to parse
  856. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  857. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  858. The special value "default" will use the default numbering system of the locale.
  859. :return: the parsed number
  860. :raise `NumberFormatError`: if the string can not be converted to a number
  861. :raise `UnsupportedNumberingSystemError`: if the numbering system is not supported by the locale.
  862. """
  863. group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
  864. if (
  865. group_symbol in SPACE_CHARS and # if the grouping symbol is a kind of space,
  866. group_symbol not in string and # and the string to be parsed does not contain it,
  867. SPACE_CHARS_RE.search(string) # but it does contain any other kind of space instead,
  868. ):
  869. # ... it's reasonable to assume it is taking the place of the grouping symbol.
  870. string = SPACE_CHARS_RE.sub(group_symbol, string)
  871. try:
  872. return int(string.replace(group_symbol, ''))
  873. except ValueError as ve:
  874. raise NumberFormatError(f"{string!r} is not a valid number") from ve
  875. def parse_decimal(
  876. string: str,
  877. locale: Locale | str | None = None,
  878. strict: bool = False,
  879. *,
  880. numbering_system: Literal["default"] | str = "latn",
  881. ) -> decimal.Decimal:
  882. """Parse localized decimal string into a decimal.
  883. >>> parse_decimal('1,099.98', locale='en_US')
  884. Decimal('1099.98')
  885. >>> parse_decimal('1.099,98', locale='de')
  886. Decimal('1099.98')
  887. >>> parse_decimal('12 345,123', locale='ru')
  888. Decimal('12345.123')
  889. >>> parse_decimal('1٬099٫98', locale='ar_EG', numbering_system='default')
  890. Decimal('1099.98')
  891. When the given string cannot be parsed, an exception is raised:
  892. >>> parse_decimal('2,109,998', locale='de')
  893. Traceback (most recent call last):
  894. ...
  895. NumberFormatError: '2,109,998' is not a valid decimal number
  896. If `strict` is set to `True` and the given string contains a number
  897. formatted in an irregular way, an exception is raised:
  898. >>> parse_decimal('30.00', locale='de', strict=True)
  899. Traceback (most recent call last):
  900. ...
  901. NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
  902. >>> parse_decimal('0.00', locale='de', strict=True)
  903. Traceback (most recent call last):
  904. ...
  905. NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
  906. :param string: the string to parse
  907. :param locale: the `Locale` object or locale identifier. Defaults to the system numeric locale.
  908. :param strict: controls whether numbers formatted in a weird way are
  909. accepted or rejected
  910. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  911. The special value "default" will use the default numbering system of the locale.
  912. :raise NumberFormatError: if the string can not be converted to a
  913. decimal number
  914. :raise UnsupportedNumberingSystemError: if the numbering system is not supported by the locale.
  915. """
  916. locale = Locale.parse(locale or LC_NUMERIC)
  917. group_symbol = get_group_symbol(locale, numbering_system=numbering_system)
  918. decimal_symbol = get_decimal_symbol(locale, numbering_system=numbering_system)
  919. if not strict and (
  920. group_symbol in SPACE_CHARS and # if the grouping symbol is a kind of space,
  921. group_symbol not in string and # and the string to be parsed does not contain it,
  922. SPACE_CHARS_RE.search(string) # but it does contain any other kind of space instead,
  923. ):
  924. # ... it's reasonable to assume it is taking the place of the grouping symbol.
  925. string = SPACE_CHARS_RE.sub(group_symbol, string)
  926. try:
  927. parsed = decimal.Decimal(string.replace(group_symbol, '')
  928. .replace(decimal_symbol, '.'))
  929. except decimal.InvalidOperation as exc:
  930. raise NumberFormatError(f"{string!r} is not a valid decimal number") from exc
  931. if strict and group_symbol in string:
  932. proper = format_decimal(parsed, locale=locale, decimal_quantization=False, numbering_system=numbering_system)
  933. if string != proper and proper != _remove_trailing_zeros_after_decimal(string, decimal_symbol):
  934. try:
  935. parsed_alt = decimal.Decimal(string.replace(decimal_symbol, '')
  936. .replace(group_symbol, '.'))
  937. except decimal.InvalidOperation as exc:
  938. raise NumberFormatError(
  939. f"{string!r} is not a properly formatted decimal number. "
  940. f"Did you mean {proper!r}?",
  941. suggestions=[proper],
  942. ) from exc
  943. else:
  944. proper_alt = format_decimal(
  945. parsed_alt,
  946. locale=locale,
  947. decimal_quantization=False,
  948. numbering_system=numbering_system,
  949. )
  950. if proper_alt == proper:
  951. raise NumberFormatError(
  952. f"{string!r} is not a properly formatted decimal number. "
  953. f"Did you mean {proper!r}?",
  954. suggestions=[proper],
  955. )
  956. else:
  957. raise NumberFormatError(
  958. f"{string!r} is not a properly formatted decimal number. "
  959. f"Did you mean {proper!r}? Or maybe {proper_alt!r}?",
  960. suggestions=[proper, proper_alt],
  961. )
  962. return parsed
  963. def _remove_trailing_zeros_after_decimal(string: str, decimal_symbol: str) -> str:
  964. """
  965. Remove trailing zeros from the decimal part of a numeric string.
  966. This function takes a string representing a numeric value and a decimal symbol.
  967. It removes any trailing zeros that appear after the decimal symbol in the number.
  968. If the decimal part becomes empty after removing trailing zeros, the decimal symbol
  969. is also removed. If the string does not contain the decimal symbol, it is returned unchanged.
  970. :param string: The numeric string from which to remove trailing zeros.
  971. :type string: str
  972. :param decimal_symbol: The symbol used to denote the decimal point.
  973. :type decimal_symbol: str
  974. :return: The numeric string with trailing zeros removed from its decimal part.
  975. :rtype: str
  976. Example:
  977. >>> _remove_trailing_zeros_after_decimal("123.4500", ".")
  978. '123.45'
  979. >>> _remove_trailing_zeros_after_decimal("100.000", ".")
  980. '100'
  981. >>> _remove_trailing_zeros_after_decimal("100", ".")
  982. '100'
  983. """
  984. integer_part, _, decimal_part = string.partition(decimal_symbol)
  985. if decimal_part:
  986. decimal_part = decimal_part.rstrip("0")
  987. if decimal_part:
  988. return integer_part + decimal_symbol + decimal_part
  989. return integer_part
  990. return string
  991. PREFIX_END = r'[^0-9@#.,]'
  992. NUMBER_TOKEN = r'[0-9@#.,E+]'
  993. PREFIX_PATTERN = r"(?P<prefix>(?:'[^']*'|%s)*)" % PREFIX_END
  994. NUMBER_PATTERN = r"(?P<number>%s*)" % NUMBER_TOKEN
  995. SUFFIX_PATTERN = r"(?P<suffix>.*)"
  996. number_re = re.compile(f"{PREFIX_PATTERN}{NUMBER_PATTERN}{SUFFIX_PATTERN}")
  997. def parse_grouping(p: str) -> tuple[int, int]:
  998. """Parse primary and secondary digit grouping
  999. >>> parse_grouping('##')
  1000. (1000, 1000)
  1001. >>> parse_grouping('#,###')
  1002. (3, 3)
  1003. >>> parse_grouping('#,####,###')
  1004. (3, 4)
  1005. """
  1006. width = len(p)
  1007. g1 = p.rfind(',')
  1008. if g1 == -1:
  1009. return 1000, 1000
  1010. g1 = width - g1 - 1
  1011. g2 = p[:-g1 - 1].rfind(',')
  1012. if g2 == -1:
  1013. return g1, g1
  1014. g2 = width - g1 - g2 - 2
  1015. return g1, g2
  1016. def parse_pattern(pattern: NumberPattern | str) -> NumberPattern:
  1017. """Parse number format patterns"""
  1018. if isinstance(pattern, NumberPattern):
  1019. return pattern
  1020. def _match_number(pattern):
  1021. rv = number_re.search(pattern)
  1022. if rv is None:
  1023. raise ValueError(f"Invalid number pattern {pattern!r}")
  1024. return rv.groups()
  1025. pos_pattern = pattern
  1026. # Do we have a negative subpattern?
  1027. if ';' in pattern:
  1028. pos_pattern, neg_pattern = pattern.split(';', 1)
  1029. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  1030. neg_prefix, _, neg_suffix = _match_number(neg_pattern)
  1031. else:
  1032. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  1033. neg_prefix = f"-{pos_prefix}"
  1034. neg_suffix = pos_suffix
  1035. if 'E' in number:
  1036. number, exp = number.split('E', 1)
  1037. else:
  1038. exp = None
  1039. if '@' in number and '.' in number and '0' in number:
  1040. raise ValueError('Significant digit patterns can not contain "@" or "0"')
  1041. if '.' in number:
  1042. integer, fraction = number.rsplit('.', 1)
  1043. else:
  1044. integer = number
  1045. fraction = ''
  1046. def parse_precision(p):
  1047. """Calculate the min and max allowed digits"""
  1048. min = max = 0
  1049. for c in p:
  1050. if c in '@0':
  1051. min += 1
  1052. max += 1
  1053. elif c == '#':
  1054. max += 1
  1055. elif c == ',':
  1056. continue
  1057. else:
  1058. break
  1059. return min, max
  1060. int_prec = parse_precision(integer)
  1061. frac_prec = parse_precision(fraction)
  1062. if exp:
  1063. exp_plus = exp.startswith('+')
  1064. exp = exp.lstrip('+')
  1065. exp_prec = parse_precision(exp)
  1066. else:
  1067. exp_plus = None
  1068. exp_prec = None
  1069. grouping = parse_grouping(integer)
  1070. return NumberPattern(pattern, (pos_prefix, neg_prefix),
  1071. (pos_suffix, neg_suffix), grouping,
  1072. int_prec, frac_prec,
  1073. exp_prec, exp_plus, number)
  1074. class NumberPattern:
  1075. def __init__(
  1076. self,
  1077. pattern: str,
  1078. prefix: tuple[str, str],
  1079. suffix: tuple[str, str],
  1080. grouping: tuple[int, int],
  1081. int_prec: tuple[int, int],
  1082. frac_prec: tuple[int, int],
  1083. exp_prec: tuple[int, int] | None,
  1084. exp_plus: bool | None,
  1085. number_pattern: str | None = None,
  1086. ) -> None:
  1087. # Metadata of the decomposed parsed pattern.
  1088. self.pattern = pattern
  1089. self.prefix = prefix
  1090. self.suffix = suffix
  1091. self.number_pattern = number_pattern
  1092. self.grouping = grouping
  1093. self.int_prec = int_prec
  1094. self.frac_prec = frac_prec
  1095. self.exp_prec = exp_prec
  1096. self.exp_plus = exp_plus
  1097. self.scale = self.compute_scale()
  1098. def __repr__(self) -> str:
  1099. return f"<{type(self).__name__} {self.pattern!r}>"
  1100. def compute_scale(self) -> Literal[0, 2, 3]:
  1101. """Return the scaling factor to apply to the number before rendering.
  1102. Auto-set to a factor of 2 or 3 if presence of a ``%`` or ``‰`` sign is
  1103. detected in the prefix or suffix of the pattern. Default is to not mess
  1104. with the scale at all and keep it to 0.
  1105. """
  1106. scale = 0
  1107. if '%' in ''.join(self.prefix + self.suffix):
  1108. scale = 2
  1109. elif '‰' in ''.join(self.prefix + self.suffix):
  1110. scale = 3
  1111. return scale
  1112. def scientific_notation_elements(
  1113. self,
  1114. value: decimal.Decimal,
  1115. locale: Locale | str | None,
  1116. *,
  1117. numbering_system: Literal["default"] | str = "latn",
  1118. ) -> tuple[decimal.Decimal, int, str]:
  1119. """ Returns normalized scientific notation components of a value.
  1120. """
  1121. # Normalize value to only have one lead digit.
  1122. exp = value.adjusted()
  1123. value = value * get_decimal_quantum(exp)
  1124. assert value.adjusted() == 0
  1125. # Shift exponent and value by the minimum number of leading digits
  1126. # imposed by the rendering pattern. And always make that number
  1127. # greater or equal to 1.
  1128. lead_shift = max([1, min(self.int_prec)]) - 1
  1129. exp = exp - lead_shift
  1130. value = value * get_decimal_quantum(-lead_shift)
  1131. # Get exponent sign symbol.
  1132. exp_sign = ''
  1133. if exp < 0:
  1134. exp_sign = get_minus_sign_symbol(locale, numbering_system=numbering_system)
  1135. elif self.exp_plus:
  1136. exp_sign = get_plus_sign_symbol(locale, numbering_system=numbering_system)
  1137. # Normalize exponent value now that we have the sign.
  1138. exp = abs(exp)
  1139. return value, exp, exp_sign
  1140. def apply(
  1141. self,
  1142. value: float | decimal.Decimal | str,
  1143. locale: Locale | str | None,
  1144. currency: str | None = None,
  1145. currency_digits: bool = True,
  1146. decimal_quantization: bool = True,
  1147. force_frac: tuple[int, int] | None = None,
  1148. group_separator: bool = True,
  1149. *,
  1150. numbering_system: Literal["default"] | str = "latn",
  1151. ):
  1152. """Renders into a string a number following the defined pattern.
  1153. Forced decimal quantization is active by default so we'll produce a
  1154. number string that is strictly following CLDR pattern definitions.
  1155. :param value: The value to format. If this is not a Decimal object,
  1156. it will be cast to one.
  1157. :type value: decimal.Decimal|float|int
  1158. :param locale: The locale to use for formatting.
  1159. :type locale: str|babel.core.Locale
  1160. :param currency: Which currency, if any, to format as.
  1161. :type currency: str|None
  1162. :param currency_digits: Whether or not to use the currency's precision.
  1163. If false, the pattern's precision is used.
  1164. :type currency_digits: bool
  1165. :param decimal_quantization: Whether decimal numbers should be forcibly
  1166. quantized to produce a formatted output
  1167. strictly matching the CLDR definition for
  1168. the locale.
  1169. :type decimal_quantization: bool
  1170. :param force_frac: DEPRECATED - a forced override for `self.frac_prec`
  1171. for a single formatting invocation.
  1172. :param group_separator: Whether to use the locale's number group separator.
  1173. :param numbering_system: The numbering system used for formatting number symbols. Defaults to "latn".
  1174. The special value "default" will use the default numbering system of the locale.
  1175. :return: Formatted decimal string.
  1176. :rtype: str
  1177. :raise UnsupportedNumberingSystemError: If the numbering system is not supported by the locale.
  1178. """
  1179. if not isinstance(value, decimal.Decimal):
  1180. value = decimal.Decimal(str(value))
  1181. value = value.scaleb(self.scale)
  1182. # Separate the absolute value from its sign.
  1183. is_negative = int(value.is_signed())
  1184. value = abs(value).normalize()
  1185. # Prepare scientific notation metadata.
  1186. if self.exp_prec:
  1187. value, exp, exp_sign = self.scientific_notation_elements(value, locale, numbering_system=numbering_system)
  1188. # Adjust the precision of the fractional part and force it to the
  1189. # currency's if necessary.
  1190. if force_frac:
  1191. # TODO (3.x?): Remove this parameter
  1192. warnings.warn(
  1193. 'The force_frac parameter to NumberPattern.apply() is deprecated.',
  1194. DeprecationWarning,
  1195. stacklevel=2,
  1196. )
  1197. frac_prec = force_frac
  1198. elif currency and currency_digits:
  1199. frac_prec = (get_currency_precision(currency), ) * 2
  1200. else:
  1201. frac_prec = self.frac_prec
  1202. # Bump decimal precision to the natural precision of the number if it
  1203. # exceeds the one we're about to use. This adaptative precision is only
  1204. # triggered if the decimal quantization is disabled or if a scientific
  1205. # notation pattern has a missing mandatory fractional part (as in the
  1206. # default '#E0' pattern). This special case has been extensively
  1207. # discussed at https://github.com/python-babel/babel/pull/494#issuecomment-307649969 .
  1208. if not decimal_quantization or (self.exp_prec and frac_prec == (0, 0)):
  1209. frac_prec = (frac_prec[0], max([frac_prec[1], get_decimal_precision(value)]))
  1210. # Render scientific notation.
  1211. if self.exp_prec:
  1212. number = ''.join([
  1213. self._quantize_value(value, locale, frac_prec, group_separator, numbering_system=numbering_system),
  1214. get_exponential_symbol(locale, numbering_system=numbering_system),
  1215. exp_sign, # type: ignore # exp_sign is always defined here
  1216. 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
  1217. ])
  1218. # Is it a significant digits pattern?
  1219. elif '@' in self.pattern:
  1220. text = self._format_significant(value,
  1221. self.int_prec[0],
  1222. self.int_prec[1])
  1223. a, sep, b = text.partition(".")
  1224. number = self._format_int(a, 0, 1000, locale, numbering_system=numbering_system)
  1225. if sep:
  1226. number += get_decimal_symbol(locale, numbering_system=numbering_system) + b
  1227. # A normal number pattern.
  1228. else:
  1229. number = self._quantize_value(value, locale, frac_prec, group_separator, numbering_system=numbering_system)
  1230. retval = ''.join([
  1231. self.prefix[is_negative],
  1232. number if self.number_pattern != '' else '',
  1233. self.suffix[is_negative]])
  1234. if '¤' in retval and currency is not None:
  1235. retval = retval.replace('¤¤¤', get_currency_name(currency, value, locale))
  1236. retval = retval.replace('¤¤', currency.upper())
  1237. retval = retval.replace('¤', get_currency_symbol(currency, locale))
  1238. # remove single quotes around text, except for doubled single quotes
  1239. # which are replaced with a single quote
  1240. retval = re.sub(r"'([^']*)'", lambda m: m.group(1) or "'", retval)
  1241. return retval
  1242. #
  1243. # This is one tricky piece of code. The idea is to rely as much as possible
  1244. # on the decimal module to minimize the amount of code.
  1245. #
  1246. # Conceptually, the implementation of this method can be summarized in the
  1247. # following steps:
  1248. #
  1249. # - Move or shift the decimal point (i.e. the exponent) so the maximum
  1250. # amount of significant digits fall into the integer part (i.e. to the
  1251. # left of the decimal point)
  1252. #
  1253. # - Round the number to the nearest integer, discarding all the fractional
  1254. # part which contained extra digits to be eliminated
  1255. #
  1256. # - Convert the rounded integer to a string, that will contain the final
  1257. # sequence of significant digits already trimmed to the maximum
  1258. #
  1259. # - Restore the original position of the decimal point, potentially
  1260. # padding with zeroes on either side
  1261. #
  1262. def _format_significant(self, value: decimal.Decimal, minimum: int, maximum: int) -> str:
  1263. exp = value.adjusted()
  1264. scale = maximum - 1 - exp
  1265. digits = str(value.scaleb(scale).quantize(decimal.Decimal(1)))
  1266. if scale <= 0:
  1267. result = digits + '0' * -scale
  1268. else:
  1269. intpart = digits[:-scale]
  1270. i = len(intpart)
  1271. j = i + max(minimum - i, 0)
  1272. result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format(
  1273. intpart=intpart or '0',
  1274. pad='',
  1275. fill=-min(exp + 1, 0),
  1276. fracpart=digits[i:j],
  1277. fracextra=digits[j:].rstrip('0'),
  1278. ).rstrip('.')
  1279. return result
  1280. def _format_int(
  1281. self,
  1282. value: str,
  1283. min: int,
  1284. max: int,
  1285. locale: Locale | str | None,
  1286. *,
  1287. numbering_system: Literal["default"] | str,
  1288. ) -> str:
  1289. width = len(value)
  1290. if width < min:
  1291. value = '0' * (min - width) + value
  1292. gsize = self.grouping[0]
  1293. ret = ''
  1294. symbol = get_group_symbol(locale, numbering_system=numbering_system)
  1295. while len(value) > gsize:
  1296. ret = symbol + value[-gsize:] + ret
  1297. value = value[:-gsize]
  1298. gsize = self.grouping[1]
  1299. return value + ret
  1300. def _quantize_value(
  1301. self,
  1302. value: decimal.Decimal,
  1303. locale: Locale | str | None,
  1304. frac_prec: tuple[int, int],
  1305. group_separator: bool,
  1306. *,
  1307. numbering_system: Literal["default"] | str,
  1308. ) -> str:
  1309. # If the number is +/-Infinity, we can't quantize it
  1310. if value.is_infinite():
  1311. return get_infinity_symbol(locale, numbering_system=numbering_system)
  1312. quantum = get_decimal_quantum(frac_prec[1])
  1313. rounded = value.quantize(quantum)
  1314. a, sep, b = f"{rounded:f}".partition(".")
  1315. integer_part = a
  1316. if group_separator:
  1317. integer_part = self._format_int(a, self.int_prec[0], self.int_prec[1], locale, numbering_system=numbering_system)
  1318. number = integer_part + self._format_frac(b or '0', locale=locale, force_frac=frac_prec, numbering_system=numbering_system)
  1319. return number
  1320. def _format_frac(
  1321. self,
  1322. value: str,
  1323. locale: Locale | str | None,
  1324. force_frac: tuple[int, int] | None = None,
  1325. *,
  1326. numbering_system: Literal["default"] | str,
  1327. ) -> str:
  1328. min, max = force_frac or self.frac_prec
  1329. if len(value) < min:
  1330. value += ('0' * (min - len(value)))
  1331. if max == 0 or (min == 0 and int(value) == 0):
  1332. return ''
  1333. while len(value) > min and value[-1] == '0':
  1334. value = value[:-1]
  1335. return get_decimal_symbol(locale, numbering_system=numbering_system) + value