Alex
Alex

Reputation: 104

Setting floating points in google graph charts

I want to assign values such as 137.55 to the "number" type column in google chart and then plot it. Anytime I assign the floating number, It throws this exception :

Uncaught Error: Type mismatch. Value 32.03 does not match type number in column index 1 

My code is something like this :

      var data = new google.visualization.DataTable();

   data.addColumn('number','Loop');
   data.addColumn('number','ReqSec');
   var myTicks = new Array();

   var formatter = new google.visualization.NumberFormat({
       fractionDigits: 2
    });

   for (var i=0;i<arr.length;i++){
        myVal = $.trim(arr[i][10]);
        myVal = parseFloat(Math.round(myVal * 100) / 100).toFixed(2);
        data.addRow([parseInt(i), myVal]);
        myTicks[i] = i;
   }

   formatter.format(data, 1);

  // Create and draw the visualization.
  new google.visualization.AreaChart(document.getElementById('visualization')).
      draw(data, {curveType: "function",
                  width: 700, height: 400,
                  vAxis: {title: 'Throughput'},
                  hAxis: {title: 'Loop', ticks: myTicks}}
          );

I tried to use formatter, but I guess it's not for floating point data type insertion. any advice or solution ?

Upvotes: 3

Views: 11586

Answers (1)

asgallant
asgallant

Reputation: 26340

This is your problem:

myVal = parseFloat(Math.round(myVal * 100) / 100).toFixed(2);

The return value of the toFixed method is a string, not a number. Using Math.round(myVal * 100) / 100 will give you a floating point number with 2 decimal precision as is; you don't need to call toFixed on it. Also, calling parseFloat on a number is rather pointless - you should call it on the string value you are getting from your array. And third, calling parseInt(i) is also pointless, since i is already as much of an integer as it is going to get (technically, all numbers in javascript are floating point). Try this instead:

for (var i=0;i<arr.length;i++){
    myVal = parseFloat($.trim(arr[i][10]));
    myVal = Math.round(myVal * 100) / 100;
    data.addRow([i, myVal]);
    myTicks[i] = i;
}

That will parse the string as a float, then trim it to a precision of 2 decimal places. If you are interested in charting the data with the precision given by the data in your array, but want to trim the value shown in the tooltips to 2 decimal places, then you can do this instead:

for (var i=0;i<arr.length;i++){
    myVal = parseFloat($.trim(arr[i][10]));
    data.addRow([i, {v: myVal, f: myval.toFixed(2)}]);
    myTicks[i] = i;
}

Upvotes: 8

Related Questions