Javascript Chart.js 数字格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25880767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:59:57  来源:igfitidea点击:

Chart.js number format

javascriptchartsformattingnumber-formattingchart.js

提问by Ronald

I went over the Chart.js documentationand 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.

有没有人找到一种方法来获取格式化为具有千位分隔符和固定小数位数的值?我想格式化图表中的轴值和值。

采纳答案by Yacine B

There is no built-in functionality for number formatting in Javascript. I found the easiest solution to be the addCommas function on this page.

Javascript 中没有用于数字格式的内置功能。我发现最简单的解决方案是此页面上addCommas 函数

Then you just have to modify your tooltipTemplateparameter line from your Chart.defaults.globalto something like this:

然后你只需要修改你的tooltipTemplate参数行,Chart.defaults.global如下所示:

tooltipTemplate: "<%= addCommas(value) %>"

Charts.js will take care of the rest.

Charts.js 将负责其余的工作。

Here's the addCommasfunction:

这是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, '' + ',' + '');
    }
    return x1 + x2;
}

回答by Sumanth

For numbers to be comma formatted i.e 3,443,440 . You can just use toLocaleString() function in the tooltipTemplate .

对于逗号格式的数字,即 3,443,440 。您可以在 tooltipTemplate 中使用 toLocaleString() 函数。

tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>"

tooltipTemplate: "<%= datasetLabel %> - <%= value.toLocaleString() %>"

回答by andresgottlieb

Existing solutions did not to work for me in Chart.js v2.5. The solution I found:

现有的解决方案在 Chart.js v2.5 中对我不起作用。我找到的解决方案:

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 函数或其他任何函数。

回答by herohat

For those using Version: 2.5.0, here is an enhancement for @andresgottlieb solution. With this, you can also format the amounts in tooltips of the chart, not only the 'ticks' in the 'yAxes'

对于使用版本:2.5.0 的用户,这里是@andresgottlieb 解决方案的增强功能。有了这个,您还可以格式化图表工具提示中的金额,而不仅仅是“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);
}

回答by Irfan Hafid Nugroho

Put tooltipsin '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 的参考。

回答by Fran Herrero

You can set up the tooltipTemplate value from your Chart.defaults.globalwith a function to formatting the value:

您可以Chart.defaults.global使用函数设置 tooltipTemplate 值以格式化该值:

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, "" + thousandSeparator) +
           (decimalsLength ? decimalSeparator + Math.abs(n - i).toFixed(decimalsLength).slice(2) : "");
}