Reputation: 93793
In a Django template, is there a way to convert a float into an integer if and only if it ends in .0?
I have a field for population that is a float in my database. Sometimes it is 'really' a float, ending .5, but more often it ends .0, because there is a whole number of people, and in those cases I'd rather just show an integer.
{{ place.population }} people
Any ideas for a clever way to get round this in Django?
Upvotes: 15
Views: 26879
Reputation: 823
You could write a template tag, but I'd recommend making this a method on your model.
class Country(models.Model):
...
def get_population(self):
if self.population == int(self.population):
self.population = int(self.population)
return self.population
Then in your template, instead of
{{ obj.population }}
You would use this:
{{ obj.get_population }}
Upvotes: 2
Reputation: 50786
You can use the floatformat filter with a negative argument!
Upvotes: 41