Dash AG Grid Table numeric columns not sorting after adding comma seperator

I have a python dash app where I am creating a table using dash AG grid. In my table, i have a mix of columns some strings and some numeric. However the numeric columns before adding them in the table I am adding a comma separator to make them legible. The problem is when I enable sorting in the table, formatted numeric columns don’t sort as expected since they are treated as text. Is there a way I can format the numbers while maintaining them as numeric? See codes below.

This is the function i use to add separator to numeric columns

def format_with_commas(val):
    if pd.isnull(val):
        return ""
    else:
        return "{:,.0f}".format(val)

This is the callback I use to generate the dash ag grid table

@callback(
    Output("table-overview", "rowData"),
    Output("table-overview", "columnDefs"),
    State("tree-select-region", "value"),
)
def update_table(region):
    df_to_display = df[['Building Type', 'Headcount', 'Seatcount', 'Annual Rent', 'Rentable Area']].rename(columns={"Building Type": "Type", "Seatcount": "WS", "Headcount": "HC", "Rentable Area": f"GIA ({uom})", "Annual Rent": f"Rent ({currency})"})

    # Apply formatting to selected columns
    for col in ['HC', 'WS', f'Rent ({currency})', f'GIA ({uom})']:
        df_to_display[col] = df_to_display[col].apply(format_with_commas)

    columns = [
        {'headerName': 'Type', 'field': 'Type'},
        {'headerName': 'HC', 'field': 'HC'},
        {'headerName': 'WS', 'field': 'WS'},
        {'headerName': f'Rent ({currency})', 'field': f'Rent ({currency})'},
        {'headerName': f'GIA ({uom})', 'field': f'GIA ({uom})'}
    ]
    return df_to_display.to_dict('records'), columns

Hello @GabrielBKaram,

This is probably an issue with the values, as it’s probably being read as text. Instead of using a formatter in Python, have you considered using the valueFormatter with d3 on the columnDefs?

@jinnyzor genius! works great. thanks a lot

1 Like