Django - 删除模板中Decimal的尾随零

Max*_*ysh 9 python django django-templates

有没有办法从Decimaldjango模板中的字段中删除尾随零?

这就是我所拥有的:0.0002559000这就是我所需要的:0.0002559.

有建议使用floatformat过滤器做到这一点的答案:

{{ balance.bitcoins|floatformat:3 }}
Run Code Online (Sandbox Code Playgroud)

但是,floatformat执行舍入(向下或向上),这在我的情况下是不需要的,因为我只需要删除尾随零而没有任何舍入.

Max*_*ysh 17

解决方案是使用以下normalize()方法:

{{ balance.bitcoins.normalize }}
Run Code Online (Sandbox Code Playgroud)

  • 有关此内容的文档位于 https://docs.python.org/3/library/decimal.html?highlight=normalize#decimal.Context.normalize (2认同)

Aiv*_*var 6

尝试{{ balance.bitcoins|floatformat:"-3" }}

\n

https://docs.djangoproject.com/en/stable/ref/templates/builtins/#floatformat

\n
\n

如果传递给 floatformat 的参数为负数,它会将数字四舍五入到小数位数 \xe2\x80\x93,但前提是有\xe2\x80\x99s 要显示的小数部分\n。

\n
\n