jbo*_*chi 21 django formatting django-templates
'%'百分比.将数字乘以100并以固定('f')格式显示,后跟百分号.
Jer*_*dis 60
我正在寻找几乎相同的问题,并找到了widthratio模板标签.您可以使用此标记从原始值和计算百分比的总值计算模板中的百分比,而不是像您的问题中那样计算百分比.如果您只需要一个没有精度的整数百分比,它就可以完成工作:
{% widthratio value total_value 100 %}
Run Code Online (Sandbox Code Playgroud)
参考:https://docs.djangoproject.com/en/dev/ref/templates/builtins/#widthratio
jbo*_*chi 23
如果有人正在寻找答案,这就是我用自定义模板标签解决问题的方法:
from django import template
register = template.Library()
@register.filter
def percentage(value):
return format(value, "%")
Run Code Online (Sandbox Code Playgroud)
tob*_*ych 14
这是我正在使用的(顺便说一下,我们只显示小数,而不是浮点数):
@register.filter
def as_percentage_of(part, whole):
try:
return "%d%%" % (float(part) / whole * 100)
except (ValueError, ZeroDivisionError):
return ""
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
Monkeys constitute {{ monkeys|as_percentage_of:animals }} of all animals.
Run Code Online (Sandbox Code Playgroud)
如果猴子是3,动物是6,你会得到:
50%
Run Code Online (Sandbox Code Playgroud)
小智 7
这就是我解决问题的方法:
from django import template
register = template.Library()
def percentage(value):
return '{0:.2%}'.format(value)
register.filter('percentage', percentage)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20045 次 |
| 最近记录: |