numbers.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.numbers
  4. ~~~~~~~~~~~~~
  5. Locale dependent formatting and parsing of numeric data.
  6. The default locale for the functions in this module is determined by the
  7. following environment variables, in that order:
  8. * ``LC_NUMERIC``,
  9. * ``LC_ALL``, and
  10. * ``LANG``
  11. :copyright: (c) 2013-2021 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. import re
  18. from datetime import date as date_, datetime as datetime_
  19. import warnings
  20. from babel.core import default_locale, Locale, get_global
  21. from babel._compat import decimal, string_types
  22. try:
  23. # Python 2
  24. long
  25. except NameError:
  26. # Python 3
  27. long = int
  28. LC_NUMERIC = default_locale('LC_NUMERIC')
  29. class UnknownCurrencyError(Exception):
  30. """Exception thrown when a currency is requested for which no data is available.
  31. """
  32. def __init__(self, identifier):
  33. """Create the exception.
  34. :param identifier: the identifier string of the unsupported currency
  35. """
  36. Exception.__init__(self, 'Unknown currency %r.' % identifier)
  37. #: The identifier of the locale that could not be found.
  38. self.identifier = identifier
  39. def list_currencies(locale=None):
  40. """ Return a `set` of normalized currency codes.
  41. .. versionadded:: 2.5.0
  42. :param locale: filters returned currency codes by the provided locale.
  43. Expected to be a locale instance or code. If no locale is
  44. provided, returns the list of all currencies from all
  45. locales.
  46. """
  47. # Get locale-scoped currencies.
  48. if locale:
  49. currencies = Locale.parse(locale).currencies.keys()
  50. else:
  51. currencies = get_global('all_currencies')
  52. return set(currencies)
  53. def validate_currency(currency, locale=None):
  54. """ Check the currency code is recognized by Babel.
  55. Accepts a ``locale`` parameter for fined-grained validation, working as
  56. the one defined above in ``list_currencies()`` method.
  57. Raises a `UnknownCurrencyError` exception if the currency is unknown to Babel.
  58. """
  59. if currency not in list_currencies(locale):
  60. raise UnknownCurrencyError(currency)
  61. def is_currency(currency, locale=None):
  62. """ Returns `True` only if a currency is recognized by Babel.
  63. This method always return a Boolean and never raise.
  64. """
  65. if not currency or not isinstance(currency, string_types):
  66. return False
  67. try:
  68. validate_currency(currency, locale)
  69. except UnknownCurrencyError:
  70. return False
  71. return True
  72. def normalize_currency(currency, locale=None):
  73. """Returns the normalized sting of any currency code.
  74. Accepts a ``locale`` parameter for fined-grained validation, working as
  75. the one defined above in ``list_currencies()`` method.
  76. Returns None if the currency is unknown to Babel.
  77. """
  78. if isinstance(currency, string_types):
  79. currency = currency.upper()
  80. if not is_currency(currency, locale):
  81. return
  82. return currency
  83. def get_currency_name(currency, count=None, locale=LC_NUMERIC):
  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. """
  93. loc = Locale.parse(locale)
  94. if count is not None:
  95. plural_form = loc.plural_form(count)
  96. plural_names = loc._data['currency_names_plural']
  97. if currency in plural_names:
  98. return plural_names[currency][plural_form]
  99. return loc.currencies.get(currency, currency)
  100. def get_currency_symbol(currency, locale=LC_NUMERIC):
  101. """Return the symbol used by the locale for the specified currency.
  102. >>> get_currency_symbol('USD', locale='en_US')
  103. u'$'
  104. :param currency: the currency code.
  105. :param locale: the `Locale` object or locale identifier.
  106. """
  107. return Locale.parse(locale).currency_symbols.get(currency, currency)
  108. def get_currency_precision(currency):
  109. """Return currency's precision.
  110. Precision is the number of decimals found after the decimal point in the
  111. currency's format pattern.
  112. .. versionadded:: 2.5.0
  113. :param currency: the currency code.
  114. """
  115. precisions = get_global('currency_fractions')
  116. return precisions.get(currency, precisions['DEFAULT'])[0]
  117. def get_currency_unit_pattern(currency, count=None, locale=LC_NUMERIC):
  118. """
  119. Return the unit pattern used for long display of a currency value
  120. for a given locale.
  121. This is a string containing ``{0}`` where the numeric part
  122. should be substituted and ``{1}`` where the currency long display
  123. name should be substituted.
  124. >>> get_currency_unit_pattern('USD', locale='en_US', count=10)
  125. u'{0} {1}'
  126. .. versionadded:: 2.7.0
  127. :param currency: the currency code.
  128. :param count: the optional count. If provided the unit
  129. pattern for that number will be returned.
  130. :param locale: the `Locale` object or locale identifier.
  131. """
  132. loc = Locale.parse(locale)
  133. if count is not None:
  134. plural_form = loc.plural_form(count)
  135. try:
  136. return loc._data['currency_unit_patterns'][plural_form]
  137. except LookupError:
  138. # Fall back to 'other'
  139. pass
  140. return loc._data['currency_unit_patterns']['other']
  141. def get_territory_currencies(territory, start_date=None, end_date=None,
  142. tender=True, non_tender=False,
  143. include_details=False):
  144. """Returns the list of currencies for the given territory that are valid for
  145. the given date range. In addition to that the currency database
  146. distinguishes between tender and non-tender currencies. By default only
  147. tender currencies are returned.
  148. The return value is a list of all currencies roughly ordered by the time
  149. of when the currency became active. The longer the currency is being in
  150. use the more to the left of the list it will be.
  151. The start date defaults to today. If no end date is given it will be the
  152. same as the start date. Otherwise a range can be defined. For instance
  153. this can be used to find the currencies in use in Austria between 1995 and
  154. 2011:
  155. >>> from datetime import date
  156. >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
  157. ['ATS', 'EUR']
  158. Likewise it's also possible to find all the currencies in use on a
  159. single date:
  160. >>> get_territory_currencies('AT', date(1995, 1, 1))
  161. ['ATS']
  162. >>> get_territory_currencies('AT', date(2011, 1, 1))
  163. ['EUR']
  164. By default the return value only includes tender currencies. This
  165. however can be changed:
  166. >>> get_territory_currencies('US')
  167. ['USD']
  168. >>> get_territory_currencies('US', tender=False, non_tender=True,
  169. ... start_date=date(2014, 1, 1))
  170. ['USN', 'USS']
  171. .. versionadded:: 2.0
  172. :param territory: the name of the territory to find the currency for.
  173. :param start_date: the start date. If not given today is assumed.
  174. :param end_date: the end date. If not given the start date is assumed.
  175. :param tender: controls whether tender currencies should be included.
  176. :param non_tender: controls whether non-tender currencies should be
  177. included.
  178. :param include_details: if set to `True`, instead of returning currency
  179. codes the return value will be dictionaries
  180. with detail information. In that case each
  181. dictionary will have the keys ``'currency'``,
  182. ``'from'``, ``'to'``, and ``'tender'``.
  183. """
  184. currencies = get_global('territory_currencies')
  185. if start_date is None:
  186. start_date = date_.today()
  187. elif isinstance(start_date, datetime_):
  188. start_date = start_date.date()
  189. if end_date is None:
  190. end_date = start_date
  191. elif isinstance(end_date, datetime_):
  192. end_date = end_date.date()
  193. curs = currencies.get(territory.upper(), ())
  194. # TODO: validate that the territory exists
  195. def _is_active(start, end):
  196. return (start is None or start <= end_date) and \
  197. (end is None or end >= start_date)
  198. result = []
  199. for currency_code, start, end, is_tender in curs:
  200. if start:
  201. start = date_(*start)
  202. if end:
  203. end = date_(*end)
  204. if ((is_tender and tender) or
  205. (not is_tender and non_tender)) and _is_active(start, end):
  206. if include_details:
  207. result.append({
  208. 'currency': currency_code,
  209. 'from': start,
  210. 'to': end,
  211. 'tender': is_tender,
  212. })
  213. else:
  214. result.append(currency_code)
  215. return result
  216. def get_decimal_symbol(locale=LC_NUMERIC):
  217. """Return the symbol used by the locale to separate decimal fractions.
  218. >>> get_decimal_symbol('en_US')
  219. u'.'
  220. :param locale: the `Locale` object or locale identifier
  221. """
  222. return Locale.parse(locale).number_symbols.get('decimal', u'.')
  223. def get_plus_sign_symbol(locale=LC_NUMERIC):
  224. """Return the plus sign symbol used by the current locale.
  225. >>> get_plus_sign_symbol('en_US')
  226. u'+'
  227. :param locale: the `Locale` object or locale identifier
  228. """
  229. return Locale.parse(locale).number_symbols.get('plusSign', u'+')
  230. def get_minus_sign_symbol(locale=LC_NUMERIC):
  231. """Return the plus sign symbol used by the current locale.
  232. >>> get_minus_sign_symbol('en_US')
  233. u'-'
  234. :param locale: the `Locale` object or locale identifier
  235. """
  236. return Locale.parse(locale).number_symbols.get('minusSign', u'-')
  237. def get_exponential_symbol(locale=LC_NUMERIC):
  238. """Return the symbol used by the locale to separate mantissa and exponent.
  239. >>> get_exponential_symbol('en_US')
  240. u'E'
  241. :param locale: the `Locale` object or locale identifier
  242. """
  243. return Locale.parse(locale).number_symbols.get('exponential', u'E')
  244. def get_group_symbol(locale=LC_NUMERIC):
  245. """Return the symbol used by the locale to separate groups of thousands.
  246. >>> get_group_symbol('en_US')
  247. u','
  248. :param locale: the `Locale` object or locale identifier
  249. """
  250. return Locale.parse(locale).number_symbols.get('group', u',')
  251. def format_number(number, locale=LC_NUMERIC):
  252. u"""Return the given number formatted for a specific locale.
  253. >>> format_number(1099, locale='en_US')
  254. u'1,099'
  255. >>> format_number(1099, locale='de_DE')
  256. u'1.099'
  257. .. deprecated:: 2.6.0
  258. Use babel.numbers.format_decimal() instead.
  259. :param number: the number to format
  260. :param locale: the `Locale` object or locale identifier
  261. """
  262. warnings.warn('Use babel.numbers.format_decimal() instead.', DeprecationWarning)
  263. return format_decimal(number, locale=locale)
  264. def get_decimal_precision(number):
  265. """Return maximum precision of a decimal instance's fractional part.
  266. Precision is extracted from the fractional part only.
  267. """
  268. # Copied from: https://github.com/mahmoud/boltons/pull/59
  269. assert isinstance(number, decimal.Decimal)
  270. decimal_tuple = number.normalize().as_tuple()
  271. if decimal_tuple.exponent >= 0:
  272. return 0
  273. return abs(decimal_tuple.exponent)
  274. def get_decimal_quantum(precision):
  275. """Return minimal quantum of a number, as defined by precision."""
  276. assert isinstance(precision, (int, long, decimal.Decimal))
  277. return decimal.Decimal(10) ** (-precision)
  278. def format_decimal(
  279. number, format=None, locale=LC_NUMERIC, decimal_quantization=True, group_separator=True):
  280. u"""Return the given decimal number formatted for a specific locale.
  281. >>> format_decimal(1.2345, locale='en_US')
  282. u'1.234'
  283. >>> format_decimal(1.2346, locale='en_US')
  284. u'1.235'
  285. >>> format_decimal(-1.2346, locale='en_US')
  286. u'-1.235'
  287. >>> format_decimal(1.2345, locale='sv_SE')
  288. u'1,234'
  289. >>> format_decimal(1.2345, locale='de')
  290. u'1,234'
  291. The appropriate thousands grouping and the decimal separator are used for
  292. each locale:
  293. >>> format_decimal(12345.5, locale='en_US')
  294. u'12,345.5'
  295. By default the locale is allowed to truncate and round a high-precision
  296. number by forcing its format pattern onto the decimal part. You can bypass
  297. this behavior with the `decimal_quantization` parameter:
  298. >>> format_decimal(1.2346, locale='en_US')
  299. u'1.235'
  300. >>> format_decimal(1.2346, locale='en_US', decimal_quantization=False)
  301. u'1.2346'
  302. >>> format_decimal(12345.67, locale='fr_CA', group_separator=False)
  303. u'12345,67'
  304. >>> format_decimal(12345.67, locale='en_US', group_separator=True)
  305. u'12,345.67'
  306. :param number: the number to format
  307. :param format:
  308. :param locale: the `Locale` object or locale identifier
  309. :param decimal_quantization: Truncate and round high-precision numbers to
  310. the format pattern. Defaults to `True`.
  311. :param group_separator: Boolean to switch group separator on/off in a locale's
  312. number format.
  313. """
  314. locale = Locale.parse(locale)
  315. if not format:
  316. format = locale.decimal_formats.get(format)
  317. pattern = parse_pattern(format)
  318. return pattern.apply(
  319. number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator)
  320. class UnknownCurrencyFormatError(KeyError):
  321. """Exception raised when an unknown currency format is requested."""
  322. def format_currency(
  323. number, currency, format=None, locale=LC_NUMERIC, currency_digits=True,
  324. format_type='standard', decimal_quantization=True, group_separator=True):
  325. u"""Return formatted currency value.
  326. >>> format_currency(1099.98, 'USD', locale='en_US')
  327. u'$1,099.98'
  328. >>> format_currency(1099.98, 'USD', locale='es_CO')
  329. u'US$\\xa01.099,98'
  330. >>> format_currency(1099.98, 'EUR', locale='de_DE')
  331. u'1.099,98\\xa0\\u20ac'
  332. The format can also be specified explicitly. The currency is
  333. placed with the '¤' sign. As the sign gets repeated the format
  334. expands (¤ being the symbol, ¤¤ is the currency abbreviation and
  335. ¤¤¤ is the full name of the currency):
  336. >>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
  337. u'EUR 1,099.98'
  338. >>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
  339. u'1,099.98 euros'
  340. Currencies usually have a specific number of decimal digits. This function
  341. favours that information over the given format:
  342. >>> format_currency(1099.98, 'JPY', locale='en_US')
  343. u'\\xa51,100'
  344. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
  345. u'1.099,98'
  346. However, the number of decimal digits can be overriden from the currency
  347. information, by setting the last parameter to ``False``:
  348. >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
  349. u'\\xa51,099.98'
  350. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
  351. u'1.099,98'
  352. If a format is not specified the type of currency format to use
  353. from the locale can be specified:
  354. >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
  355. u'\\u20ac1,099.98'
  356. When the given currency format type is not available, an exception is
  357. raised:
  358. >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
  359. Traceback (most recent call last):
  360. ...
  361. UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
  362. >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=False)
  363. u'$101299.98'
  364. >>> format_currency(101299.98, 'USD', locale='en_US', group_separator=True)
  365. u'$101,299.98'
  366. You can also pass format_type='name' to use long display names. The order of
  367. the number and currency name, along with the correct localized plural form
  368. of the currency name, is chosen according to locale:
  369. >>> format_currency(1, 'USD', locale='en_US', format_type='name')
  370. u'1.00 US dollar'
  371. >>> format_currency(1099.98, 'USD', locale='en_US', format_type='name')
  372. u'1,099.98 US dollars'
  373. >>> format_currency(1099.98, 'USD', locale='ee', format_type='name')
  374. u'us ga dollar 1,099.98'
  375. By default the locale is allowed to truncate and round a high-precision
  376. number by forcing its format pattern onto the decimal part. You can bypass
  377. this behavior with the `decimal_quantization` parameter:
  378. >>> format_currency(1099.9876, 'USD', locale='en_US')
  379. u'$1,099.99'
  380. >>> format_currency(1099.9876, 'USD', locale='en_US', decimal_quantization=False)
  381. u'$1,099.9876'
  382. :param number: the number to format
  383. :param currency: the currency code
  384. :param format: the format string to use
  385. :param locale: the `Locale` object or locale identifier
  386. :param currency_digits: use the currency's natural number of decimal digits
  387. :param format_type: the currency format type to use
  388. :param decimal_quantization: Truncate and round high-precision numbers to
  389. the format pattern. Defaults to `True`.
  390. :param group_separator: Boolean to switch group separator on/off in a locale's
  391. number format.
  392. """
  393. if format_type == 'name':
  394. return _format_currency_long_name(number, currency, format=format,
  395. locale=locale, currency_digits=currency_digits,
  396. decimal_quantization=decimal_quantization, group_separator=group_separator)
  397. locale = Locale.parse(locale)
  398. if format:
  399. pattern = parse_pattern(format)
  400. else:
  401. try:
  402. pattern = locale.currency_formats[format_type]
  403. except KeyError:
  404. raise UnknownCurrencyFormatError(
  405. "%r is not a known currency format type" % format_type)
  406. return pattern.apply(
  407. number, locale, currency=currency, currency_digits=currency_digits,
  408. decimal_quantization=decimal_quantization, group_separator=group_separator)
  409. def _format_currency_long_name(
  410. number, currency, format=None, locale=LC_NUMERIC, currency_digits=True,
  411. format_type='standard', decimal_quantization=True, group_separator=True):
  412. # Algorithm described here:
  413. # https://www.unicode.org/reports/tr35/tr35-numbers.html#Currencies
  414. locale = Locale.parse(locale)
  415. # Step 1.
  416. # There are no examples of items with explicit count (0 or 1) in current
  417. # locale data. So there is no point implementing that.
  418. # Step 2.
  419. # Correct number to numeric type, important for looking up plural rules:
  420. if isinstance(number, string_types):
  421. number_n = float(number)
  422. else:
  423. number_n = number
  424. # Step 3.
  425. unit_pattern = get_currency_unit_pattern(currency, count=number_n, locale=locale)
  426. # Step 4.
  427. display_name = get_currency_name(currency, count=number_n, locale=locale)
  428. # Step 5.
  429. if not format:
  430. format = locale.decimal_formats.get(format)
  431. pattern = parse_pattern(format)
  432. number_part = pattern.apply(
  433. number, locale, currency=currency, currency_digits=currency_digits,
  434. decimal_quantization=decimal_quantization, group_separator=group_separator)
  435. return unit_pattern.format(number_part, display_name)
  436. def format_percent(
  437. number, format=None, locale=LC_NUMERIC, decimal_quantization=True, group_separator=True):
  438. """Return formatted percent value for a specific locale.
  439. >>> format_percent(0.34, locale='en_US')
  440. u'34%'
  441. >>> format_percent(25.1234, locale='en_US')
  442. u'2,512%'
  443. >>> format_percent(25.1234, locale='sv_SE')
  444. u'2\\xa0512\\xa0%'
  445. The format pattern can also be specified explicitly:
  446. >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
  447. u'25,123\u2030'
  448. By default the locale is allowed to truncate and round a high-precision
  449. number by forcing its format pattern onto the decimal part. You can bypass
  450. this behavior with the `decimal_quantization` parameter:
  451. >>> format_percent(23.9876, locale='en_US')
  452. u'2,399%'
  453. >>> format_percent(23.9876, locale='en_US', decimal_quantization=False)
  454. u'2,398.76%'
  455. >>> format_percent(229291.1234, locale='pt_BR', group_separator=False)
  456. u'22929112%'
  457. >>> format_percent(229291.1234, locale='pt_BR', group_separator=True)
  458. u'22.929.112%'
  459. :param number: the percent number to format
  460. :param format:
  461. :param locale: the `Locale` object or locale identifier
  462. :param decimal_quantization: Truncate and round high-precision numbers to
  463. the format pattern. Defaults to `True`.
  464. :param group_separator: Boolean to switch group separator on/off in a locale's
  465. number format.
  466. """
  467. locale = Locale.parse(locale)
  468. if not format:
  469. format = locale.percent_formats.get(format)
  470. pattern = parse_pattern(format)
  471. return pattern.apply(
  472. number, locale, decimal_quantization=decimal_quantization, group_separator=group_separator)
  473. def format_scientific(
  474. number, format=None, locale=LC_NUMERIC, decimal_quantization=True):
  475. """Return value formatted in scientific notation for a specific locale.
  476. >>> format_scientific(10000, locale='en_US')
  477. u'1E4'
  478. The format pattern can also be specified explicitly:
  479. >>> format_scientific(1234567, u'##0.##E00', locale='en_US')
  480. u'1.23E06'
  481. By default the locale is allowed to truncate and round a high-precision
  482. number by forcing its format pattern onto the decimal part. You can bypass
  483. this behavior with the `decimal_quantization` parameter:
  484. >>> format_scientific(1234.9876, u'#.##E0', locale='en_US')
  485. u'1.23E3'
  486. >>> format_scientific(1234.9876, u'#.##E0', locale='en_US', decimal_quantization=False)
  487. u'1.2349876E3'
  488. :param number: the number to format
  489. :param format:
  490. :param locale: the `Locale` object or locale identifier
  491. :param decimal_quantization: Truncate and round high-precision numbers to
  492. the format pattern. Defaults to `True`.
  493. """
  494. locale = Locale.parse(locale)
  495. if not format:
  496. format = locale.scientific_formats.get(format)
  497. pattern = parse_pattern(format)
  498. return pattern.apply(
  499. number, locale, decimal_quantization=decimal_quantization)
  500. class NumberFormatError(ValueError):
  501. """Exception raised when a string cannot be parsed into a number."""
  502. def __init__(self, message, suggestions=None):
  503. super(NumberFormatError, self).__init__(message)
  504. #: a list of properly formatted numbers derived from the invalid input
  505. self.suggestions = suggestions
  506. def parse_number(string, locale=LC_NUMERIC):
  507. """Parse localized number string into an integer.
  508. >>> parse_number('1,099', locale='en_US')
  509. 1099
  510. >>> parse_number('1.099', locale='de_DE')
  511. 1099
  512. When the given string cannot be parsed, an exception is raised:
  513. >>> parse_number('1.099,98', locale='de')
  514. Traceback (most recent call last):
  515. ...
  516. NumberFormatError: '1.099,98' is not a valid number
  517. :param string: the string to parse
  518. :param locale: the `Locale` object or locale identifier
  519. :return: the parsed number
  520. :raise `NumberFormatError`: if the string can not be converted to a number
  521. """
  522. try:
  523. return int(string.replace(get_group_symbol(locale), ''))
  524. except ValueError:
  525. raise NumberFormatError('%r is not a valid number' % string)
  526. def parse_decimal(string, locale=LC_NUMERIC, strict=False):
  527. """Parse localized decimal string into a decimal.
  528. >>> parse_decimal('1,099.98', locale='en_US')
  529. Decimal('1099.98')
  530. >>> parse_decimal('1.099,98', locale='de')
  531. Decimal('1099.98')
  532. >>> parse_decimal('12 345,123', locale='ru')
  533. Decimal('12345.123')
  534. When the given string cannot be parsed, an exception is raised:
  535. >>> parse_decimal('2,109,998', locale='de')
  536. Traceback (most recent call last):
  537. ...
  538. NumberFormatError: '2,109,998' is not a valid decimal number
  539. If `strict` is set to `True` and the given string contains a number
  540. formatted in an irregular way, an exception is raised:
  541. >>> parse_decimal('30.00', locale='de', strict=True)
  542. Traceback (most recent call last):
  543. ...
  544. NumberFormatError: '30.00' is not a properly formatted decimal number. Did you mean '3.000'? Or maybe '30,00'?
  545. >>> parse_decimal('0.00', locale='de', strict=True)
  546. Traceback (most recent call last):
  547. ...
  548. NumberFormatError: '0.00' is not a properly formatted decimal number. Did you mean '0'?
  549. :param string: the string to parse
  550. :param locale: the `Locale` object or locale identifier
  551. :param strict: controls whether numbers formatted in a weird way are
  552. accepted or rejected
  553. :raise NumberFormatError: if the string can not be converted to a
  554. decimal number
  555. """
  556. locale = Locale.parse(locale)
  557. group_symbol = get_group_symbol(locale)
  558. decimal_symbol = get_decimal_symbol(locale)
  559. if not strict and (
  560. group_symbol == u'\xa0' and # if the grouping symbol is U+00A0 NO-BREAK SPACE,
  561. group_symbol not in string and # and the string to be parsed does not contain it,
  562. ' ' in string # but it does contain a space instead,
  563. ):
  564. # ... it's reasonable to assume it is taking the place of the grouping symbol.
  565. string = string.replace(' ', group_symbol)
  566. try:
  567. parsed = decimal.Decimal(string.replace(group_symbol, '')
  568. .replace(decimal_symbol, '.'))
  569. except decimal.InvalidOperation:
  570. raise NumberFormatError('%r is not a valid decimal number' % string)
  571. if strict and group_symbol in string:
  572. proper = format_decimal(parsed, locale=locale, decimal_quantization=False)
  573. if string != proper and string.rstrip('0') != (proper + decimal_symbol):
  574. try:
  575. parsed_alt = decimal.Decimal(string.replace(decimal_symbol, '')
  576. .replace(group_symbol, '.'))
  577. except decimal.InvalidOperation:
  578. raise NumberFormatError((
  579. "%r is not a properly formatted decimal number. Did you mean %r?" %
  580. (string, proper)
  581. ), suggestions=[proper])
  582. else:
  583. proper_alt = format_decimal(parsed_alt, locale=locale, decimal_quantization=False)
  584. if proper_alt == proper:
  585. raise NumberFormatError((
  586. "%r is not a properly formatted decimal number. Did you mean %r?" %
  587. (string, proper)
  588. ), suggestions=[proper])
  589. else:
  590. raise NumberFormatError((
  591. "%r is not a properly formatted decimal number. Did you mean %r? Or maybe %r?" %
  592. (string, proper, proper_alt)
  593. ), suggestions=[proper, proper_alt])
  594. return parsed
  595. PREFIX_END = r'[^0-9@#.,]'
  596. NUMBER_TOKEN = r'[0-9@#.,E+]'
  597. PREFIX_PATTERN = r"(?P<prefix>(?:'[^']*'|%s)*)" % PREFIX_END
  598. NUMBER_PATTERN = r"(?P<number>%s*)" % NUMBER_TOKEN
  599. SUFFIX_PATTERN = r"(?P<suffix>.*)"
  600. number_re = re.compile(r"%s%s%s" % (PREFIX_PATTERN, NUMBER_PATTERN,
  601. SUFFIX_PATTERN))
  602. def parse_grouping(p):
  603. """Parse primary and secondary digit grouping
  604. >>> parse_grouping('##')
  605. (1000, 1000)
  606. >>> parse_grouping('#,###')
  607. (3, 3)
  608. >>> parse_grouping('#,####,###')
  609. (3, 4)
  610. """
  611. width = len(p)
  612. g1 = p.rfind(',')
  613. if g1 == -1:
  614. return 1000, 1000
  615. g1 = width - g1 - 1
  616. g2 = p[:-g1 - 1].rfind(',')
  617. if g2 == -1:
  618. return g1, g1
  619. g2 = width - g1 - g2 - 2
  620. return g1, g2
  621. def parse_pattern(pattern):
  622. """Parse number format patterns"""
  623. if isinstance(pattern, NumberPattern):
  624. return pattern
  625. def _match_number(pattern):
  626. rv = number_re.search(pattern)
  627. if rv is None:
  628. raise ValueError('Invalid number pattern %r' % pattern)
  629. return rv.groups()
  630. pos_pattern = pattern
  631. # Do we have a negative subpattern?
  632. if ';' in pattern:
  633. pos_pattern, neg_pattern = pattern.split(';', 1)
  634. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  635. neg_prefix, _, neg_suffix = _match_number(neg_pattern)
  636. else:
  637. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  638. neg_prefix = '-' + pos_prefix
  639. neg_suffix = pos_suffix
  640. if 'E' in number:
  641. number, exp = number.split('E', 1)
  642. else:
  643. exp = None
  644. if '@' in number:
  645. if '.' in number and '0' in number:
  646. raise ValueError('Significant digit patterns can not contain '
  647. '"@" or "0"')
  648. if '.' in number:
  649. integer, fraction = number.rsplit('.', 1)
  650. else:
  651. integer = number
  652. fraction = ''
  653. def parse_precision(p):
  654. """Calculate the min and max allowed digits"""
  655. min = max = 0
  656. for c in p:
  657. if c in '@0':
  658. min += 1
  659. max += 1
  660. elif c == '#':
  661. max += 1
  662. elif c == ',':
  663. continue
  664. else:
  665. break
  666. return min, max
  667. int_prec = parse_precision(integer)
  668. frac_prec = parse_precision(fraction)
  669. if exp:
  670. exp_plus = exp.startswith('+')
  671. exp = exp.lstrip('+')
  672. exp_prec = parse_precision(exp)
  673. else:
  674. exp_plus = None
  675. exp_prec = None
  676. grouping = parse_grouping(integer)
  677. return NumberPattern(pattern, (pos_prefix, neg_prefix),
  678. (pos_suffix, neg_suffix), grouping,
  679. int_prec, frac_prec,
  680. exp_prec, exp_plus)
  681. class NumberPattern(object):
  682. def __init__(self, pattern, prefix, suffix, grouping,
  683. int_prec, frac_prec, exp_prec, exp_plus):
  684. # Metadata of the decomposed parsed pattern.
  685. self.pattern = pattern
  686. self.prefix = prefix
  687. self.suffix = suffix
  688. self.grouping = grouping
  689. self.int_prec = int_prec
  690. self.frac_prec = frac_prec
  691. self.exp_prec = exp_prec
  692. self.exp_plus = exp_plus
  693. self.scale = self.compute_scale()
  694. def __repr__(self):
  695. return '<%s %r>' % (type(self).__name__, self.pattern)
  696. def compute_scale(self):
  697. """Return the scaling factor to apply to the number before rendering.
  698. Auto-set to a factor of 2 or 3 if presence of a ``%`` or ``‰`` sign is
  699. detected in the prefix or suffix of the pattern. Default is to not mess
  700. with the scale at all and keep it to 0.
  701. """
  702. scale = 0
  703. if '%' in ''.join(self.prefix + self.suffix):
  704. scale = 2
  705. elif u'‰' in ''.join(self.prefix + self.suffix):
  706. scale = 3
  707. return scale
  708. def scientific_notation_elements(self, value, locale):
  709. """ Returns normalized scientific notation components of a value.
  710. """
  711. # Normalize value to only have one lead digit.
  712. exp = value.adjusted()
  713. value = value * get_decimal_quantum(exp)
  714. assert value.adjusted() == 0
  715. # Shift exponent and value by the minimum number of leading digits
  716. # imposed by the rendering pattern. And always make that number
  717. # greater or equal to 1.
  718. lead_shift = max([1, min(self.int_prec)]) - 1
  719. exp = exp - lead_shift
  720. value = value * get_decimal_quantum(-lead_shift)
  721. # Get exponent sign symbol.
  722. exp_sign = ''
  723. if exp < 0:
  724. exp_sign = get_minus_sign_symbol(locale)
  725. elif self.exp_plus:
  726. exp_sign = get_plus_sign_symbol(locale)
  727. # Normalize exponent value now that we have the sign.
  728. exp = abs(exp)
  729. return value, exp, exp_sign
  730. def apply(
  731. self,
  732. value,
  733. locale,
  734. currency=None,
  735. currency_digits=True,
  736. decimal_quantization=True,
  737. force_frac=None,
  738. group_separator=True,
  739. ):
  740. """Renders into a string a number following the defined pattern.
  741. Forced decimal quantization is active by default so we'll produce a
  742. number string that is strictly following CLDR pattern definitions.
  743. :param value: The value to format. If this is not a Decimal object,
  744. it will be cast to one.
  745. :type value: decimal.Decimal|float|int
  746. :param locale: The locale to use for formatting.
  747. :type locale: str|babel.core.Locale
  748. :param currency: Which currency, if any, to format as.
  749. :type currency: str|None
  750. :param currency_digits: Whether or not to use the currency's precision.
  751. If false, the pattern's precision is used.
  752. :type currency_digits: bool
  753. :param decimal_quantization: Whether decimal numbers should be forcibly
  754. quantized to produce a formatted output
  755. strictly matching the CLDR definition for
  756. the locale.
  757. :type decimal_quantization: bool
  758. :param force_frac: DEPRECATED - a forced override for `self.frac_prec`
  759. for a single formatting invocation.
  760. :return: Formatted decimal string.
  761. :rtype: str
  762. """
  763. if not isinstance(value, decimal.Decimal):
  764. value = decimal.Decimal(str(value))
  765. value = value.scaleb(self.scale)
  766. # Separate the absolute value from its sign.
  767. is_negative = int(value.is_signed())
  768. value = abs(value).normalize()
  769. # Prepare scientific notation metadata.
  770. if self.exp_prec:
  771. value, exp, exp_sign = self.scientific_notation_elements(value, locale)
  772. # Adjust the precision of the fractional part and force it to the
  773. # currency's if necessary.
  774. if force_frac:
  775. # TODO (3.x?): Remove this parameter
  776. warnings.warn('The force_frac parameter to NumberPattern.apply() is deprecated.', DeprecationWarning)
  777. frac_prec = force_frac
  778. elif currency and currency_digits:
  779. frac_prec = (get_currency_precision(currency), ) * 2
  780. else:
  781. frac_prec = self.frac_prec
  782. # Bump decimal precision to the natural precision of the number if it
  783. # exceeds the one we're about to use. This adaptative precision is only
  784. # triggered if the decimal quantization is disabled or if a scientific
  785. # notation pattern has a missing mandatory fractional part (as in the
  786. # default '#E0' pattern). This special case has been extensively
  787. # discussed at https://github.com/python-babel/babel/pull/494#issuecomment-307649969 .
  788. if not decimal_quantization or (self.exp_prec and frac_prec == (0, 0)):
  789. frac_prec = (frac_prec[0], max([frac_prec[1], get_decimal_precision(value)]))
  790. # Render scientific notation.
  791. if self.exp_prec:
  792. number = ''.join([
  793. self._quantize_value(value, locale, frac_prec, group_separator),
  794. get_exponential_symbol(locale),
  795. exp_sign,
  796. self._format_int(
  797. str(exp), self.exp_prec[0], self.exp_prec[1], locale)])
  798. # Is it a siginificant digits pattern?
  799. elif '@' in self.pattern:
  800. text = self._format_significant(value,
  801. self.int_prec[0],
  802. self.int_prec[1])
  803. a, sep, b = text.partition(".")
  804. number = self._format_int(a, 0, 1000, locale)
  805. if sep:
  806. number += get_decimal_symbol(locale) + b
  807. # A normal number pattern.
  808. else:
  809. number = self._quantize_value(value, locale, frac_prec, group_separator)
  810. retval = ''.join([
  811. self.prefix[is_negative],
  812. number,
  813. self.suffix[is_negative]])
  814. if u'¤' in retval:
  815. retval = retval.replace(u'¤¤¤',
  816. get_currency_name(currency, value, locale))
  817. retval = retval.replace(u'¤¤', currency.upper())
  818. retval = retval.replace(u'¤', get_currency_symbol(currency, locale))
  819. return retval
  820. #
  821. # This is one tricky piece of code. The idea is to rely as much as possible
  822. # on the decimal module to minimize the amount of code.
  823. #
  824. # Conceptually, the implementation of this method can be summarized in the
  825. # following steps:
  826. #
  827. # - Move or shift the decimal point (i.e. the exponent) so the maximum
  828. # amount of significant digits fall into the integer part (i.e. to the
  829. # left of the decimal point)
  830. #
  831. # - Round the number to the nearest integer, discarding all the fractional
  832. # part which contained extra digits to be eliminated
  833. #
  834. # - Convert the rounded integer to a string, that will contain the final
  835. # sequence of significant digits already trimmed to the maximum
  836. #
  837. # - Restore the original position of the decimal point, potentially
  838. # padding with zeroes on either side
  839. #
  840. def _format_significant(self, value, minimum, maximum):
  841. exp = value.adjusted()
  842. scale = maximum - 1 - exp
  843. digits = str(value.scaleb(scale).quantize(decimal.Decimal(1)))
  844. if scale <= 0:
  845. result = digits + '0' * -scale
  846. else:
  847. intpart = digits[:-scale]
  848. i = len(intpart)
  849. j = i + max(minimum - i, 0)
  850. result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format(
  851. intpart=intpart or '0',
  852. pad='',
  853. fill=-min(exp + 1, 0),
  854. fracpart=digits[i:j],
  855. fracextra=digits[j:].rstrip('0'),
  856. ).rstrip('.')
  857. return result
  858. def _format_int(self, value, min, max, locale):
  859. width = len(value)
  860. if width < min:
  861. value = '0' * (min - width) + value
  862. gsize = self.grouping[0]
  863. ret = ''
  864. symbol = get_group_symbol(locale)
  865. while len(value) > gsize:
  866. ret = symbol + value[-gsize:] + ret
  867. value = value[:-gsize]
  868. gsize = self.grouping[1]
  869. return value + ret
  870. def _quantize_value(self, value, locale, frac_prec, group_separator):
  871. quantum = get_decimal_quantum(frac_prec[1])
  872. rounded = value.quantize(quantum)
  873. a, sep, b = "{:f}".format(rounded).partition(".")
  874. integer_part = a
  875. if group_separator:
  876. integer_part = self._format_int(a, self.int_prec[0], self.int_prec[1], locale)
  877. number = integer_part + self._format_frac(b or '0', locale, frac_prec)
  878. return number
  879. def _format_frac(self, value, locale, force_frac=None):
  880. min, max = force_frac or self.frac_prec
  881. if len(value) < min:
  882. value += ('0' * (min - len(value)))
  883. if max == 0 or (min == 0 and int(value) == 0):
  884. return ''
  885. while len(value) > min and value[-1] == '0':
  886. value = value[:-1]
  887. return get_decimal_symbol(locale) + value