Jinja模板 - 将浮点数格式化为逗号分隔的货币

Kyl*_*son 39 python jinja2 flask

我正在尝试将浮点格式化为逗号分隔的货币.我543921.9354变成了$543,921.94.我format在Jinja模板中使用过滤器,它似乎模仿%Python中的运算符而不是Python format函数?

如何在Jinja中完成此格式化?是否可以使用format过滤器?这就是我到目前为止所做的事情,它除了逗号之外还完成了所有事情:

"$%.2f"|format(543921.9354)

这当然会产生

$543921.94

bio*_*ker 64

更新:使用Jinja2和Python 3,这在模板中运行得非常好,无需定义任何自定义代码:

{{ "${:,.2f}".format(543921.9354) }}
Run Code Online (Sandbox Code Playgroud)

我不确定依赖是什么让这项工作,但恕我直言,其他人阅读这个答案将至少尝试它之前,担心自定义过滤器.

  • 这对我来说也适用于Python 2.7.很棒的答案! (2认同)

ale*_*asi 48

为此编写自定义过滤器.如果您使用的是python 2.7,它可能如下所示:

def format_currency(value):
    return "${:,.2f}".format(value)
Run Code Online (Sandbox Code Playgroud)


小智 10

Python3.6:

def numberFormat(value):
    return format(int(value), ',d')
Run Code Online (Sandbox Code Playgroud)

Flask 全局过滤器

@app.template_filter()
def numberFormat(value):
    return format(int(value), ',d')
Run Code Online (Sandbox Code Playgroud)

蓝图的 Flask 全局过滤器

@app.app_template_filter()
def numberFormat(value):
    return format(int(value), ',d')
Run Code Online (Sandbox Code Playgroud)

调用这个全局过滤器

{{ '1234567' | numberFormat }}
#prints 1,234,567
Run Code Online (Sandbox Code Playgroud)

在 Jinja 中调用它而不分配全局过滤器

{{ format('1234567', ',d') }}
#prints 1,234,567
Run Code Online (Sandbox Code Playgroud)


sea*_*ers 5

为了扩展@alex vasi的答案,我肯定会编写一个自定义过滤器,但是我还将使用python自己的locale功能,该功能处理货币分组和符号,

def format_currency(value):
    return locale.currency(value, symbol=True, grouping=True)
Run Code Online (Sandbox Code Playgroud)

使用的主要注意事项locale是它不适用于默认的“ C”语言环境,因此您必须对其进行设置,以使其在计算机上可用。

对于您要找的东西,您可能需要,

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
Run Code Online (Sandbox Code Playgroud)

但是如果您想要英镑,就可以使用,

locale.setlocale(locale.LC_ALL, 'en_GB.UTF_8')
Run Code Online (Sandbox Code Playgroud)

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.currency(543921.94, symbol=True, grouping=True)
> '$543,921.94'
locale.setlocale(locale.LC_ALL, 'en_GB')
> '£543,921.94'
Run Code Online (Sandbox Code Playgroud)