Value formatter don't working for dash-ag-grid

Hi. I try to do something like this: Number Filters | Dash for Python Documentation | Plotly. Only with currency GBP,

columnDefs=[{'headerName': col, 
                 'field': col, 
                 "valueFormatter": {
                     "function": "d3.formatLocale({'decimal': '.', 'thousands': ',', 'currency': ['£', '']}).format('£,.2f')(params.value)"
                 },
                } if col in currency_columns
                else {'headerName': col, 'field': col} for col in df.columns
    ]

but get error: “invalid format: £,.2f”
How to fix it
I want to get this format only with £:
image

When try:

columnDefs=[{'headerName': col, 'field': col, 'valueFormatter': {"function": "'£' + (params.value.toFixed(2))"}} if col in currency_columns
                else {'headerName': col, 'field': col} for col in df.columns
    ]

table values is formatted:
image
but I get: 34 errors


what could be the reason for this behavior?

Hello @AlesiaSel,

Welcome to the community!

You should be checking to make sure that a value exists before trying to format it:

columnDefs=[{'headerName': col, 'field': col, 'valueFormatter': {"function": "params.value ? '£' + (params.value.toFixed(2)) : null"}} if col in currency_columns
                else {'headerName': col, 'field': col} for col in df.columns
    ]

This should get you the expected results.

3 Likes

Hi @AlesiaSel !

Indeed if using your second solution 'valueFormatter': {"function": "'£' + (params.value.toFixed(2))"} raises those errors means you have empty values in your dataset, it seems 34…

To handle empty values, as suggested by @jinnyzor you can set:
'valueFormatter': {"function": "params.value ? '£' + (params.value.toFixed(2)) : null"}
Or set the default value to 0:
'valueFormatter': {"function": "params.value ? '£' + (params.value.toFixed(2)) : '£0'"}

About your first solution, using D3 formatter should handle empty values setting them to 0 by default. The issue is the format you used: .format('£,.2f') that should be .format('$,.2f')

$ here is only to tell you want to use the currency locale (defined in d3.formatLocale() as you did using £ as prefix)

Here are more examples using currencies:

2 Likes

D3 value formatter looks good!!! Thanks