This a thousand seperator filter as PHP number_format() function:
@app.template_filter()
def number_format(value, tsep=',', dsep='.'):
s = unicode(value)
cnt = 0
numchars = dsep + '0123456789'
ls = len(s)
while cnt < ls and s[cnt] not in numchars:
cnt += 1
lhs = s[:cnt]
s = s[cnt:]
if not dsep:
cnt = -1
else:
cnt = s.rfind(dsep)
if cnt > 0:
rhs = dsep + s[cnt+1:]
s = s[:cnt]
else:
rhs = ''
splt = ''
while s != '':
splt = s[-3:] + tsep + splt
s = s[:-3]
return lhs + splt[:-1] + rhs
Based on a snippet on activestate: Thousands Separator. Original code by Michael Robellard.
This snippet by Eunjin Lee can be used freely for anything you like. Consider it public domain.
Comments
alternative (python 2.7+) by B S on 2013-04-09 @ 22:21
An alternative for this in python 2.7+ that will work with a float `value` is:
@app.template_filter def number_format(value) return '{:,.2f}'.format(value)
will turn 123456789.1234 into '123,456,789.12'
It is also possible to remove the `.2f` to work with integers... more info on `format()` here: http://docs.python.org/2/library/string.html#formatspec