javascriptchartsformattingnumber-formattingchart.js

Chart.js number format


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.


Solution

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