Chart.js tooltip format number with commas

Chart.js V2.0 is a useful javascript charting library. It looks great, has ton of features though it is new enough that there is still some work to find out how to get some relatively simple things done.

In this case I wanted to format the chart’s tooltip. Tooltips are the pop-ups that show when you hover mouse over a bar or line in a chart and show the yAxis value along with any other information you want to include.

By default Chart.js tooltips do not format numbers with commas and there was no simple option to do this.

Instead after some Googling about I found out it required using Chart.js callbacks feature which can be used to format chart elements. Note V1 used a different method that modified tooltip template but that is deprecated in V2.0.

The callback is in the Options’ tooltips section. You put function into the callback that uses regex to insert commas.


callbacks: {
    label: function(tooltipItem, data) {
        return tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
},

This can be done as a global change to all charts in the page or just to a specific chart which is what I used and is shown in the example below.

The result is that the tooltip now has a commas.

chartjs tooltip number comma




2 Thoughts on “Chart.js tooltip format number with commas

  1. Paulo on March 2, 2018 at 8:54 pm said:

    Add this in order show the label name before the value, when you have multiple datasets:

    tooltips: {
    mode: ‘index’,
    label: ‘myLabel’,
    callbacks: {
    label: function(tooltipItem, data) {
    return data.datasets[tooltipItem.datasetIndex].label + ‘: ‘+ tooltipItem.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, “.”);
    }
    }
    }

  2. Gracias por tu aporte me sirvió mucho

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Post Navigation