Format numbers in django templates

前端 未结 13 1066
清歌不尽
清歌不尽 2020-11-29 17:22

I\'m trying to format numbers. Examples:

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

It strikes as a

相关标签:
13条回答
  • 2020-11-29 18:02

    Not sure why this has not been mentioned, yet:

    {% load l10n %}
    
    {{ value|localize }}
    

    https://docs.djangoproject.com/en/1.11/topics/i18n/formatting/#std:templatefilter-localize

    You can also use this in your Django code (outside templates) by calling localize(number).

    0 讨论(0)
  • 2020-11-29 18:05

    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.

    0 讨论(0)
  • 2020-11-29 18:07

    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)
    
    0 讨论(0)
  • 2020-11-29 18:09

    Try adding the following line in settings.py:

    USE_THOUSAND_SEPARATOR = True
    

    This should work.

    Refer to documentation.


    update at 2018-04-16:

    There is also a python way to do this thing:

    >>> '{:,}'.format(1000000)
    '1,000,000'
    
    0 讨论(0)
  • 2020-11-29 18:10

    Regarding Ned Batchelder's solution, here it is with 2 decimal points and a dollar sign. This goes somewhere like my_app/templatetags/my_filters.py

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

    Then you can

    {% load my_filters %}
    {{my_dollars | currency}}
    
    0 讨论(0)
  • 2020-11-29 18:10

    The humanize app offers a nice and a quick way of formatting a number but if you need to use a separator different from the comma, it's simple to just reuse the code from the humanize app, replace the separator char, and create a custom filter. For example, use space as a separator:

    @register.filter('intspace')
    def intspace(value):
        """
        Converts an integer to a string containing spaces every three digits.
        For example, 3000 becomes '3 000' and 45000 becomes '45 000'.
        See django.contrib.humanize app
        """
        orig = force_unicode(value)
        new = re.sub("^(-?\d+)(\d{3})", '\g<1> \g<2>', orig)
        if orig == new:
            return new
        else:
            return intspace(new)
    
    0 讨论(0)
提交回复
热议问题