我正在使用 django-tables2 来显示一些数据。我有一列浮点数,并希望它们只显示两位小数(因此, 10.238324
将显示为 10.24
)。有没有一种简单的方法可以做到这一点?在 Django 模板中,我使用 {{number||floatformat:2}}
来做到这一点。 .
可能相关的文档:
http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html .
最佳答案
如果您只有一列带有浮点数,请在 render_<column_name>()
method 中格式化您的值:
class NumberTable(tables.Table):
number = tables.Column()
def render_number(self, value):
return '{:0.2f}'.format(value)
如果您有多个带有浮点数的列,您可以定义一个 custom column并重用它:
class NumberColumn(tables.Column):
def render(self, value):
return '{:0.2f}'.format(value)
class NumberTable(tables.Table):
temperature = NumberColumn()
pressure = NumberColumn()
flow = NumberColumn()
如果您想更改小数位数,此自定义列还可以实现自定义构造函数来添加小数位数。
关于django - 使用 django-tables2 时如何格式化 float 的显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48546729/