Is there a django template filter to display percentages?

I was looking for almost the same question and found the widthratio template tag. Instead of having the percentage already calculated like in your question, you can use this tag to calculate the percentage in the template from the original value and total value against which your percentage is calculated. It does the job if you only need an integer percentage without precision:

{% widthratio value total_value 100 %}

Ref: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#widthratio


In case somebody is looking for the answser, this is how I solved the problem with a custom templatetag:

from django import template

register = template.Library()

@register.filter
def percentage(value):
    return format(value, "%")

Here's what I'm using (we only show decimals, not floats, by the way):

@register.filter
def as_percentage_of(part, whole):
    try:
        return "%d%%" % (float(part) / whole * 100)
    except (ValueError, ZeroDivisionError):
        return ""

Use it like this:

Monkeys constitute {{ monkeys|as_percentage_of:animals }} of all animals.

where if monkeys is 3 and animals is 6, you'll get:

50%

This is how I solved the problem:

from django import template

register = template.Library()

def percentage(value):
    return '{0:.2%}'.format(value)

register.filter('percentage', percentage)