Django float format get only digits after floating point

后端 未结 3 883
误落风尘
误落风尘 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 }}
    

提交回复
热议问题