[Chartjs]-Chart.js Globally Formatted Number Labels

4👍

After talking to the developer I have a really nice global method for setting y axis and tooltip number formatting. I hope this can help someone else too!

You can definitely use global options to control that.

For instance, here’s how you would update so that all linear scales (the default Y axis) will format using dollar signs and nice numbers

Chart.scaleService.updateScaleDefaults('linear', {
  ticks: {
    callback: function(tick) {
      return '$' + tick.toLocaleString();
    }
  }
});

Here’s how you could also do the same for a tooltip

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data) {
  var dataset = data.datasets[tooltipItem.datasetIndex];
  var datasetLabel = dataset.label || '';
  return datasetLabel + ": $" + dataset.data[tooltipItem.index].toLocaleString();
};

Then I asked about including simple flags for formatting within the axes and dataset settings:

I’ve hesitated to push to include these in the core because there are so many different options and trying to support each and every one would dramatically increase the size of the already large library. It may make sense to encourage someone to create a library of formatters that essentially automates the creation of these functions to speed up development.

References:

https://github.com/chartjs/Chart.js/issues/3294#issuecomment-246532871
https://jsfiddle.net/ChrisGo/k4Lxncvm/

Leave a comment