2009-12-23 01:58:49 +08:00
|
|
|
from django.conf import settings
|
2010-09-27 23:25:08 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2011-04-22 20:03:10 +08:00
|
|
|
def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep=''):
|
2009-12-23 01:58:49 +08:00
|
|
|
"""
|
|
|
|
Gets a number (as a number or string), and returns it as a string,
|
|
|
|
using formats definied as arguments:
|
|
|
|
|
|
|
|
* decimal_sep: Decimal separator symbol (for example ".")
|
|
|
|
* decimal_pos: Number of decimal positions
|
|
|
|
* grouping: Number of digits in every group limited by thousand separator
|
|
|
|
* thousand_sep: Thousand separator symbol (for example ",")
|
|
|
|
|
|
|
|
"""
|
2010-09-27 23:25:08 +08:00
|
|
|
use_grouping = settings.USE_L10N and \
|
|
|
|
settings.USE_THOUSAND_SEPARATOR and grouping
|
|
|
|
# Make the common case fast:
|
|
|
|
if isinstance(number, int) and not use_grouping and not decimal_pos:
|
|
|
|
return mark_safe(unicode(number))
|
2009-12-23 01:58:49 +08:00
|
|
|
# sign
|
|
|
|
if float(number) < 0:
|
|
|
|
sign = '-'
|
|
|
|
else:
|
|
|
|
sign = ''
|
|
|
|
str_number = unicode(number)
|
|
|
|
if str_number[0] == '-':
|
|
|
|
str_number = str_number[1:]
|
2010-09-27 23:25:08 +08:00
|
|
|
# decimal part
|
2009-12-23 01:58:49 +08:00
|
|
|
if '.' in str_number:
|
|
|
|
int_part, dec_part = str_number.split('.')
|
2011-04-22 20:03:10 +08:00
|
|
|
if decimal_pos is not None:
|
2009-12-23 01:58:49 +08:00
|
|
|
dec_part = dec_part[:decimal_pos]
|
|
|
|
else:
|
|
|
|
int_part, dec_part = str_number, ''
|
2011-04-22 20:03:10 +08:00
|
|
|
if decimal_pos is not None:
|
2009-12-23 01:58:49 +08:00
|
|
|
dec_part = dec_part + ('0' * (decimal_pos - len(dec_part)))
|
|
|
|
if dec_part: dec_part = decimal_sep + dec_part
|
|
|
|
# grouping
|
2010-09-27 23:25:08 +08:00
|
|
|
if use_grouping:
|
2009-12-23 01:58:49 +08:00
|
|
|
int_part_gd = ''
|
|
|
|
for cnt, digit in enumerate(int_part[::-1]):
|
|
|
|
if cnt and not cnt % grouping:
|
|
|
|
int_part_gd += thousand_sep
|
|
|
|
int_part_gd += digit
|
|
|
|
int_part = int_part_gd[::-1]
|
|
|
|
return sign + int_part + dec_part
|
|
|
|
|