Charts.js Formatting Y Axis with both Currency and Thousands Separator
I'm new to chart.js, but here's what I had to do to make Billy Moon's answer work with the latest version 2.1.6.
var data = {
labels: ["12 AM", "1 AM", "2 AM", "3 AM", "4 AM", "5 AM", "6 AM", "7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 PM", "1 PM", "2 PM", "3 PM", "4 PM", "5 PM", "6 PM", "7 PM", "8 PM", "9 PM", "10 PM", "11 PM"],
datasets: [
{
label: "Sales $",
lineTension: 0,
backgroundColor: "rgba(143,199,232,0.2)",
borderColor: "rgba(108,108,108,1)",
borderWidth: 1,
pointBackgroundColor: "#535353",
data: [65, 59, 80, 81, 56, 55, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40]
}
]
};
//var myChart =
new Chart(document.getElementById('sales-summary-today'), {
type: 'line',
data: data,
options: {
animation: false,
legend: {display: false},
maintainAspectRatio: false,
responsive: true,
responsiveAnimationDuration: 0,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if(parseInt(value) >= 1000){
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
}
});
Again, credit goes to Billy Moon's Answer for the label formatting function.
I'm mostly summarizing what others have mentioned, but I think the cleanest solution to this exact (and frequently encountered) question is to utilize the toLocaleString
method with USD currency formatting:
return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
This works in all modern browsers. The Mozilla documentation for toLocaleString
lists specific browser compatibility and options for other locales, currencies, and formatting types (e.g. percentages).
Note Chart.js Version 2+ (released in April 2016) requires using the callback
method for advanced tick formatting:
var chartInstance = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
callback: function(value, index, values) {
return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
}
}
}]
}
}
});
The syntax if you are using Chart.js Version 1.X would be:
var myLineChart = new Chart(ctx).Line(data, options);
var data = {
...
}
var options = {
scaleLabel: function(label) {
return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
}
Credit to Perry Tew for referencing the syntax change, and to mfink for the idea to use toLocaleString
.