Python Jinja2 圆形过滤器不四舍五入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17957511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jinja2 round filter not rounding
提问by Mittenchops
I have the following code in my template:
我的模板中有以下代码:
data: [{% for deet in deets %} {{ deet.value*100|round(1) }}{% if not loop.last %},{% endif %} {% endfor %}]
I am expecting data rounded to 1 decimal place. However, when I view the page or source, this is the output I'm getting:
我希望数据四舍五入到小数点后一位。但是,当我查看页面或源代码时,这是我得到的输出:
data: [ 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818, 44.2765833818 ]
This is not rounded to 1 decimal place. It runs without a template error or anything, but produces incorrect output. My understanding from the documentation, and even a related stack overflow question, are that my format should work. What am I missing or doing wrong?
这不会四舍五入到小数点后 1 位。它运行时没有模板错误或任何错误,但会产生不正确的输出。我从文档,甚至是相关的堆栈溢出问题中了解到,我的格式应该可以工作。我错过了什么或做错了什么?
采纳答案by Mittenchops
Didn't realize the filter operator had precedence over multiplication!
没有意识到过滤运算符优先于乘法!
Following up on bernie's comment, I switched
跟进伯尼的评论,我换了
{{ deet.value*100|round(1) }}
to
到
{{ 100*deet.value|round(1) }}
which solved the problem. I agree the processing should happen in the code elsewhere, and that would be better practice.
这解决了问题。我同意处理应该在其他地方的代码中进行,这将是更好的做法。
回答by John R
You can put parens around the value that you want to round. (This works for division as well, contrary to what @sobri wrote.)
您可以在要舍入的值周围放置括号。(这也适用于除法,与@sobri 所写的相反。)
{{ (deet.value/100)|round }}
NOTE: round
returns a float
so if you really want the int
you have to pass the value through that filter as well.
注意:如果你真的想要你必须通过该过滤器传递值,则round
返回一个float
so int
。
{{ (deet.value/100)|round|int }}
回答by Dan Garthwaite
I ran across this... needed int(mem_total / 4) in jinja. I solved it by making it two operations:
我遇到了这个……在 jinja 中需要 int(mem_total / 4)。我通过进行两个操作来解决它:
{% set LS_HEAP_SIZE = grains['mem_total'] / 4 %}
{% set LS_HEAP_SIZE = LS_HEAP_SIZE | round | int %}
回答by Dithon
Try this
尝试这个
{{ (deet.value*100)|round(1) }}
If we didn't put parenthesis, round will do only to 100 not to the result.
如果我们不加括号,round 只会对 100 进行处理,而不会对结果进行处理。
回答by Denis Shulyaka
If filter operator has precedence, then you should use round(3) instead of round(1) in "{{ 100*deet.value|round(1) }}"
如果过滤操作符有优先权,那么你应该在 "{{ 100*deet.value|round(1) }}" 中使用 round(3) 而不是 round(1)