Showing Percentage in AgGrid

Hi All
I’m currently using Streamlit-Aggrid to create a dashboard, but is there anyway I can show percentage such as 72.7% without changing the data to type ‘str’?
Because I need to use the sorting function on webpage, so df[‘temp’].astype(‘str’) + ‘%’ won’t cut it~
image

Many Thanks
Oliver Jia

Hi Oliver,

would an f-string work here? One of these two:

f"{df['temp']:.1f} %"   # if data is already percentage
f"{df['temp']:.1%}"     # if not

I tried these and .style.format() before, it works with st.dataframe() but not works with AgGrid() :sob:

I just had a look at one of the examples from the developer. Looks like it’s a little more complicated with AgGrid. There is something called a GridOptionsBuilder that lets you configure various properties of columns.

In the AgGrid Documentation, you can also find a ValueFormatter. Not sure how that works though - I don’t know JavaScript.

I’m still not sure how it works, but if I understand the example correctly, you need to do something like this:

gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_column("temp", custom_format_string='%')

or maybe something like this:

gridOptions = {
    "columnDefs": [
        {
        "field": "temp", 
        "valueFormatter": "x.toLocaleString() + '%'"
        },
    ]
}

[....]

grid = AgGrid(
    df,
    gridOptions=gridOptions,
)

Hope that helps a little (sorry, I haven’t tried it myself, so not sure if any of this works). Let me know if you figure it out.

Hi much appreciate with your help, this method do change the format of the columns to percentage display, but because it change to string value, on page sorting still be a problem :sob:

@oliverjia did you ever find a solution for this?

Unfortunately No :sob: Have to let the user get use to it :rofl:

This is what we use:

from st_aggrid import JsCode, AgGrid, GridOptionsBuilder

AG_GRID_PERCENT_FORMATTER = JsCode(
    """
    function customPercentFormatter(params) {
        let n = Number.parseFloat(params.value) * 100;
        let precision = params.column.colDef.precision ?? 0;

        if (!Number.isNaN(n)) {
          return n.toFixed(precision).replace(/\B(?=(\d{3})+(?!\d))/g, ',')+'%';
        } else {
          return '-';
        }
    }
    """
)

and then when building grid options:

go.configure_columns(
            colname,
            type=["numberColumnFilter", "customNumericFormat", "numericColumn"],
            valueFormatter=AG_GRID_PERCENT_FORMATTER,
            precision=2,
        )

Appreciate it! This is really helpful!

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.