Django – remove trailing zeroes for a Decimal in a template

Question:

Is there a way to remove trailing zeros from a Decimal field in a django template?

This is what I have: 0.0002559000 and this is what I need: 0.0002559.

There are answers suggesting to do this using the floatformat filter:

{{ balance.bitcoins|floatformat:3 }}

However, floatformat performs rounding (either down or up), which is unwanted in my case, as I only need to remove trailing zeros without any rounding at all.

Asked By: Max Malysh

||

Answers:

The solution is to use the normalize() method:

{{ balance.bitcoins.normalize }}
Answered By: Max Malysh

Try {{ balance.bitcoins|floatformat:"-3" }}.

https://docs.djangoproject.com/en/stable/ref/templates/builtins/#floatformat:

If the argument passed to floatformat is negative, it will round a
number to that many decimal places – but only if there’s a decimal
part to be displayed.

Answered By: Aivar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.