Format numbers in django templates

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

    Slightly off topic:

    I found this question while looking for a way to format a number as currency, like so:

    $100
    ($50)  # negative numbers without '-' and in parens
    

    I ended up doing:

    {% if   var >= 0 %} ${{ var|stringformat:"d" }}
    {% elif var <  0 %} $({{ var|stringformat:"d"|cut:"-" }})
    {% endif %}
    

    You could also do, e.g. {{ var|stringformat:"1.2f"|cut:"-" }} to display as $50.00 (with 2 decimal places if that's what you want.

    Perhaps slightly on the hacky side, but maybe someone else will find it useful.

提交回复
热议问题