Custom Data Formatting for Tooltips in Chart.js: Implementing Percentage Display

Dec 04, 2025 · Programming · 16 views · 7.8

Keywords: Chart.js | Tooltip Formatting | Percentage Display | JavaScript Data Visualization | HTML Escaping

Abstract: This technical article provides an in-depth exploration of custom tooltip data formatting in Chart.js, focusing on displaying numerical data as percentages. By analyzing API changes across different Chart.js versions, it details two core approaches: using tooltipTemplate/multiTooltipTemplate and tooltips.callbacks.label. Practical code examples demonstrate how to transform raw database values (e.g., -0.17222) into formatted percentages (e.g., -17.22%). The article also discusses the essential distinction between HTML tags as instructions and as textual content, ensuring proper parsing in various environments.

Technical Implementation of Tooltip Data Formatting in Chart.js

In data visualization projects, Chart.js, as a popular JavaScript charting library, often requires displaying raw database data in specific formats to users. This article provides a detailed technical analysis of a common requirement: showing numerical data as formatted percentages in tooltips.

Problem Context and Technical Challenges

Developers retrieve raw data from databases (e.g., -0.17222) and successfully format it as percentages in tables, but in Chart.js bar charts, tooltips still display the raw values. This occurs because Chart.js does not apply data formatting by default, requiring manual configuration of tooltip display formats.

Solutions for Chart.js Versions Before 2.0

For Chart.js versions prior to 2.0, the primary approach uses the tooltipTemplate and multiTooltipTemplate configuration options. These allow developers to define HTML template strings for tooltips, directly controlling data display format.

Core code implementation:

options: {
    tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
    multiTooltipTemplate: "<%= value + ' %' %>"
}

In this code, tooltipTemplate is for single-dataset charts, and multiTooltipTemplate for multi-dataset charts. The template strings use Chart.js's built-in template syntax, where <%= value %> inserts the data value, and the percentage symbol is added via string concatenation.

Important considerations: Datasets should contain only numerical data, with formatting performed entirely in the tooltip template. This method is straightforward but lacks advanced data processing capabilities.

Modern Approach for Chart.js 2.0 and Later

Chart.js 2.0 introduced significant API changes, removing tooltipTemplate and multiTooltipTemplate in favor of the more flexible tooltips.callbacks.label callback system.

Basic implementation structure:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

This callback function receives two parameters, tooltipItem and data, providing access to detailed information about the current data point. By modifying the return value, complex formatting logic can be implemented.

Specific Implementation for Percentage Formatting

To display -0.17222 as -17.22%, implement as follows:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                var value = tooltipItem.yLabel;
                var percentage = (value * 100).toFixed(2) + '%';
                return percentage;
            }
        }
    }
}

This code retrieves the raw value, multiplies by 100 to convert to a percentage, uses toFixed(2) to keep two decimal places, and finally appends the percentage symbol. This approach is more flexible than template strings, allowing any JavaScript logic.

Advanced Formatting Examples

Developers can implement more sophisticated formatting as needed. For example, adding thousand separators and currency symbols:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                var value = Number(tooltipItem.yLabel);
                var formatted = "$" + value.toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
                return formatted;
            }
        }
    }
}

This example demonstrates combining number formatting, string manipulation, and regular expressions for professional financial data display.

Version Compatibility and Best Practices

In real-world projects, consider Chart.js version compatibility:

  1. Chart.js 1.x: Use tooltipTemplate/multiTooltipTemplate
  2. Chart.js 2.x+: Use tooltips.callbacks.label

Recommended best practices:

Essential Principles of HTML Escaping

When writing documentation containing HTML examples, special characters must be handled correctly. For instance, when describing HTML tags as textual content, angle brackets should be escaped: <br> represents a text description of a line break tag, not an actual line break instruction. Similarly, in code examples, print("<T>"); ensures <T> is not parsed as an HTML tag.

This escaping principle ensures correct parsing across various environments, preventing accidental DOM structure corruption. Developers should always distinguish between "HTML tags as instructions" and "HTML descriptions as textual content" when writing technical documentation.

Conclusion and Future Directions

Chart.js's custom tooltip formatting is powerful and flexible, allowing developers to choose appropriate methods based on specific needs. From simple percentage displays to complex financial formatting, Chart.js provides comprehensive solutions. As Chart.js continues to evolve, monitor official documentation for updates and adopt modern APIs for more robust, maintainable code.

Through this technical analysis, developers should grasp the core concepts of Chart.js tooltip formatting, effectively addressing data display formatting requirements in practical projects, thereby enhancing user experience and data readability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.