Chris Go Chris Go - 11 months ago 43
Javascript Question

Chart.js Globally Formatted Number Labels

All I want to do is set a simple Global Option that formats numbers with commas for Y AXIS and Tooltips. I have tried a million examples and I can not get this to work.

Version: Chart.js/2.2.2

I would like to format all numbers with commas for Y axis and tooltip values using a simple global option. The reason why this would be easier using global is that I am generating and dynamically sending in the JSON data and adding more options to that would be a pain, dynamically when all the numbers need to just behave the same.

Here is my working example to help:

What I had to do was edit the JSON object before it was sent to the Chart creation chart = new Chart(ctx, results.graph);. I figured maybe someone else might need this example or close to it.

results.graph.options.scales.yAxes[0].ticks = ({ callback: function (label, index, labels) { return label.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } });

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

Answer Source

You will need to use the callback property for both the yAxes (scroll down until "Tick Configuration") and the tooltip.

To make the integer displayed as you wanted (for instance 10.050,42), here is a simple function in JavaScript, that I use in these callbacks :

function addThousands(num) {
    num += '';
    numSplit = num.split('.');
    x1 = numSplit[0];
    x2 = numSplit.length > 1 ? ',' + numSplit[1] : '';
    var regex = /(\d+)(\d{3})/;
    while (regex.test(x1)) {
        x1 = x1.replace(regex, '$1' + '.' + '$2');
    return x1 + x2;

// 10050.42 -> "10.050,42"
// 42042 -> "42.042"

You can see a full example in this jsFiddle, and here is its result :

enter image description here