Format numbers in django templates

前端 未结 13 1177
清歌不尽
清歌不尽 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: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}}
    

提交回复
热议问题