Formatting Values in DataModel
DataModel provides flexible APIs for formatting both numeric and temporal (date) values. This guide explains how to apply custom formatting to your data fields.
Number Formatting
You can format numeric values in DataModel using two different approaches:
Schema-level Formatting
Define formatting directly in your field schema by providing a format function:
{
"name": "Acceleration",
"type": "measure",
"defAggFn": "avg",
"format": val => `Formatted Value ${val}`
}
Runtime Formatting
Apply formatting using the formattedData()
method after accessing the field:
dm.getField("Acceleration").formattedData((val) => `Formatted Value ${val}`);
To access formatted values, always chain the .formattedData()
method after retrieving your field:
const formattedValues = dm.getField("Acceleration").formattedData();
Date Formatting
Understanding Date Handling
DataModel internally converts all date values to milliseconds for consistent processing. This makes it essential to specify your date format for proper display.
Configuring Date Formats
Specify the date format in your schema using standard format tokens:
{
"name": "Year",
"type": "dimension",
"subtype": "temporal",
"format": "%Y-%m-%d"
}
Retrieving Formatted Dates
You can retrieve formatted date values in several ways:
- Using the default format specified in schema:
dm.getField("Year").formattedData();
- Using a custom format string:
// Format dates as YYYY
dm.getField("Year").formattedData("%Y");
- Using a custom format function:
dm.getField("Year").formattedData((val) => {
// Custom date formatting logic
return formattedValue;
});
The format string follows the standard date format tokens:
%Y
: Full year (e.g., 2024)%m
: Month (01-12)%d
: Day of month (01-31)