[英]Chart.js number format
I went over the Chart.js documentation and did not find anything on number formatting ie) 1,000.02 from number format "#,###.00"我浏览了Chart.js 文档,没有找到任何关于数字格式的内容,即)1,000.02 来自数字格式“#,###.00”
I also did some basic tests and it seems charts do not accept non-numeric text for its values我还做了一些基本的测试,似乎图表不接受其值的非数字文本
Has anyone found a way to get values formatted to have thousands separator and a fixed number of decimal places?有没有人找到一种方法来获取格式化为具有千位分隔符和固定小数位数的值? I would like to have the axis values and values in the chart formatted.
我想格式化图表中的轴值和值。
Put tooltips
in 'option' like this:将
tooltips
放在“选项”中,如下所示:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
}
}
}
Reference from https://github.com/chartjs/Chart.js/pull/160 .来自https://github.com/chartjs/Chart.js/pull/160 的参考。
There is no built-in functionality for number formatting in Javascript. Javascript 中没有数字格式的内置功能。 I found the easiest solution to be the addCommas function on this page .
我发现最简单的解决方案是此页面上的addCommas 函数。
Then you just have to modify your tooltipTemplate
parameter line from your Chart.defaults.global
to something like this:然后,您只需将您的
tooltipTemplate
参数行从Chart.defaults.global
修改为如下所示:
tooltipTemplate: "<%= addCommas(value) %>"
Charts.js will take care of the rest. Charts.js 将负责其余的工作。
Here's the addCommas
function:这是
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;
}
Existing solutions did not to work for me in Chart.js v2.5.现有的解决方案在 Chart.js v2.5 中对我不起作用。 The solution I found:
我找到的解决方案:
options: {
scales: {
yAxes: [{
ticks: {
callback: function (value) {
return numeral(value).format('$ 0,0')
}
}
}]
}
}
I used numeral.js , but you can use the addCommas function proposed by Yacine, or anything else.我使用了numeric.js ,但您可以使用 Yacine 提出的 addCommas 函数或其他任何函数。
For numbers to be comma formatted ie 3,443,440 .对于逗号格式的数字,即 3,443,440 。 You can just use toLocaleString() function in the tooltipTemplate .
您可以在 tooltipTemplate 中使用 toLocaleString() 函数。
tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>" tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>"
For those using Version: 2.5.0, here is an enhancement for @andresgottlieb solution.对于使用版本:2.5.0 的用户,这里是@andresgottlieb 解决方案的增强功能。 With this, you can also format the amounts in tooltips of the chart, not only the 'ticks' in the 'yAxes'
有了这个,您还可以格式化图表工具提示中的金额,而不仅仅是“yAxes”中的“刻度”
...
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);
}
}
}
}
Here is the number_format() function what I am using:这是我正在使用的 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);
}
You can set up the tooltipTemplate value from your Chart.defaults.global
with a function to formatting the value:您可以从建立tooltipTemplate值
Chart.defaults.global
用一个函数来格式化值:
tooltipTemplate : function(valueObj) {
return formatNumber(valueObj.value, 2, ',', '.');
}
Here's the format function:这是格式函数:
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) : "");
}
You can use the locale
option to tell chart.js how to format numbers for everything from axes to the tooltip:您可以使用
locale
选项来告诉 chart.js 如何格式化从轴到工具提示的所有内容的数字:
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.