Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use floatformat in a centralized way in Django

In my project I'm asking the user for some measures, prices and weights. I want to store data as a two decimal value. I guess I should be using DecimalField instead of FloatField, because I don't need much precision.

When I print values in my templates, I don't want zero non significant decimals to be printed.

Examples:

10.00 should show simply 10

10.05 should show 10.05

I don't want to use floatformat filter in every template I display the value, too many places. So I was wondering if there is some way to affect the value rendered for all the application, in a centralized manner.

Thanks

like image 207
maraujop Avatar asked Jan 30 '26 10:01

maraujop


1 Answers

Have you tried the django plugin Humanize ?

You might find there what you're looking for.

Edit

Your are right, humanize filters don't do the job here. After digging around the django built-in filters and tags I couldn't find anything that solves your issue. Therefore, I think you need a custom filter for this. Something like ...

from django import template

register = template.Library()

def my_format(value):
    if value - int(value) != 0:
        return value
    return int(value)

register.filter('my_format',my_format)
my_format.is_safe = True

And in your django template you could do something like ...

{% load my_filters %}
<html>
<body>
{{x|my_format}}
<br/>
{{y|my_format}}
</body>
</html>

For values x and y, 1.0 and 1.1 respectively that would show:

  1
  1.1

I hope this helps.

like image 174
Manuel Salvadores Avatar answered Jan 31 '26 22:01

Manuel Salvadores



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!