Jake Lam
Jake Lam

Reputation: 3452

rounding value in google chart

I'm using google chart and when doing with very accurate decimal number, GG chart tends to round it to 3 decimal number

You can see it this example :

      google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Age', 'Weight'],
      [ 8,      3.535778],
      [ 4,      5.5],
      [ 11,     14],
      [ 4,      5],
      [ 3,      3.535678],
      [ 6.5,    7]
    ]);

    var options = {
      title: 'Age vs. Weight comparison',
      hAxis: {title: 'Age', minValue: 0, maxValue: 15},
      vAxis: {title: 'Weight', minValue: 0, maxValue: 15},
      legend: 'none'
    };

    var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

    chart.draw(data, options);
  }

https://jsfiddle.net/00a1sut0/2/

In the data , there are 2 number which values are 3.535778 and 3.535678 and GG chart marks it all as 3.536

I want to show the correct decimal number

Anyone with any idea ??

Upvotes: 1

Views: 2018

Answers (1)

Pirate X
Pirate X

Reputation: 3093

Use NumberFormat to show exact values or define pattern for values

Add this bit after the datatable creation

var NumberFormat = new google.visualization.NumberFormat(
//You can explore various type of patterns in Documentation
{pattern:'##.#######'}
);
NumberFormat.format(data, 1);

NumberFormat accepts data table and the column which is supposed to have the pattern format(dataTable, columnIndex)

Overall Code

  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Age', 'Weight'],
      [ 8,      3.535778],
      [ 4,      5.5],
      [ 11,     14],
      [ 4,      5],
      [ 3,      3.535678],
      [ 6.5,    7]
    ]);

   var NumberFormat = new google.visualization.NumberFormat(
   //You can explore various type of patterns in Documentation
   {pattern:'##.#######'}
   );
   NumberFormat.format(data, 1); // Apply formatter to second column

    var options = {
      title: 'Age vs. Weight comparison',
      hAxis: {title: 'Age', minValue: 0, maxValue: 15},
      vAxis: {title: 'Weight', minValue: 0, maxValue: 15},
      legend: 'none'
    };

    var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));

    chart.draw(data, options);
  }

See the demo here - JSFiddle

enter image description here

Upvotes: 1

Related Questions