如果Jinja2没有十进制值,如何舍入为小数点后的零?

问题描述:

我建立一个网站使用(优秀)Flask framework我现在想显示一些数字。通过使用Jinja2提供的round filter工作正常,除了当没有十进制值:如果Jinja2没有十进制值,如何舍入为小数点后的零?

{{ 1.55555|round(2) }} -> 1.56 
{{ 1.5|round(2) }} -> 1.5 
{{ 1.0|round(2) }} -> 1.0 
{{ 1|round(2) }} -> 1.0 

但我想过去两年来显示像1(无尾.0)。有人知道我怎么能用jinja2做到这一点?欢迎所有提示!

[编辑]

我使用trim()尝试,但让我吃惊下面的代码片段给出了一个TypeError: do_trim() takes exactly 1 argument (2 given)

{{ 1.0|round(2)|trim('.0') }} 
+1

我不认为你可以用默认的Jinja2过滤器。也许,或者创建你自己的过滤器来实现这个功能,在Python中用[不使用多余的零来格式化浮点数](http://*.com/q/2440692)。 – 2015-02-11 15:54:27

+0

'trim'只需要将值修剪为参数。你不能指定修剪出什么。 – 2015-02-11 15:56:47

您可以使用string filter,然后使用str.rstrip

>>> import jinja2 
>>> print(jinja2.Template(''' 
... {{ (1.55555|round(2)|string).rstrip('.0') }} 
... {{ (1.5|round(2)|string).rstrip('.0') }} 
... {{ (1.0|round(2)|string).rstrip('.0') }} 
... {{ (1|round(2)|string).rstrip('.0') }} 
... ''').render()) 

1.56 
1.5 
1 
1 

注意

使用str.rstrip,您将得到一个空字符串0

>>> jinja2.Template('''{{ (0|round(2)|string()).strip('.0') }}''').render() 
u'' 

这里是为了避免上述的解决方案(呼叫rstrip两次;与0.一次,连用)

>>> print(jinja2.Template(''' 
... {{ (1.55555|round(2)|string).rstrip('0').rstrip('.') }} 
... {{ (1.5|round(2)|string).rstrip('0').rstrip('.') }} 
... {{ (1.0|round(2)|string).rstrip('0').rstrip('.') }} 
... {{ (1|round(2)|string).rstrip('0').rstrip('.') }} 
... {{ (0|round(2)|string).rstrip('0').rstrip('.') }} 
... ''').render()) 

1.56 
1.5 
1 
1 
0 
+0

太棒了!奇迹般有效!这将是更真棒,如果你也有空字符串问题的解决方案.. :) – kramer65 2015-02-11 16:09:48

+0

@ kramer65,我更新了包含它的答案。 – falsetru 2015-02-11 16:13:40

如果你要使用这个有很多,我认为这是最好写一个自定义的过滤器,以避免混乱,像这样:

from jinja2 import filters 

def myround(*args, **kw): 
    # Use the original round filter, to deal with the extra arguments 
    res = filters.do_round(*args, **kw) 
    # Test if the result is equivalent to an integer and 
    # return depending on it 
    ires = int(res) 
    return (res if res != ires else ires) 

注册它,你就完成了。互动翻译中的例子:

>>> from jinja2 import Environment 
>>> env = Environment() 
>>> env.filters['myround'] = myround 
>>> env.from_string("{{ 1.4|myround(2) }}").render() 
u'1.4' 
>>> env.from_string("{{ 1.4|myround }}").render() 
u'1' 
>>> env.from_string("{{ 0.3|myround }}").render() 
u'0'