3

I need to add commas to numbers in a ChartJS graph. Ex. Data points might be 1032.05, 4334.75, 8482.46 and I need it to display as 1,032.05, 4,334.75, 8,482.46.

Here is the link to a development site with current code: http://investingcalculator.azurewebsites.net/

I am currently passing in the values as an array on calculate and since arrays are comma delimitated, I am not sure how to change the data points to have commas.

My calculate code is as follows. Please note that I am using requires:

define(['jquery', 'chartjs'], function ($) {

var investCalc = {

    calculate: function () {

        var currentbalance = $("#currentbalance");
        var interestrate = $("#interestrate");
        var yearscontributing = $("#yearscontributing");
        var monthlycontribution = $("#monthlycontribution");

        var year = [];
        var yearlybalance = [];

        $('#calculate').on('click', function () {

            var P = parseFloat(currentbalance.val());
            var r = parseFloat(interestrate.val());
            var t = parseFloat(yearscontributing.val());
            var add = parseFloat(monthlycontribution.val());
            var addtotal = add * 12;
            if (isNaN(P) || isNaN(r) || isNaN(t) || isNaN(add)) {
                alert('All Inputs Must Be Numbers');
                return;
            }



            // Loop to provide the value per year and push them into an array for consumption by the chart
            for (var i = 0; i < t; i++) {
                // Convert int of interest rate to proper decimal (ex. 8 = .08)
                var actualrate = r / 100;
                var A = (P + addtotal) * (1 + actualrate);
                var P = A;

                // Convert the loop from starting at 0 to print the actual year
                startyear = i + 1;
                actualyear = "Year " + startyear;

                // Format the number output to 2 decimal places
                formattedValue = A.toFixed(2);
                endBalance = P.toFixed(2);

                // Push the values in the array
                year.push(actualyear);
                yearlybalance.push(formattedValue);
            }

            $("#endingbalance").val(endBalance);



            // Bar chart
            var barChartData = {
                labels: year,
                datasets: [
                    {
                        label: "Investing Results",
                        fillColor: "rgba(151,187,205,0.2)",
                        strokeColor: "rgba(151,187,205,1)",
                        pointColor: "rgba(151,187,205,1)",
                        pointStrokeColor: "#fff",
                        pointHighlightFill: "#fff",
                        pointHighlightStroke: "rgba(151,187,205,1)",
                        data: yearlybalance
                    }
                ]
            }

            var ctx = $("#canvas").get(0).getContext("2d");
            // This will get the first returned node in the jQuery collection.
            newBarChart = new Chart(ctx).Bar(barChartData, {
                responsive: true

            });
            $('#calculate').hide();


            var chartjs = Chart.noConflict();

        });

        // Reset values and page
        $('#reset').on( 'click',  function  () {

            location.reload();

        });
    }
};

 return investCalc;

  });
Kode
  • 3,073
  • 18
  • 74
  • 140

2 Answers2

2

I recommend this regex in a replace function to add commas in. Like this:

endBalance = P.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")

Howard Renollet
  • 4,609
  • 1
  • 24
  • 31
  • What about each data point on the Chart. The variable is yearlybalance – Kode Nov 07 '14 at 20:15
  • I just gave that as an example. You can use it on any string. `yearlybalance.push(formattedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ","))` – Howard Renollet Nov 07 '14 at 20:17
  • Works great for the endBalance, but doesn't work for the yearlybalance as that is an array of values (ex. "yearlybalance1, yearlybalance2, etc.) Since it has commas I believe it is getting confused and not rendering the chart. – Kode Nov 07 '14 at 21:32
  • 1
    Ok, I see the problem and it appears as though Chart.js doesn't support formatting of data 'out of the box' like HighCharts does, which I find very odd. Give me a few days to dig into the Chart.js source and I'll see if I can write an extension that can handle the formatting for you. I'm sure it would be useful to many others as well. I used Chart.js for a little while but it wasn't flexible enough for my needs so we moved to HighCharts. – Howard Renollet Nov 07 '14 at 21:47
  • Thanks Howard! I will check into HighCharts as well. – Kode Nov 07 '14 at 22:15
  • Odd issue. Do you know why the regex replace doesn't work in a mobile browser? It is working fine in a desktop browser, but anything that requires a comma is not displayed (it shows as 0) in an iPhone – Kode Nov 07 '14 at 22:45
  • Fixed the mobile issue by switching the output field to a text value. – Kode Nov 08 '14 at 02:29
  • 2
    Ok, this is really strange. I've spent a couple hours on this and their method of drawing the tooltips is very strange to me. There's no way to affect the tooltip text directly. Every time you hover over a point and the tooltip is displayed, the entire chart is re-drawn. Also, they are using a very odd micro template that has no documentation that I can find. I'm still working on it, but it's not looking promising as far as adding commas. I did find out how to add in other characters, like units of measure or dollar signs, etc... but not a comma for the thousands separator. – Howard Renollet Nov 10 '14 at 20:16
  • Wow, that is incredible effort. Thanks for your help. At this point, maybe we need to push the ChartJS contributors to make an update. – Kode Nov 11 '14 at 17:59
2

You can add "multiTooltipTemplate" or "tooltipTemplate" to your chart options. Below is a copy of your code with "multiTooltipTemplate" added as an option. I have a small function that I use to add commas, I've included that below also.

newBarChart = new Chart(ctx).Bar(barChartData, {
                responsive: true,
                multiTooltipTemplate: "$<%=addCommas(value)%>"
            });

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;

}

I hope this helps, we use it for our tooltips in Chart.js and it works great.

tstaheli
  • 546
  • 4
  • 5