django - 使用 django-tables2 时如何格式化 float 的显示?

标签 django django-tables2

我正在使用 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/

相关文章:

python - 我无法使用 docker-compose 对 MySQL 和 Django App 进行 Dockerize

django - Django/Celery 中的周期性任务 - 如何在屏幕上通知用户?

python - 以天为单位的日期时间差异的高性能计算

python - 从 ORM 中提取数据并按日期分组

django-tables2 - 为 django-tables2 设置空文本行为

django-tables2 linkcolumn 同一单元格中的多个项目

django - Django 表 2 中的链接列

python - 在 python 的 __init__ 处获取装饰器内的方法类名

django-models - 使用 django-tables2 如何显示模型@property?

django - 在 django-tables2 中禁用分页?