Home > Blockchain >  d3 - Round number from nest() and sum()
d3 - Round number from nest() and sum()

Time:09-18

I am using nest() and sum() in d3 and need to round the resulting number to two decimal places.

How should I do that?

  var categories = d3.nest()
    .key(function(d){return d.Category})
    .rollup(function(leaves){
      return d3.sum(leaves, function(d) {return d3.sum(d3.values(d))});
    })
    .entries(data);

and the result is displayed via:

 var sum=0;

  columns = svg.append("g")
    .selectAll("text").data(categories)
    .enter().append("text")
    .attr("x", function(d){
      return x(d.key)   x.rangeBand()/2
    })
    .attr("y", function (d) {
      return y(d.values);
    })
    .attr("dy", "-0.7em")
    .attr('style', 'font-size:11px')
    .text( function (d){
      return d.values   '%';
    })
    .style({fill: 'black', "text-anchor": "middle"});

CodePudding user response:

You can use javascript's Math.round(). The only issue is that it rounds to the nearest integer, so if you want to round to 2d.p., you would multiply the number by 100, round it to the nearest integer, then divide it back to get the decimal correctly.

columns = svg.append("g")
    .selectAll("text").data(categories)
    .enter().append("text")
    .attr("x", function(d){
      return x(d.key)   x.rangeBand()/2
    })
    .attr("y", function (d) {
      return y(d.values);
    })
    .attr("dy", "-0.7em")
    .attr('style', 'font-size:11px')
    .text( function (d){
      return Math.round(d.values * 100) / 100   '%';
    })
    .style({fill: 'black', "text-anchor": "middle"});

CodePudding user response:

I found the built in formatting function in d3:

https://github.com/d3/d3-format

Using this worked for me.

return d3.format(".2f")(d.values)   '%';
  • Related