Format numbers in django templates

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

提交回复
热议问题