这告诉我如何将数据值添加到图表JS - Adding data values to chart JS
现在我想为这些值添加逗号,例如5,000 6,000而不是5000 6000
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx).Line(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.points.forEach(function (points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
});
var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y - 5);
});
})
}
});
答案 0 :(得分:1)
不幸的是,在JavaScript中没有针对此答案的内置跨浏览器解决方案:
How to print a number with commas as thousands separators in JavaScript
您可以使用小提琴中包含的numbersWithCommas
:
var numberWithCommas = function(x) {
return x
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
只需在bar.value = numberWithCommas(bar.value);
函数
this.datasets.forEach
即可
在将数字附加到图表之前,这将使用逗号格式化数字。