4π
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.
1π
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/
- [Django]-Is it possible to redirect the python output to web by using 'sys.stdout' command?
- [Django]-Django. Remove select_related from queryset
- [Django]-Django Custom User Model Best Practice: User = get_user_model()?
- [Django]-How can I display an jupyter notebook on a homepage built with django?
- [Django]-Logging out on django web app redirects to django admin logout page. What's going on?
1π
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
0π
If you only have to format a number with percent, for example β65%β :
{{ number|stringformat:"d%%" }}
- [Django]-Django β NameError: name 'Post' is not defined in many to many relationship
- [Django]-DjangoQ run manage.py qcluster results in PermissionError: [WinError5] Access is denied
-1π
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 π
- [Django]-Wagtail: Can i use the API for fetching read-only drafts of pages for review?
- [Django]-Problem trying to achieve a join using the `comments` contrib in Django