Format numbers in django templates

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

    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)
    

提交回复
热议问题