You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

numberformat.py 1.9 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import unicode_literals
  2. from decimal import Decimal
  3. from django.conf import settings
  4. from django.utils import six
  5. from django.utils.safestring import mark_safe
  6. def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
  7. force_grouping=False):
  8. """
  9. Gets a number (as a number or string), and returns it as a string,
  10. using formats defined as arguments:
  11. * decimal_sep: Decimal separator symbol (for example ".")
  12. * decimal_pos: Number of decimal positions
  13. * grouping: Number of digits in every group limited by thousand separator
  14. * thousand_sep: Thousand separator symbol (for example ",")
  15. """
  16. use_grouping = settings.USE_L10N and settings.USE_THOUSAND_SEPARATOR
  17. use_grouping = use_grouping or force_grouping
  18. use_grouping = use_grouping and grouping > 0
  19. # Make the common case fast
  20. if isinstance(number, int) and not use_grouping and not decimal_pos:
  21. return mark_safe(six.text_type(number))
  22. # sign
  23. sign = ''
  24. if isinstance(number, Decimal):
  25. str_number = '{:f}'.format(number)
  26. else:
  27. str_number = six.text_type(number)
  28. if str_number[0] == '-':
  29. sign = '-'
  30. str_number = str_number[1:]
  31. # decimal part
  32. if '.' in str_number:
  33. int_part, dec_part = str_number.split('.')
  34. if decimal_pos is not None:
  35. dec_part = dec_part[:decimal_pos]
  36. else:
  37. int_part, dec_part = str_number, ''
  38. if decimal_pos is not None:
  39. dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
  40. if dec_part:
  41. dec_part = decimal_sep + dec_part
  42. # grouping
  43. if use_grouping:
  44. int_part_gd = ''
  45. for cnt, digit in enumerate(int_part[::-1]):
  46. if cnt and not cnt % grouping:
  47. int_part_gd += thousand_sep[::-1]
  48. int_part_gd += digit
  49. int_part = int_part_gd[::-1]
  50. return sign + int_part + dec_part