我想要類似於string formatting from the standard library的東西。是否有一個Django模板過濾器顯示百分比?
'%'百分比。將數字 乘以100,並以固定('f') 格式顯示,然後顯示百分號。
我想要類似於string formatting from the standard library的東西。是否有一個Django模板過濾器顯示百分比?
'%'百分比。將數字 乘以100,並以固定('f') 格式顯示,然後顯示百分號。
string.Formatter()
的新穎性意味着Django不太可能支持它的內置。可以編寫或查找實現它的模板標籤或過濾器。
萬一有人找answser,這是我的問題解決了使用自定義templatetag:
from django import template
register = template.Library()
@register.filter
def percentage(value):
return format(value, "%")
這是我如何解決了這個問題:用
from django import template
register = template.Library()
def percentage(value):
return '{0:.2%}'.format(value)
register.filter('percentage', percentage)
更好的解決方案國際化與Python 2.5一起工作。
from django import template
register = template.Library()
from django.template.defaultfilters import floatformat
@register.filter
def percent(value):
if value is None:
return None
return floatformat(value * 100.0, 2) + '%'
下面是我使用的是什麼(我們只列出小數,沒有花車,順便說一句):
@register.filter
def as_percentage_of(part, whole):
try:
return "%d%%" % (float(part)/whole * 100)
except (ValueError, ZeroDivisionError):
return ""
使用方法如下:
Monkeys constitute {{ monkeys|as_percentage_of:animals }} of all animals.
其中,如果猴子是3和動物是6,你會得到:
50%
我正在尋找幾乎相同的問題,發現模板標籤寬度。 您可以使用此標記從原始值和計算百分比的總值中計算模板中的百分比,而不是像您的問題中那樣計算百分比。它的工作,如果你只需要在沒有精確的整數百分比:
{% widthratio value total_value 100 %}
編號:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#widthratio
如果你想控制小數位:'返回格式(價值「 0.2%」)'(用於2位小數) – User 2017-09-19 12:46:26