我查阅了 Chart.js 文档,但没有找到有关数字格式的任何内容,例如 "#,###.00" 格式下的 1,000.02。
我还进行了一些基本测试,似乎图表不接受非数字文本作为其值。
是否有人找到了一种方法,可以使数值具有千位分隔符和固定的小数位数?我希望坐标轴值和图表中的数值都能够格式化。
我查阅了 Chart.js 文档,但没有找到有关数字格式的任何内容,例如 "#,###.00" 格式下的 1,000.02。
我还进行了一些基本测试,似乎图表不接受非数字文本作为其值。
是否有人找到了一种方法,可以使数值具有千位分隔符和固定的小数位数?我希望坐标轴值和图表中的数值都能够格式化。
将工具提示
放在选项中,像这样:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
}
}
}
Javascript没有内置的数字格式化功能。我发现这个页面上的addCommas function是最简单的解决方案。
然后,你只需要修改你的Chart.defaults.global
中的tooltipTemplate
参数行,例如:
tooltipTemplate: "<%= addCommas(value) %>"
Charts.js会处理剩下的部分。
这里是addCommas
函数:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
在Chart.js v2.5中,我发现现有的解决方案对我没有用。我找到了一个解决方法:
options: {
scales: {
yAxes: [{
ticks: {
callback: function (value) {
return numeral(value).format('$ 0,0')
}
}
}]
}
}
我使用了 numeral.js,但你也可以使用 Yacine 建议的 addCommas 函数,或其他任何东西。
对于使用版本2.5.0的用户,这是@andresgottlieb解决方案的一个增强。通过这个增强,您也可以格式化图表工具提示中的金额,而不仅仅是'yAxes'中的'ticks'。
...
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
callback: function(value, index, values) {
return '$ ' + number_format(value);
}
}
}]
},
tooltips: {
callbacks: {
label: function(tooltipItem, chart){
var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
return datasetLabel + ': $ ' + number_format(tooltipItem.yLabel, 2);
}
}
}
}
这里是我正在使用的number_format()函数:
function number_format(number, decimals, dec_point, thousands_sep) {
// * example: number_format(1234.56, 2, ',', ' ');
// * return: '1 234,56'
number = (number + '').replace(',', '').replace(' ', '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
要将数字格式化为千位分隔符,即3,443,440。您可以在tooltipTemplate中使用toLocaleString()函数。
tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>"
Chart.defaults.global
的tooltipTemplate的值,以格式化该值:tooltipTemplate : function(valueObj) {
return formatNumber(valueObj.value, 2, ',', '.');
}
这里是格式化函数:
function formatNumber(number, decimalsLength, decimalSeparator, thousandSeparator) {
var n = number,
decimalsLength = isNaN(decimalsLength = Math.abs(decimalsLength)) ? 2 : decimalsLength,
decimalSeparator = decimalSeparator == undefined ? "," : decimalSeparator,
thousandSeparator = thousandSeparator == undefined ? "." : thousandSeparator,
sign = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(decimalsLength)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign +
(j ? i.substr(0, j) + thousandSeparator : "") +
i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousandSeparator) +
(decimalsLength ? decimalSeparator + Math.abs(n - i).toFixed(decimalsLength).slice(2) : "");
}
locale
。
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12000, 19000, 3000, 5000, 2000, 3000],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7000, 11000, 5000, 8000, 3000, 7000],
borderColor: 'orange'
}
]
},
options: {
locale: 'en-US'
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("normal").addEventListener("click", () => {
setIntl('nl-NL')
});
document.getElementById("us").addEventListener("click", () => {
setIntl('en-US')
});
const setIntl = (intl) => {
chart.options.locale = intl;
chart.update();
}
<body>
<button id="us">
US formatting of numbers
</button>
<button id="normal">
Normal formatting of numbers
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>