Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django and floatformat tag

Tags:

I want to modify / change the way the floatformat works.

By default it changes the input decimal as such:

{{ 1.00|floatformat }} -> 1
{{ 1.50|floatformat }} -> 1.5
{{ 1.53|floatformat }} -> 1.53

I want to change this abit as such: If there is a floating part, it should keep the first 2 floating digits. If no floating (which means .00) it should simply cut out the floating part. IE:

{{ 1.00|floatformat }} -> 1
{{ 1.50|floatformat }} -> 1.50
{{ 1.53|floatformat }} -> 1.53
like image 904
Hellnar Avatar asked Apr 06 '10 09:04

Hellnar


People also ask

What is Floatformat?

The floatformat filter takes an n argument for the number of decimal places to round to. Without that argument, it will round to one decimal place unless the decimal value is 0 , in which case it will just output the integer. filter.

What is a Django tag?

Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page. First, In your application folder, create a "templatetags" directory at the same level as the models and views.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How do you round a number in Django template?

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.


1 Answers

Doesn't using a parameter of -2, as described in the docs you link to, do what you want?

{{ 1.00|floatformat:-2 }}

See Django Docs: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#floatformat

like image 141
Daniel Roseman Avatar answered Nov 16 '22 08:11

Daniel Roseman