Friday, March 4, 2011

Format numbers in django templates

I'm trying to format numbers. Examples:

1     => 1
12    => 12
123   => 123
1234  => 1,234
12345 => 12,345

It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.

Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.

From stackoverflow
  • Well I couldn't find a Django way, but I did find a python way from inside my model:

    def format_price(self):
        import locale
        locale.setlocale(locale.LC_ALL, '')
        return locale.format('%d', self.price, True)
    
  • As far as I can tell it is not currently possible: Django Users: locale aware number formats

  • If you don't want to get involved with locales here is a function that formats numbers:

    def int_format(value, decimal_points=3, seperator=u'.'):
        value = str(value)
        if len(value) <= decimal_points:
            return value
        # say here we have value = '12345' and the default params above
        parts = []
        while value:
            parts.append(value[-decimal_points:])
            value = value[:-decimal_points]
        # now we should have parts = ['345', '12']
        parts.reverse()
        # and the return value should be u'12.345'
        return seperator.join(parts)
    

    Creating a custom template filter from this function is trivial.

  • Django's contributed humanize application does this:

    {% load humanize %}
    {{ my_num|intcomma }}
    
  • Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).

    My proposition: check out the Babel package. Some means of integrating with Django templates are available.

  • Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign.

    from django.contrib.humanize.templatetags.humanize import intcomma
    
    def currency(dollars):
        dollars = float(dollars)
        return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])
    

    Then you can

    {{my_dollars | currency}}
    

0 comments:

Post a Comment