Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django – remove trailing zeroes for a Decimal in a template

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.

like image 991
Max Malysh Avatar asked Oct 19 '16 15:10

Max Malysh


People also ask

How do you get rid of trailing zeros after a decimal?

You can remove trailing zeros using TRIM() function.

How do I round a template in Django?

You can use floatformat to round of the value in django template. If you want to perform more mathematical operations, you can try django-mathfilters. Or you could write your custom template tag and perform the operations in that template tag.

How do you remove trailing zeros from strings?

Algorithm. Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.


2 Answers

The solution is to use the normalize() method:

{{ balance.bitcoins.normalize }}
like image 169
Max Malysh Avatar answered Sep 16 '22 13:09

Max Malysh


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

https://docs.djangoproject.com/en/2.0/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.

like image 28
Aivar Avatar answered Sep 16 '22 13:09

Aivar