numberformat.py 1.7 KB

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