Development of an internal social media platform with personalised dashboards for students
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 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from decimal import Decimal
  2. from django.conf import settings
  3. from django.utils.safestring import mark_safe
  4. def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
  5. force_grouping=False, use_l10n=None):
  6. """
  7. Get a number (as a number or string), and return 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. For non-uniform digit grouping, it can be a sequence with the number
  13. of digit group sizes following the format used by the Python locale
  14. module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).
  15. * thousand_sep: Thousand separator symbol (for example ",")
  16. """
  17. use_grouping = (use_l10n or (use_l10n is None and settings.USE_L10N)) and settings.USE_THOUSAND_SEPARATOR
  18. use_grouping = use_grouping or force_grouping
  19. use_grouping = use_grouping and grouping != 0
  20. # Make the common case fast
  21. if isinstance(number, int) and not use_grouping and not decimal_pos:
  22. return mark_safe(str(number))
  23. # sign
  24. sign = ''
  25. if isinstance(number, Decimal):
  26. str_number = '{:f}'.format(number)
  27. else:
  28. str_number = str(number)
  29. if str_number[0] == '-':
  30. sign = '-'
  31. str_number = str_number[1:]
  32. # decimal part
  33. if '.' in str_number:
  34. int_part, dec_part = str_number.split('.')
  35. if decimal_pos is not None:
  36. dec_part = dec_part[:decimal_pos]
  37. else:
  38. int_part, dec_part = str_number, ''
  39. if decimal_pos is not None:
  40. dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
  41. dec_part = dec_part and decimal_sep + dec_part
  42. # grouping
  43. if use_grouping:
  44. try:
  45. # if grouping is a sequence
  46. intervals = list(grouping)
  47. except TypeError:
  48. # grouping is a single value
  49. intervals = [grouping, 0]
  50. active_interval = intervals.pop(0)
  51. int_part_gd = ''
  52. cnt = 0
  53. for digit in int_part[::-1]:
  54. if cnt and cnt == active_interval:
  55. if intervals:
  56. active_interval = intervals.pop(0) or active_interval
  57. int_part_gd += thousand_sep[::-1]
  58. cnt = 0
  59. int_part_gd += digit
  60. cnt += 1
  61. int_part = int_part_gd[::-1]
  62. return sign + int_part + dec_part