Chart.js number format

Ronald picture Ronald · Sep 17, 2014 · Viewed 53.8k times · Source

I went over the Chart.js documentation and did not find anything on number formatting ie) 1,000.02 from number format "#,###.00"

I also did some basic tests and it seems charts do not accept non-numeric text for its values

Has anyone found a way to get values formatted to have thousands separator and a fixed number of decimal places? I would like to have the axis values and values in the chart formatted.

Answer

Yacine B picture Yacine B · Oct 25, 2014

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