B. Clay Shannon B. Clay Shannon - 1 month ago 9
Javascript Question

How can I give the automatically generated y-axis values on bar charts in Chart.JS commas?

I am adding commas to my data values like so:

ctx.fillText(addCommas(dataset.data[i]), model.x, y_pos);
. . .
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}


...but the "contextual" values on the y axis of the bar chart are "raw" (no commas) as can be seen here:

enter image description here

How can I get those values to be more human-friendly, too, by adding commas so as to read:

1,900,000
1,800,000
1,700,000
1,600,000
1,500,000


?

Answer

Using your hand-made addCommas function should do the trick :

options: {
    scales: {
        yAxes: [{
            ticks: {
                userCallback: function(item) {
                    return addCommas(item);
                },
            }
        }]
    }
}
Comments