Wednesday, November 20, 2013

showing percentages with a single decimal point in JavaScript

reshapeData: function(data) {
   var totalRecords = 0;
   data.forEach(function(datum){
      totalRecords = totalRecords + datum.data;
   });
   var reshapedData = [];
   data.forEach(function(datum){
      var description = datum.label;
      if (totalRecords > 0) {
         var percentage = (datum.data/totalRecords)*100;
         if (percentage > 10) {
            description = description + " (" + percentage.toPrecision(3) + "%)";
         } else {
            description = description + " (" + percentage.toPrecision(2) + "%)";
         }
      }
      reshapedData.push({y: datum.data, text: description});
   });
   return reshapedData;
}

No comments:

Post a Comment