numbers.py 62 KB

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