Scott Skiles
Scott Skiles

Reputation: 3847

Is there a Django template tag that will convert a percentage to a human readable format?

For example:

I see in humanize there is nothing and I could not find anything in the Django documentation. I have tried {{ value|multiply:100 }}% without success. I know I can write my own template tag but I prefer to avoid doing that whenever possible.

UPDATE: I have also looked into the widthratio tag. For a value of 0.001 it goes to 0%. This is not what I want, unfortunately.

Upvotes: 3

Views: 3127

Answers (5)

Nick Brady
Nick Brady

Reputation: 6572

I went ahead and created a template tag filter like this:

@register.filter
def to_percent(obj, sigdigits):
    if obj:
        return "{0:.{sigdigits}%}".format(obj, sigdigits=sigdigits)
    else: return obj

I was surprised to see the link shared in another answer didn't have a clean solution like that yet. The best one I saw used a try block instead of the if obj... I personally want to see an error in my use case, but that's up to you.

Still, good to know there isn't a more "Django" way to do it that I saw. You'd use this in your template like...

{{{{mymodel.some_percentage_field|to_percent:2}}

where 2 is the number of significant digits you want.

Upvotes: 4

Cyril
Cyril

Reputation: 177

If you only have to format a number with percent, for example "65%" :

{{ number|stringformat:"d%%" }}

Upvotes: 0

shafikshaon
shafikshaon

Reputation: 6404

You can do this with Django built-in template tag withraatio

{% widthratio this_value max_value max_width as width %}

If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).

You can also see the details here

Upvotes: 1

Vipin Joshi
Vipin Joshi

Reputation: 302

As Michael mentioned above, I will suggest you to write your own template tag for that : https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/

Upvotes: 1

Michael Stachura
Michael Stachura

Reputation: 1370

Maybe use one of these solutions: Is there a django template filter to display percentages?

Hope it helps. If not, write your own simple filter :)

Upvotes: -1

Related Questions