Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format the display of floats when using django-tables2?

I am using django-tables2 to display some data. I have a column of floats and want them to be shown to just two decimal places (so, 10.238324 would be shown as 10.24). Is there a simple way to do this? In Django templates, I do this using {{number||floatformat:2}}.

Potentially relevant docs:
http://django-tables2.readthedocs.io/en/latest/pages/column-attributes.html.

like image 587
cort Avatar asked Jan 02 '23 21:01

cort


1 Answers

If you only have one column with floats, format your value in a render_<column_name>() method:

class NumberTable(tables.Table):
    number = tables.Column()

    def render_number(self, value):
        return '{:0.2f}'.format(value)

If you have multiple columns with floats, you can define a custom column and reuse it:

class NumberColumn(tables.Column):
    def render(self, value):
        return '{:0.2f}'.format(value)


class NumberTable(tables.Table):
    temperature = NumberColumn()
    pressure = NumberColumn()
    flow = NumberColumn()

This custom column might also implement a custom constructor adding the number of decimals if that's something you want to vary.

like image 157
Jieter Avatar answered Jan 05 '23 16:01

Jieter