[Chartjs]-Chart.js number format

29👍

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;
}

34👍

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.

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.

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() %>”

16👍

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);
}

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) : "");
}

2👍

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>

Leave a comment