[Chartjs]-How to commaize the data values provided to a chart in Chart.JS?

2👍

var formatter = new Intl.NumberFormat();
var data = {labels: ["..."], datasets: [{data: [2755, 2256, 1637, 1608, 1603, 1433, 1207, 1076, 1056, 1048], backgroundColor: ["..."]}]};

data.datasets.forEach(function (dataset) {
    dataset.data = dataset.data.map(formatter.format);
});

// Output: {"labels":["..."],"datasets":[{"data":["2,755","2,256","1,637","1,608","1,603","1,433","1,207","1,076","1,056","1,048"],"backgroundColor":["..."]}]}
console.log(data);

Another way of doing it is implementing a label callback:

...

var formatter = new Intl.NumberFormat();

var optionsPie = {
    responsive: true,
    scaleBeginAtZero: true,
    tooltips: {
        callbacks: {
            label: function (tooltipItem, data) {
                return data.labels[tooltipItem.index] + ": " +
                    formatter.format(data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]);
            }
        }
    }
};

...

var top10PieChart = new Chart(ctx, {
    type: 'pie',
    data: data,
    options: optionsPie
});

...

1👍

Try something like this –

datasets: [
{
    labels: [addCommas(2755), addCommas(2256), addCommas(1637), addCommas(1608)],
    data: [2755, 2256, 1637, 1608],
    . . .

1👍

All that is really needed is the first line of felipeptcho’s code, namely:

var formatter = new Intl.NumberFormat("en-US");

…and then somewhere after that this:

data.datasets.forEach(function(dataset) {
    dataset.data = dataset.data.map(formatter.format);
});

Even when I had that last code after a block of other code declaring datasets and data for a different chart, it worked on the chart/data under discussion.

That’s all! It simply works. How, I don’t quite grok, but it does, so I’m satisfied.

Leave a comment