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