Flask Snippets

number_format filter

By Eunjin Lee filed in Template Tricks

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