numbers.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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 by the Babel Team.
  12. :license: BSD, see LICENSE for more details.
  13. """
  14. # TODO:
  15. # Padding and rounding increments in pattern:
  16. # - http://www.unicode.org/reports/tr35/ (Appendix G.6)
  17. import re
  18. from datetime import date as date_, datetime as datetime_
  19. from itertools import chain
  20. from babel.core import default_locale, Locale, get_global
  21. from babel._compat import decimal, string_types
  22. from babel.localedata import locale_identifiers
  23. LC_NUMERIC = default_locale('LC_NUMERIC')
  24. class UnknownCurrencyError(Exception):
  25. """Exception thrown when a currency is requested for which no data is available.
  26. """
  27. def __init__(self, identifier):
  28. """Create the exception.
  29. :param identifier: the identifier string of the unsupported currency
  30. """
  31. Exception.__init__(self, 'Unknown currency %r.' % identifier)
  32. #: The identifier of the locale that could not be found.
  33. self.identifier = identifier
  34. def list_currencies(locale=None):
  35. """ Return a `set` of normalized currency codes.
  36. .. versionadded:: 2.5.0
  37. :param locale: filters returned currency codes by the provided locale.
  38. Expected to be a locale instance or code. If no locale is
  39. provided, returns the list of all currencies from all
  40. locales.
  41. """
  42. # Get locale-scoped currencies.
  43. if locale:
  44. currencies = Locale.parse(locale).currencies.keys()
  45. else:
  46. currencies = get_global('all_currencies')
  47. return set(currencies)
  48. def validate_currency(currency, locale=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, locale=None):
  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, string_types):
  61. return False
  62. try:
  63. validate_currency(currency, locale)
  64. except UnknownCurrencyError:
  65. return False
  66. return True
  67. def normalize_currency(currency, locale=None):
  68. """Returns the normalized sting 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, string_types):
  74. currency = currency.upper()
  75. if not is_currency(currency, locale):
  76. return
  77. return currency
  78. def get_currency_name(currency, count=None, locale=LC_NUMERIC):
  79. """Return the name used by the locale for the specified currency.
  80. >>> get_currency_name('USD', locale='en_US')
  81. u'US Dollar'
  82. .. versionadded:: 0.9.4
  83. :param currency: the currency code.
  84. :param count: the optional count. If provided the currency name
  85. will be pluralized to that number if possible.
  86. :param locale: the `Locale` object or locale identifier.
  87. """
  88. loc = Locale.parse(locale)
  89. if count is not None:
  90. plural_form = loc.plural_form(count)
  91. plural_names = loc._data['currency_names_plural']
  92. if currency in plural_names:
  93. return plural_names[currency][plural_form]
  94. return loc.currencies.get(currency, currency)
  95. def get_currency_symbol(currency, locale=LC_NUMERIC):
  96. """Return the symbol used by the locale for the specified currency.
  97. >>> get_currency_symbol('USD', locale='en_US')
  98. u'$'
  99. :param currency: the currency code.
  100. :param locale: the `Locale` object or locale identifier.
  101. """
  102. return Locale.parse(locale).currency_symbols.get(currency, currency)
  103. def get_currency_precision(currency):
  104. """Return currency's precision.
  105. Precision is the number of decimals found after the decimal point in the
  106. currency's format pattern.
  107. .. versionadded:: 2.5.0
  108. :param currency: the currency code.
  109. """
  110. precisions = get_global('currency_fractions')
  111. return precisions.get(currency, precisions['DEFAULT'])[0]
  112. def get_territory_currencies(territory, start_date=None, end_date=None,
  113. tender=True, non_tender=False,
  114. include_details=False):
  115. """Returns the list of currencies for the given territory that are valid for
  116. the given date range. In addition to that the currency database
  117. distinguishes between tender and non-tender currencies. By default only
  118. tender currencies are returned.
  119. The return value is a list of all currencies roughly ordered by the time
  120. of when the currency became active. The longer the currency is being in
  121. use the more to the left of the list it will be.
  122. The start date defaults to today. If no end date is given it will be the
  123. same as the start date. Otherwise a range can be defined. For instance
  124. this can be used to find the currencies in use in Austria between 1995 and
  125. 2011:
  126. >>> from datetime import date
  127. >>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
  128. ['ATS', 'EUR']
  129. Likewise it's also possible to find all the currencies in use on a
  130. single date:
  131. >>> get_territory_currencies('AT', date(1995, 1, 1))
  132. ['ATS']
  133. >>> get_territory_currencies('AT', date(2011, 1, 1))
  134. ['EUR']
  135. By default the return value only includes tender currencies. This
  136. however can be changed:
  137. >>> get_territory_currencies('US')
  138. ['USD']
  139. >>> get_territory_currencies('US', tender=False, non_tender=True,
  140. ... start_date=date(2014, 1, 1))
  141. ['USN', 'USS']
  142. .. versionadded:: 2.0
  143. :param territory: the name of the territory to find the currency for.
  144. :param start_date: the start date. If not given today is assumed.
  145. :param end_date: the end date. If not given the start date is assumed.
  146. :param tender: controls whether tender currencies should be included.
  147. :param non_tender: controls whether non-tender currencies should be
  148. included.
  149. :param include_details: if set to `True`, instead of returning currency
  150. codes the return value will be dictionaries
  151. with detail information. In that case each
  152. dictionary will have the keys ``'currency'``,
  153. ``'from'``, ``'to'``, and ``'tender'``.
  154. """
  155. currencies = get_global('territory_currencies')
  156. if start_date is None:
  157. start_date = date_.today()
  158. elif isinstance(start_date, datetime_):
  159. start_date = start_date.date()
  160. if end_date is None:
  161. end_date = start_date
  162. elif isinstance(end_date, datetime_):
  163. end_date = end_date.date()
  164. curs = currencies.get(territory.upper(), ())
  165. # TODO: validate that the territory exists
  166. def _is_active(start, end):
  167. return (start is None or start <= end_date) and \
  168. (end is None or end >= start_date)
  169. result = []
  170. for currency_code, start, end, is_tender in curs:
  171. if start:
  172. start = date_(*start)
  173. if end:
  174. end = date_(*end)
  175. if ((is_tender and tender) or
  176. (not is_tender and non_tender)) and _is_active(start, end):
  177. if include_details:
  178. result.append({
  179. 'currency': currency_code,
  180. 'from': start,
  181. 'to': end,
  182. 'tender': is_tender,
  183. })
  184. else:
  185. result.append(currency_code)
  186. return result
  187. def get_decimal_symbol(locale=LC_NUMERIC):
  188. """Return the symbol used by the locale to separate decimal fractions.
  189. >>> get_decimal_symbol('en_US')
  190. u'.'
  191. :param locale: the `Locale` object or locale identifier
  192. """
  193. return Locale.parse(locale).number_symbols.get('decimal', u'.')
  194. def get_plus_sign_symbol(locale=LC_NUMERIC):
  195. """Return the plus sign symbol used by the current locale.
  196. >>> get_plus_sign_symbol('en_US')
  197. u'+'
  198. :param locale: the `Locale` object or locale identifier
  199. """
  200. return Locale.parse(locale).number_symbols.get('plusSign', u'+')
  201. def get_minus_sign_symbol(locale=LC_NUMERIC):
  202. """Return the plus sign symbol used by the current locale.
  203. >>> get_minus_sign_symbol('en_US')
  204. u'-'
  205. :param locale: the `Locale` object or locale identifier
  206. """
  207. return Locale.parse(locale).number_symbols.get('minusSign', u'-')
  208. def get_exponential_symbol(locale=LC_NUMERIC):
  209. """Return the symbol used by the locale to separate mantissa and exponent.
  210. >>> get_exponential_symbol('en_US')
  211. u'E'
  212. :param locale: the `Locale` object or locale identifier
  213. """
  214. return Locale.parse(locale).number_symbols.get('exponential', u'E')
  215. def get_group_symbol(locale=LC_NUMERIC):
  216. """Return the symbol used by the locale to separate groups of thousands.
  217. >>> get_group_symbol('en_US')
  218. u','
  219. :param locale: the `Locale` object or locale identifier
  220. """
  221. return Locale.parse(locale).number_symbols.get('group', u',')
  222. def format_number(number, locale=LC_NUMERIC):
  223. u"""Return the given number formatted for a specific locale.
  224. >>> format_number(1099, locale='en_US')
  225. u'1,099'
  226. >>> format_number(1099, locale='de_DE')
  227. u'1.099'
  228. :param number: the number to format
  229. :param locale: the `Locale` object or locale identifier
  230. """
  231. # Do we really need this one?
  232. return format_decimal(number, locale=locale)
  233. def format_decimal(number, format=None, locale=LC_NUMERIC):
  234. u"""Return the given decimal number formatted for a specific locale.
  235. >>> format_decimal(1.2345, locale='en_US')
  236. u'1.234'
  237. >>> format_decimal(1.2346, locale='en_US')
  238. u'1.235'
  239. >>> format_decimal(-1.2346, locale='en_US')
  240. u'-1.235'
  241. >>> format_decimal(1.2345, locale='sv_SE')
  242. u'1,234'
  243. >>> format_decimal(1.2345, locale='de')
  244. u'1,234'
  245. The appropriate thousands grouping and the decimal separator are used for
  246. each locale:
  247. >>> format_decimal(12345.5, locale='en_US')
  248. u'12,345.5'
  249. :param number: the number to format
  250. :param format:
  251. :param locale: the `Locale` object or locale identifier
  252. """
  253. locale = Locale.parse(locale)
  254. if not format:
  255. format = locale.decimal_formats.get(format)
  256. pattern = parse_pattern(format)
  257. return pattern.apply(number, locale)
  258. class UnknownCurrencyFormatError(KeyError):
  259. """Exception raised when an unknown currency format is requested."""
  260. def format_currency(number, currency, format=None, locale=LC_NUMERIC,
  261. currency_digits=True, format_type='standard'):
  262. u"""Return formatted currency value.
  263. >>> format_currency(1099.98, 'USD', locale='en_US')
  264. u'$1,099.98'
  265. >>> format_currency(1099.98, 'USD', locale='es_CO')
  266. u'US$\\xa01.099,98'
  267. >>> format_currency(1099.98, 'EUR', locale='de_DE')
  268. u'1.099,98\\xa0\\u20ac'
  269. The format can also be specified explicitly. The currency is
  270. placed with the '¤' sign. As the sign gets repeated the format
  271. expands (¤ being the symbol, ¤¤ is the currency abbreviation and
  272. ¤¤¤ is the full name of the currency):
  273. >>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
  274. u'EUR 1,099.98'
  275. >>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
  276. u'1,099.98 euros'
  277. Currencies usually have a specific number of decimal digits. This function
  278. favours that information over the given format:
  279. >>> format_currency(1099.98, 'JPY', locale='en_US')
  280. u'\\xa51,100'
  281. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
  282. u'1.100'
  283. However, the number of decimal digits can be overriden from the currency
  284. information, by setting the last parameter to ``False``:
  285. >>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
  286. u'\\xa51,099.98'
  287. >>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
  288. u'1.099,98'
  289. If a format is not specified the type of currency format to use
  290. from the locale can be specified:
  291. >>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
  292. u'\\u20ac1,099.98'
  293. When the given currency format type is not available, an exception is
  294. raised:
  295. >>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
  296. Traceback (most recent call last):
  297. ...
  298. UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
  299. :param number: the number to format
  300. :param currency: the currency code
  301. :param format: the format string to use
  302. :param locale: the `Locale` object or locale identifier
  303. :param currency_digits: use the currency's number of decimal digits
  304. :param format_type: the currency format type to use
  305. """
  306. locale = Locale.parse(locale)
  307. if format:
  308. pattern = parse_pattern(format)
  309. else:
  310. try:
  311. pattern = locale.currency_formats[format_type]
  312. except KeyError:
  313. raise UnknownCurrencyFormatError("%r is not a known currency format"
  314. " type" % format_type)
  315. if currency_digits:
  316. precision = get_currency_precision(currency)
  317. frac = (precision, precision)
  318. else:
  319. frac = None
  320. return pattern.apply(number, locale, currency=currency, force_frac=frac)
  321. def format_percent(number, format=None, locale=LC_NUMERIC):
  322. """Return formatted percent value for a specific locale.
  323. >>> format_percent(0.34, locale='en_US')
  324. u'34%'
  325. >>> format_percent(25.1234, locale='en_US')
  326. u'2,512%'
  327. >>> format_percent(25.1234, locale='sv_SE')
  328. u'2\\xa0512\\xa0%'
  329. The format pattern can also be specified explicitly:
  330. >>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
  331. u'25,123\u2030'
  332. :param number: the percent number to format
  333. :param format:
  334. :param locale: the `Locale` object or locale identifier
  335. """
  336. locale = Locale.parse(locale)
  337. if not format:
  338. format = locale.percent_formats.get(format)
  339. pattern = parse_pattern(format)
  340. return pattern.apply(number, locale)
  341. def format_scientific(number, format=None, locale=LC_NUMERIC):
  342. """Return value formatted in scientific notation for a specific locale.
  343. >>> format_scientific(10000, locale='en_US')
  344. u'1E4'
  345. The format pattern can also be specified explicitly:
  346. >>> format_scientific(1234567, u'##0E00', locale='en_US')
  347. u'1.23E06'
  348. :param number: the number to format
  349. :param format:
  350. :param locale: the `Locale` object or locale identifier
  351. """
  352. locale = Locale.parse(locale)
  353. if not format:
  354. format = locale.scientific_formats.get(format)
  355. pattern = parse_pattern(format)
  356. return pattern.apply(number, locale)
  357. class NumberFormatError(ValueError):
  358. """Exception raised when a string cannot be parsed into a number."""
  359. def parse_number(string, locale=LC_NUMERIC):
  360. """Parse localized number string into an integer.
  361. >>> parse_number('1,099', locale='en_US')
  362. 1099
  363. >>> parse_number('1.099', locale='de_DE')
  364. 1099
  365. When the given string cannot be parsed, an exception is raised:
  366. >>> parse_number('1.099,98', locale='de')
  367. Traceback (most recent call last):
  368. ...
  369. NumberFormatError: '1.099,98' is not a valid number
  370. :param string: the string to parse
  371. :param locale: the `Locale` object or locale identifier
  372. :return: the parsed number
  373. :raise `NumberFormatError`: if the string can not be converted to a number
  374. """
  375. try:
  376. return int(string.replace(get_group_symbol(locale), ''))
  377. except ValueError:
  378. raise NumberFormatError('%r is not a valid number' % string)
  379. def parse_decimal(string, locale=LC_NUMERIC):
  380. """Parse localized decimal string into a decimal.
  381. >>> parse_decimal('1,099.98', locale='en_US')
  382. Decimal('1099.98')
  383. >>> parse_decimal('1.099,98', locale='de')
  384. Decimal('1099.98')
  385. When the given string cannot be parsed, an exception is raised:
  386. >>> parse_decimal('2,109,998', locale='de')
  387. Traceback (most recent call last):
  388. ...
  389. NumberFormatError: '2,109,998' is not a valid decimal number
  390. :param string: the string to parse
  391. :param locale: the `Locale` object or locale identifier
  392. :raise NumberFormatError: if the string can not be converted to a
  393. decimal number
  394. """
  395. locale = Locale.parse(locale)
  396. try:
  397. return decimal.Decimal(string.replace(get_group_symbol(locale), '')
  398. .replace(get_decimal_symbol(locale), '.'))
  399. except decimal.InvalidOperation:
  400. raise NumberFormatError('%r is not a valid decimal number' % string)
  401. PREFIX_END = r'[^0-9@#.,]'
  402. NUMBER_TOKEN = r'[0-9@#.,E+]'
  403. PREFIX_PATTERN = r"(?P<prefix>(?:'[^']*'|%s)*)" % PREFIX_END
  404. NUMBER_PATTERN = r"(?P<number>%s+)" % NUMBER_TOKEN
  405. SUFFIX_PATTERN = r"(?P<suffix>.*)"
  406. number_re = re.compile(r"%s%s%s" % (PREFIX_PATTERN, NUMBER_PATTERN,
  407. SUFFIX_PATTERN))
  408. def parse_grouping(p):
  409. """Parse primary and secondary digit grouping
  410. >>> parse_grouping('##')
  411. (1000, 1000)
  412. >>> parse_grouping('#,###')
  413. (3, 3)
  414. >>> parse_grouping('#,####,###')
  415. (3, 4)
  416. """
  417. width = len(p)
  418. g1 = p.rfind(',')
  419. if g1 == -1:
  420. return 1000, 1000
  421. g1 = width - g1 - 1
  422. g2 = p[:-g1 - 1].rfind(',')
  423. if g2 == -1:
  424. return g1, g1
  425. g2 = width - g1 - g2 - 2
  426. return g1, g2
  427. def parse_pattern(pattern):
  428. """Parse number format patterns"""
  429. if isinstance(pattern, NumberPattern):
  430. return pattern
  431. def _match_number(pattern):
  432. rv = number_re.search(pattern)
  433. if rv is None:
  434. raise ValueError('Invalid number pattern %r' % pattern)
  435. return rv.groups()
  436. pos_pattern = pattern
  437. # Do we have a negative subpattern?
  438. if ';' in pattern:
  439. pos_pattern, neg_pattern = pattern.split(';', 1)
  440. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  441. neg_prefix, _, neg_suffix = _match_number(neg_pattern)
  442. else:
  443. pos_prefix, number, pos_suffix = _match_number(pos_pattern)
  444. neg_prefix = '-' + pos_prefix
  445. neg_suffix = pos_suffix
  446. if 'E' in number:
  447. number, exp = number.split('E', 1)
  448. else:
  449. exp = None
  450. if '@' in number:
  451. if '.' in number and '0' in number:
  452. raise ValueError('Significant digit patterns can not contain '
  453. '"@" or "0"')
  454. if '.' in number:
  455. integer, fraction = number.rsplit('.', 1)
  456. else:
  457. integer = number
  458. fraction = ''
  459. def parse_precision(p):
  460. """Calculate the min and max allowed digits"""
  461. min = max = 0
  462. for c in p:
  463. if c in '@0':
  464. min += 1
  465. max += 1
  466. elif c == '#':
  467. max += 1
  468. elif c == ',':
  469. continue
  470. else:
  471. break
  472. return min, max
  473. int_prec = parse_precision(integer)
  474. frac_prec = parse_precision(fraction)
  475. if exp:
  476. frac_prec = parse_precision(integer + fraction)
  477. exp_plus = exp.startswith('+')
  478. exp = exp.lstrip('+')
  479. exp_prec = parse_precision(exp)
  480. else:
  481. exp_plus = None
  482. exp_prec = None
  483. grouping = parse_grouping(integer)
  484. return NumberPattern(pattern, (pos_prefix, neg_prefix),
  485. (pos_suffix, neg_suffix), grouping,
  486. int_prec, frac_prec,
  487. exp_prec, exp_plus)
  488. class NumberPattern(object):
  489. def __init__(self, pattern, prefix, suffix, grouping,
  490. int_prec, frac_prec, exp_prec, exp_plus):
  491. self.pattern = pattern
  492. self.prefix = prefix
  493. self.suffix = suffix
  494. self.grouping = grouping
  495. self.int_prec = int_prec
  496. self.frac_prec = frac_prec
  497. self.exp_prec = exp_prec
  498. self.exp_plus = exp_plus
  499. if '%' in ''.join(self.prefix + self.suffix):
  500. self.scale = 2
  501. elif u'‰' in ''.join(self.prefix + self.suffix):
  502. self.scale = 3
  503. else:
  504. self.scale = 0
  505. def __repr__(self):
  506. return '<%s %r>' % (type(self).__name__, self.pattern)
  507. def apply(self, value, locale, currency=None, force_frac=None):
  508. frac_prec = force_frac or self.frac_prec
  509. if not isinstance(value, decimal.Decimal):
  510. value = decimal.Decimal(str(value))
  511. value = value.scaleb(self.scale)
  512. is_negative = int(value.is_signed())
  513. if self.exp_prec: # Scientific notation
  514. exp = value.adjusted()
  515. value = abs(value)
  516. # Minimum number of integer digits
  517. if self.int_prec[0] == self.int_prec[1]:
  518. exp -= self.int_prec[0] - 1
  519. # Exponent grouping
  520. elif self.int_prec[1]:
  521. exp = int(exp / self.int_prec[1]) * self.int_prec[1]
  522. if exp < 0:
  523. value = value * 10**(-exp)
  524. else:
  525. value = value / 10**exp
  526. exp_sign = ''
  527. if exp < 0:
  528. exp_sign = get_minus_sign_symbol(locale)
  529. elif self.exp_plus:
  530. exp_sign = get_plus_sign_symbol(locale)
  531. exp = abs(exp)
  532. number = u'%s%s%s%s' % \
  533. (self._format_significant(value, frac_prec[0], frac_prec[1]),
  534. get_exponential_symbol(locale), exp_sign,
  535. self._format_int(str(exp), self.exp_prec[0],
  536. self.exp_prec[1], locale))
  537. elif '@' in self.pattern: # Is it a siginificant digits pattern?
  538. text = self._format_significant(abs(value),
  539. self.int_prec[0],
  540. self.int_prec[1])
  541. a, sep, b = text.partition(".")
  542. number = self._format_int(a, 0, 1000, locale)
  543. if sep:
  544. number += get_decimal_symbol(locale) + b
  545. else: # A normal number pattern
  546. precision = decimal.Decimal('1.' + '1' * frac_prec[1])
  547. rounded = value.quantize(precision)
  548. a, sep, b = str(abs(rounded)).partition(".")
  549. number = (self._format_int(a, self.int_prec[0],
  550. self.int_prec[1], locale) +
  551. self._format_frac(b or '0', locale, force_frac))
  552. retval = u'%s%s%s' % (self.prefix[is_negative], number,
  553. self.suffix[is_negative])
  554. if u'¤' in retval:
  555. retval = retval.replace(u'¤¤¤',
  556. get_currency_name(currency, value, locale))
  557. retval = retval.replace(u'¤¤', currency.upper())
  558. retval = retval.replace(u'¤', get_currency_symbol(currency, locale))
  559. return retval
  560. #
  561. # This is one tricky piece of code. The idea is to rely as much as possible
  562. # on the decimal module to minimize the amount of code.
  563. #
  564. # Conceptually, the implementation of this method can be summarized in the
  565. # following steps:
  566. #
  567. # - Move or shift the decimal point (i.e. the exponent) so the maximum
  568. # amount of significant digits fall into the integer part (i.e. to the
  569. # left of the decimal point)
  570. #
  571. # - Round the number to the nearest integer, discarding all the fractional
  572. # part which contained extra digits to be eliminated
  573. #
  574. # - Convert the rounded integer to a string, that will contain the final
  575. # sequence of significant digits already trimmed to the maximum
  576. #
  577. # - Restore the original position of the decimal point, potentially
  578. # padding with zeroes on either side
  579. #
  580. def _format_significant(self, value, minimum, maximum):
  581. exp = value.adjusted()
  582. scale = maximum - 1 - exp
  583. digits = str(value.scaleb(scale).quantize(decimal.Decimal(1)))
  584. if scale <= 0:
  585. result = digits + '0' * -scale
  586. else:
  587. intpart = digits[:-scale]
  588. i = len(intpart)
  589. j = i + max(minimum - i, 0)
  590. result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format(
  591. intpart=intpart or '0',
  592. pad='',
  593. fill=-min(exp + 1, 0),
  594. fracpart=digits[i:j],
  595. fracextra=digits[j:].rstrip('0'),
  596. ).rstrip('.')
  597. return result
  598. def _format_int(self, value, min, max, locale):
  599. width = len(value)
  600. if width < min:
  601. value = '0' * (min - width) + value
  602. gsize = self.grouping[0]
  603. ret = ''
  604. symbol = get_group_symbol(locale)
  605. while len(value) > gsize:
  606. ret = symbol + value[-gsize:] + ret
  607. value = value[:-gsize]
  608. gsize = self.grouping[1]
  609. return value + ret
  610. def _format_frac(self, value, locale, force_frac=None):
  611. min, max = force_frac or self.frac_prec
  612. if len(value) < min:
  613. value += ('0' * (min - len(value)))
  614. if max == 0 or (min == 0 and int(value) == 0):
  615. return ''
  616. while len(value) > min and value[-1] == '0':
  617. value = value[:-1]
  618. return get_decimal_symbol(locale) + value