Custom Function Value Formatters

For more information on valueFormatter see:

Example 1: Using Intl.NumberFormat

Rather than using d3.format, this example formats currency in different locales using Intl.NumberFormat

The custom functions are registered by adding them to the dashAgGridFunctions namespace. This is added to the dashAgGridFunctions.js file in the assets folder.

Here is an example:

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

dagfuncs.EUR = function(number) {
  return Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number);
}

Then use the function in the columnDefs like this:

columnDefs = [
     {"headerName": "Euro", "field": "EUR", "valueFormatter": {"function": "EUR(params.value)"}},
 ]
"""
Example of currency formatting using Intl.NumberFormat
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat</a>

"""

import dash_ag_grid as dag
from dash import Dash, html, dcc, Input, Output, callback
import pandas as pd

app = Dash(__name__)

df = pd.DataFrame(
    {
        "Exchange": ["Canadian Dollar", "Euro", "Japanese Yen", "US Dollar"],
        "CAD": [1, 1.3128, .000945, 1.3105],
        "EUR": [.7618, 1, .0071980, .9983],
        "JPY": [105.84, 138.94, 1, 138.76],
        "USD": [.7630, 1.0016, .00720950, 1],
    }
)
df = df.set_index("Exchange")


columnDefs = [
    {"headerName": "Currency Exchange Table", "field": "Exchange"},
    {"headerName": "Canadian Dollar", "field": "CAD", "valueFormatter": {"function": "CAD(params.value)"}},
    {"headerName": "Euro", "field": "EUR", "valueFormatter": {"function": "EUR(params.value)"}},
    {"headerName": "Japanese Yen", "field": "JPY", "valueFormatter": {"function": "JPY(params.value)"}},
    {"headerName": "US Dollar", "field": "USD", "valueFormatter": {"function": "USD(params.value)"}}
]


app.layout = html.Div(
    [
        dcc.Markdown("Example of custom functions using `Intl.NumberFormat` to format currencies"),

        html.Label("Amount to Exchange"),
        dcc.Input(id="currency-exchange-input", type="number", value=1000),
        dag.AgGrid(
            id="currency-exchange-grid",
            columnDefs=columnDefs,
            columnSize="sizeToFit",
            defaultColDef={"type": "rightAligned"}
        )

    ], style={"margin": 20}
)


@callback(
    Output("currency-exchange-grid", "rowData"), Input("currency-exchange-input", "value")
)
def update_table(amount):
    dff = df.multiply(amount, fill_value=0) if amount else df.copy()
    return dff.reset_index().to_dict("records")


if __name__ == "__main__":
    app.run(debug=True)


"""
Put the following in the dashAgGridComponentFunctions.js file in the assets folder
This will register the functions used to format the currencies.

---------------

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

dagfuncs.Intl = Intl

dagfuncs.EUR = function(number) {
  return Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number);
}


dagfuncs.JPY = function(number) {
  return Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)
}


dagfuncs.USD = function(number) {
  return Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
}


dagfuncs.CAD = function(number) {
  return Intl.NumberFormat('en-CA', { style: 'currency', currency: 'CAD', currencyDisplay: 'code' }).format(number);
}



"""

Example of custom functions using Intl.NumberFormat to format currencies

Example 2: Custom Function for blank when NaN

This example adds more features to the function that formats currency and percentages. It will return blanks
instead of NaN when text or other invalid numbers are entered in the January or Budget columns.

"""
String formatting with basic JavaScript function
"""
import dash_ag_grid as dag
from dash import Dash, html, dcc

app = Dash(__name__)

rowData = [
    dict(account='Salaries',  January=103567.34, Budget=110000),
    dict(account='Rent',  January=8745.00, Budget=7000),
    dict(account='Utilities',  January=-3745.34, Budget=2000),
    dict(account='Bad Debt',  January=2546.78, Budget=3000),
    dict(account='Depreciation',  January=4000.00, Budget=4000),
]


columnDefs = [
    {
        "field": "account",
    },
    {
        "field": "January",
        "valueFormatter": {"function": "MoneyFilna(params.value)"},
        "editable": True
    },
    {
        "field": "Budget",
        "valueFormatter": {"function": "MoneyFilna(params.value)"},
        "editable":True
    },
    {
        "headerName": "Variance",
        "valueGetter": {"function": "(Number(params.data.January) - Number(params.data.Budget)) / Number(params.data.Budget)"},
        "valueFormatter": {"function": "PercentageFilna(params.value)"},

    },
]

defaultColDef = {
    "resizable": True,
    "editable": False,
}

app.layout = html.Div(
    [
        dcc.Markdown(
            """
            This example demonstrates a custom function that replaces NaN with blanks.
            Try entering invalid number in the January or Budget columns.

            -----------

            """,

        ),
        html.H4("Expense Summary for January"),
        dag.AgGrid(
            id="custom-function-2",
            columnDefs=columnDefs,
            rowData=rowData,
            columnSize="sizeToFit",
            defaultColDef=defaultColDef,
        ),
    ],
    style={"margin": 20},
)


if __name__ == "__main__":
    app.run(debug=True)



"""
Put the following in the dashAgGridComponentFunctions.js file in the assets folder
This will register the functions used to format the currencies.

---------------

var dagfuncs = window.dashAgGridFunctions = window.dashAgGridFunctions || {};

dagfuncs.Intl = Intl

dagfuncs.EUR = function(number) {
  return Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number);
}


dagfuncs.JPY = function(number) {
  return Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)
}


dagfuncs.USD = function(number) {
  return Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
}


dagfuncs.CAD = function(number) {
  return Intl.NumberFormat('en-CA', { style: 'currency', currency: 'CAD', currencyDisplay: 'code' }).format(number);
}


dagfuncs.PercentageFilna = function(number, filna="") {
    if (isNaN(number)){
        return filna
    }
    return Intl.NumberFormat("en-US", {style: "percent"}).format(number)
}



dagfuncs.MoneyFilna = function(number, filna="") {
    if (isNaN(number)){
        return filna
    }
    return Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
}


"""

This example demonstrates a custom function that replaces NaN with blanks.
Try entering invalid number in the January or Budget columns.


Expense Summary for January