Django float format get only digits after floating point

后端 未结 3 884
误落风尘
误落风尘 2021-01-16 06:52

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


        
相关标签:
3条回答
  • 2021-01-16 07:35

    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 }}
    
    0 讨论(0)
  • 2021-01-16 07:43

    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'
    
    0 讨论(0)
  • 2021-01-16 07:58

    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" }}
    
    0 讨论(0)
提交回复
热议问题