0

I have this code:

var store = [{ Name:"Item 1", Total:18.73424242 },
               { Name:"Item 2", Total:7.34311 },
               { Name:"Item 3", Total:3.1235535},
               { Name:"Item 4", Total:12.763574}];
  

  var colorScale = new Plottable.Scales.Color();
  var legend = new Plottable.Components.Legend(colorScale);

  var pie = new Plottable.Plots.Pie()
  .attr("fill", function(d){ return d.Name; }, colorScale)
  .addDataset(new Plottable.Dataset(store))
  .sectorValue(function(d){ return d.Total; } )
  .labelsEnabled(true);
 
    
  new Plottable.Components.Table([[pie, legend]]).renderTo("#chart");
<link href="https://rawgithub.com/palantir/plottable/develop/plottable.css" rel="stylesheet"/>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://rawgithub.com/palantir/plottable/develop/plottable.js"></script>
<div id="container">
  <svg id="chart" width="350" height="350"></svg>
</div>

How can I format the values to 2 digit decimals: 18.73, 7.34, 3.12, etc2 inside the pie chart?

neversaint
  • 60,904
  • 137
  • 310
  • 477
  • Where are the totals coming from? For example, in this `{ Name:"Item 4", Total:12.763574}` where is `12.763574` coming from? Is is hardcoded in? – Nick Zuber Dec 07 '15 at 01:50

1 Answers1

2

Use d3.format() or .toFixed().

 var pie = new Plottable.Plots.Pie()   
 .attr("fill", function(d){return d.Name; }, colorScale)   
 .addDataset(new Plottable.Dataset(store))
 .sectorValue(function(d){ return +d3.format('0.2f')(d.Total);})   
  //.sectorValue(function(d){ return +d.Total.toFixed(2);})   //works too
 .labelsEnabled(true);

Here's a gist.

jwildfire
  • 68
  • 5
  • nothing at all :) `.sectorValue(function(d){ return +d.Total.toFixed(2);})` should work too. – jwildfire Dec 07 '15 at 02:08
  • @jwildfire: Can you give snippet example where toFixed(2) work? On my snippet it failed. – neversaint Dec 07 '15 at 02:10
  • 1
    @mkoryak it rounds as well. `d3.format('0.2f')(10.236) = "10.24"` – jwildfire Dec 07 '15 at 02:21
  • @jwildfire: ok it works. I need to add `+` inside. What's the meaning of that plus sign? – neversaint Dec 07 '15 at 02:22
  • 1
    It's shorthand to convert a string to a number. See [this](http://stackoverflow.com/questions/12862624/whats-the-fastest-way-to-convert-string-to-number-in-javascript) response for details – jwildfire Dec 07 '15 at 02:25
  • @jwildfire: Thanks. BTW care to look at my other question? http://stackoverflow.com/questions/34125268/how-to-enable-qtip2-in-piechart-made-by-plottable-js-d3-js – neversaint Dec 07 '15 at 02:30