Reputation: 22518
Is there a django template filter to get only digits after the floating point?
For example :
2.34 --> 34
2.00 --> 00
1.10 --> 10
I have not found an answer in https://docs.djangoproject.com/en/dev/ref/templates/builtins/.
Upvotes: 1
Views: 2819
Reputation: 41
It's better to write your own filter, but if you don't wanna do it I can propose you one more not optimal "lazy" solution:
{{ value|stringformat:"f"|slice:"-6:-4" }}
Upvotes: 1
Reputation: 2999
As there are too many other questions referred to this one, I'd like to add one more answer too.
As for me the answer proposed by @alecxe is an overkill. Readability sucks and your project begins to depend on additional library. But you only need to show two digits on the page.
The solution with creating own template seems better. It looks simpler, uses less operations, has no dependencies.
@register.filter
def floatfract(value):
sf = "%.2f" % value
return sf.split('.')[1]
And use it in your templates:
{{ object.price|floatfract }}
That's it. I am using it.
Just to make the answer complete, I can extend it with the case when you would like to have flexible fraction length. For example, have from 2 to 5 digits. Looks much worse:
@register.filter
def floatfract(value, length=2):
sf = "%.{length}f".format(length=length) % value
return sf.split('.')[1]
Usage:
{{ object.price|floatfract:5 }}
Upvotes: 0
Reputation: 473853
Aside from creating your own custom filter, you can solve it using django-mathfilters
package:
{{ value|mod:1|mul:100|floatformat:"0" }}
where:
mod
is a "modulo" filter provided by mathfilters
mul
is a "multiplication" filter provided by mathfilters
floatformat
is a built-in django filterDemo:
>>> from django.template import Template, Context
>>> c = Context({'value': 2.34})
>>> t = Template('{% load mathfilters %}{{ value|mod:1|mul:100|floatformat:"0" }}')
>>> t.render(c)
u'34'
Upvotes: 5