千位分隔符 Jinja2

时间:2021-04-25 01:34:00

标签: templates format numbers jinja2 asciidoc

我尝试使用 Jinja2 模板在 AsciiDoc 中打印变量,但找不到使用千位分隔符(空格或点)打印此数字的方法。这个数字作为文本出现,我将它格式化为浮动,然后我用我想要的小数打印它,但除此之外,我想用千位分隔符打印它。我就是这样做的:

### dc_max_avg_memory_usage.json.data.result[0].value[1] = 12345.6789

{{ '%0.0f'| format(dc_max_avg_memory_usage.json.data.result[0].value[1]|float) }} 

这会将数字打印为 12345.67,但我希望它像 12 345,6712.345,67

有人可以帮我吗?提前致谢!

1 个答案:

答案 0 :(得分:0)

Jinja2 的 format 过滤器使用 printf 样式的格式字符串。见https://jinja.palletsprojects.com/en/2.11.x/templates/#format

Python 的 format 函数功能更多,可以使用逗号作为分组操作符。见https://docs.python.org/3/library/string.html#format-specification-mini-language

在 Python 中,您可以:

print('{:,.2f}'.format(12345.6789))

为了能够在 Jinja 模板中使用 Python 的 format,您必须创建一个自定义过滤器:

import jinja2

env = jinja2.Environment()

def commafy(value):
    """Applies thousands separator to floats, with 2 decimal places."""
    return '{:,.2f}'.format(float(value))

env.filters['commafy'] = commafy

template_string = """{{ mynum | commafy }}"""
template = env.from_string(template_string)
print(template.render(mynum='12345.6789'))