score:26
There is no built-in functionality for number formatting in Javascript. I found the easiest solution to be the addCommas function on this page.
Then you just have to modify your tooltipTemplate
parameter line from your Chart.defaults.global
to something like this:
tooltipTemplate: "<%= addCommas(value) %>"
Charts.js will take care of the rest.
Here's the addCommas
function:
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;
}
score:1
You can use the locale
option to tell chart.js how to format numbers for everything from axes to the tooltip:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12000, 19000, 3000, 5000, 2000, 3000],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7000, 11000, 5000, 8000, 3000, 7000],
borderColor: 'orange'
}
]
},
options: {
locale: 'en-US'
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("normal").addEventListener("click", () => {
setIntl('nl-NL')
});
document.getElementById("us").addEventListener("click", () => {
setIntl('en-US')
});
const setIntl = (intl) => {
chart.options.locale = intl;
chart.update();
}
<body>
<button id="us">
US formatting of numbers
</button>
<button id="normal">
Normal formatting of numbers
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
score:10
You can set up the tooltipTemplate value from your Chart.defaults.global
with a function to format the value:
tooltipTemplate : function(valueObj) {
return formatNumber(valueObj.value, 2, ',', '.');
}
Here's the format function:
function formatNumber(number, decimalsLength, decimalSeparator, thousandSeparator) {
var n = number,
decimalsLength = isNaN(decimalsLength = Math.abs(decimalsLength)) ? 2 : decimalsLength,
decimalSeparator = decimalSeparator == undefined ? "," : decimalSeparator,
thousandSeparator = thousandSeparator == undefined ? "." : thousandSeparator,
sign = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(decimalsLength)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign +
(j ? i.substr(0, j) + thousandSeparator : "") +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousandSeparator) +
(decimalsLength ? decimalSeparator + Math.abs(n - i).toFixed(decimalsLength).slice(2) : "");
}
score:14
For those using Version: 2.5.0, here is an enhancement for @andresgottlieb solution. With this, you can also format the amounts in tooltips of the chart, not only the 'ticks' in the 'yAxes'
...
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
callback: function(value, index, values) {
return '$ ' + number_format(value);
}
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItem, chart){
var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': $ ' + number_format(tooltipItem.yLabel, 2);
}
}
}
}
Here is the number_format() function what I am using:
function number_format(number, decimals, dec_point, thousands_sep) {
// * example: number_format(1234.56, 2, ',', ' ');
// * return: '1 234,56'
number = (number + '').replace(',', '').replace(' ', '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
score:16
For numbers to be comma formatted i.e 3,443,440 . You can just use toLocaleString() function in the tooltipTemplate .
tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>"
score:22
Existing solutions did not to work for me in Chart.js v2.5. The solution I found:
options: {
scales: {
yAxes: [{
ticks: {
callback: function (value) {
return numeral(value).format('$ 0,0')
}
}
}]
}
}
I used numeral.js, but you can use the addCommas function proposed by Yacine, or anything else.
score:30
Put tooltips
in 'option' like this:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
}
}
}
Reference from https://github.com/chartjs/Chart.js/pull/160.
Source: stackoverflow.com
Related Query
- Limit labels number on Chart.js line chart
- Chart.js number format
- Display a limited number of labels only on X-Axis of Line Chart using Chart.js
- Line chart with large number of labels on X axis
- Chartjs - data format for bar chart with multi-level x-axes
- Chart.js number Y-AXIS label format for many decimal places
- Chart.js: summing number of items in active/shown datasets on yAxes of pie chart
- Number value format with comma and two decimal points
- ChartsJS make number in middle for only one chart
- Chart JS Dynamic number of datasets
- Set minimum number of steps in line chart
- How to export a chart in Excel and PDF format using Chart.js
- How to plot chart from external JSON and format X-AXIS to show time using Chart.JS?
- How to reduce the number of points shown on line chartjs chart with a large dataset?
- ChartJS 3.0 - Number format
- Inverting X axis number labels in chart.js scatter chart
- I am using chart.js I sent my time values throw my api as timestamp know i need to show them in the chart as date format
- ChartJS 2 - Adding data to chart breaks after X number of items added
- How to make money format in chart js in javascript
- Chart won't draw. Returning a string value not a Number value - Meteor - Chartjs
- what is wrong with my code ? java script chart position
- How to print a chart rendered by code
- Chart.js - Line Chart format data to Lacs/Crores
- Can't draw pie chart using chartjs - TypeError: Cannot create property '_meta' on number '16'
- How to set the number of of rows in a line chart in chart.js?
- VueJS + Chartjs - Chart only renders after code change
- How do I destroy/update Chart Data in this chart.js code example?
- How to push a variable number of datasets to a chart data, without the _observer "magic"_ (using vuecharts.js)?
- Chart js adding number
- getting additional value fields from data source for dx.chartjs doughnut chart
More Query from same tag
- Doughnut chart from Chart.js, custom legend and call of original handler not works as expected
- How to add index labels(on top of bar charts) in Chart.js
- HTML Canvas Fill Area Under Line
- chart.js doughnut legend in the chart
- Chart JS Layered Vertical Bar Chart
- ChartJS click on bar and change it's background color
- Chart.js (v3) Doughnut with rounded edges, but not everywhere
- Display JSON data in react-chartjs-2
- Alter values of xAxis in chartjs
- Render chartjs and export image to data not in the DOM
- Cannot read property 'labels' of undefined
- How to use chart.js to plot line chart with x axis as time stamp in seconds
- How to change bar color acording to label value in chartjs
- Why Chart.js's tooltip appears in wrong position when mouse hover?
- How to skip labels on x-axes?
- Chart JS - Disable lines and Uncheck legends by default
- cannot read property 'yyyx' of undefined
- Adding a second custom tooltip for charts in ChartsJs
- Drilldown on barchart using CHARTJS Devexpress
- Unable to hide X-Axis in horizontal stacked chart.js
- Chart in other module
- set scroll on bar chart in chartjs
- jQuery convert hex to rgba
- How to display half hour ticks on x-axes
- Trying to update background color on chart.js
- Reduce size of chart within the canvas
- Chart js each label for each data
- chartjs: need color bars near yAxis scale
- Chart.js how to get Combined Bar and line charts?
- ChartJS legend background color while using point styles