Django float format get only digits after floating point

旧街凉风 提交于 2019-12-30 11:34:40

问题


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/.


回答1:


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 filter

Demo:

>>> 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'



回答2:


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" }}



回答3:


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 }}


来源:https://stackoverflow.com/questions/27403675/django-float-format-get-only-digits-after-floating-point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!