Chart.js Number Format


Answer :

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

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.


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.


Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Change The Font Size Of Visual Studio Solution Explorer