Python 在 jinja2 中是否有直接的方法来格式化数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12681036/
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
Is there a direct approach to format numbers in jinja2?
提问by Lucas
I need to format decimal numbers in jinja2.
我需要在 jinja2 中格式化十进制数字。
When I need to format dates, I call the strftime() method in my template, like this:
当我需要格式化日期时,我会在模板中调用 strftime() 方法,如下所示:
{{ somedate.strftime('%Y-%m-%d') }}
I wonder if there is a similar approach to do this over numbers.
我想知道是否有类似的方法可以在数字上做到这一点。
Thanks in advance!
提前致谢!
采纳答案by Lipis
You can do it simply like this, the Python way:
你可以像这样简单地做到这一点,Python 方式:
{{ '%04d' % 42 }}
{{ 'Number: %d' % variable }}
Or using that method:
或使用该方法:
{{ '%d' | format(42) }}
I personally prefer the first one since it's exactly like in Python.
我个人更喜欢第一个,因为它与 Python 中的完全一样。
回答by Tkingovr
You could use round it will let you round the number to a given precision usage is:
您可以使用 round 它可以让您将数字四舍五入到给定的精度用法是:
round(value, precision=0, method='common')
The first parameter specifies the precision (default is 0), the second the rounding method from which you can choose 3:
第一个参数指定精度(默认为 0),第二个参数指定舍入方法,您可以从中选择 3:
'common' rounds either up or down
'ceil' always rounds up
'floor' always rounds down
回答by Yuji 'Tomita' Tomita
I want to highlight Joran Beasley's comment because I find it the best solution:
我想强调 Joran Beasley 的评论,因为我发现它是最好的解决方案:
Original comment:
原评论:
can you not do {{ "{0:0.2f}".format(my_num) }} or {{ my_num|format "%0.2f" }} (wsgiarea.pocoo.org/jinja/docs/filters.html#format) – Joran Beasley Oct 1 '12 at 21:07`
你能不能不做 {{ "{0:0.2f}".format(my_num) }} 或 {{ my_num|format "%0.2f" }} (wsgiarea.pocoo.org/jinja/docs/filters.html#format ) – Joran Beasley 2012 年 10 月 1 日 21:07`
Indeed, {{ '{0:0.2f}'.format(100) }}works fantastically.
确实,{{ '{0:0.2f}'.format(100) }}效果非常好。
This is just python string formatting. Given the first argument, {0}, format it with the following format 0.2f.
这只是python字符串格式。给定第一个参数 ,{0}使用以下格式对其进行格式化0.2f。
回答by Sandip Bhattacharya
Formatting and padding works well in the same way.
格式化和填充以同样的方式工作得很好。
{{ "{0}".format(size).rjust(15) }}

