gpt4 book ai didi

javascript - 如何在 Plottable.js Piechart 标签中将数字精度格式化为两位小数

转载 作者:行者123 更新时间:2023-12-02 15:20:35 26 4
gpt4 key购买 nike

我有这个代码:

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>

如何将饼图中的值格式化为 2 位小数:18.73、7.34、3.12、etc2

最佳答案

使用d3.format().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);

这是一个gist .

关于javascript - 如何在 Plottable.js Piechart 标签中将数字精度格式化为两位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com