Force the ".0" portion of a value to explicitly display for Chart.JS - Javascript Chart.js

Javascript examples for Chart.js:Chart Data

Description

Force the ".0" portion of a value to explicitly display for Chart.JS

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from   w w  w . j  av a  2  s.  c o m
Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
        ctx.fillStyle = '#666';
        chartInstance.data.datasets.forEach(function(dataset) {
           if (dataset.label != "Price Compliant") return;
            for (var i = 0; i < dataset.data.length; i++) {
               ctx.textAlign = "center";
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i] +"%", ((model.x + model.base) / 2 ), model.y + (model.height / 3));
            }
        });
    }
});
var data = {
    labels: [
        "Bix Produce", "Capitol City", "Charlies Portland", "Costa Fruit and Produce", "Get Fresh Sales", "Loffredo East", "Loffredo West", "Paragon", "Pizza Produce",
    ],
    datasets: [{
        label: "Non-Compliant",
        backgroundColor: "rgba(255, 0, 0, 0.5)",
        hoverBackgroundColor: "rgba(255, 0, 0, 1)",
        data: ["1.0", "0.8", "0.6", "1.1", "0.9", "0.5", "0.4", "0.8", "0.3"]
    }, {
        label: "Price Compliant",
        backgroundColor: "rgba(34,139,34,0.5)",
        hoverBackgroundColor: "rgba(34,139,34,1)",
        data: ["99.0", "99.2", "99.4", "98.9", "99.1", "99.5", "99.6", "99.2", "99.7"]
    }]
};
var ctx = document.getElementById("forecastLineChart");
var myChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: data,
    options: {
        scales: {
            yAxes: [{
                stacked: true
            }]
        }
    }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="forecastLineChart" height="200"></canvas>  
   </body>
</html>

Related Tutorials