Tom Rudge
Tom Rudge

Reputation: 3272

Adding decimal points to data values chartJS

This told me how to add data values to chart JS - Adding data values to chart JS

Now I want to add commas to these values e.g 5,000 6,000 instead of 5000 6000

JSFiddle for data values code

            var chartData = {
                labels: ["January", "February", "March", "April", "May", "June"],
                datasets: [
                    {
                        fillColor: "#79D1CF",
                        strokeColor: "#79D1CF",
                        data: [60, 80, 81, 56, 55, 40]
                    }
                ]
            };

            var ctx = document.getElementById("myChart1").getContext("2d");
            var myLine = new Chart(ctx).Line(chartData, {
                showTooltips: false,
                onAnimationComplete: function () {

                    var ctx = this.chart.ctx;
                    ctx.font = this.scale.font;
                    ctx.fillStyle = this.scale.textColor
                    ctx.textAlign = "center";
                    ctx.textBaseline = "bottom";

                    this.datasets.forEach(function (dataset) {
                        dataset.points.forEach(function (points) {
                            ctx.fillText(points.value, points.x, points.y - 10);
                        });
                    })
                }
            });

            var ctx = document.getElementById("myChart2").getContext("2d");
            var myBar = new Chart(ctx).Bar(chartData, {
                showTooltips: false,
                onAnimationComplete: function () {

                    var ctx = this.chart.ctx;
                    ctx.font = this.scale.font;
                    ctx.fillStyle = this.scale.textColor
                    ctx.textAlign = "center";
                    ctx.textBaseline = "bottom";

                    this.datasets.forEach(function (dataset) {
                        dataset.bars.forEach(function (bar) {
                            ctx.fillText(bar.value, bar.x, bar.y - 5);
                        });
                    })
                }
            });

Upvotes: 1

Views: 4039

Answers (1)

Matt O'Connell
Matt O'Connell

Reputation: 287

Unfortunately, there's no built-in cross browser solution for this answer in JavaScript:

How to print a number with commas as thousands separators in JavaScript

You can use the numbersWithCommas you included in your fiddle:

var numberWithCommas = function(x) {
    return x
        .toString()
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

Just include bar.value = numberWithCommas(bar.value); within the this.datasets.forEach function

This will format the numbers with commas prior to appending them to the chart.

Upvotes: 1

Related Questions