2015-02-11 110 views
2

我建立一個網站使用(優秀)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://stackoverflow.com/q/2440692)。 – 2015-02-11 15:54:27

+0

'trim'只需要將值修剪爲參數。你不能指定修剪出什麼。 – 2015-02-11 15:56:47

回答

2

您可以使用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

4

如果你要使用這個有很多,我認爲這是最好寫一個自定義的過濾器,以避免混亂,像這樣:

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'