Javascript Charts.js 使用货币和千位分隔符格式化 Y 轴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28523394/
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-23 01:55:59  来源:igfitidea点击:

Charts.js Formatting Y Axis with both Currency and Thousands Separator

javascriptfunctionchart.js

提问by NickyTheWrench

I'm using Charts.js to show a graph on my site. Currently, the label shows as a long string of numbers (i.e 123456). I want it to show as currency with thousands separator: (i.e $123,456)

我正在使用 Charts.js 在我的网站上显示图表。目前,标签显示为一长串数字(即 123456)。我希望它显示为带有千位分隔符的货币:(即 $123,456)

I'm using the scaleLabel option to put a $ USD symbol before the value:

我正在使用 scaleLabel 选项在值之前放置一个 $ USD 符号:

scaleLabel: "<%= ' $' + Number(value)%>"

and a function to insert the comma separator:

和一个插入逗号分隔符的函数:

function(label){return label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}

I just do not know how to use these together to get what I want.

我只是不知道如何将这些一起使用来获得我想要的。

Here is the fiddle: http://jsfiddle.net/vy0yhd6m/79/

这是小提琴:http: //jsfiddle.net/vy0yhd6m/79/

(please keep in mind that currently the graph will only work if you remove one of those two pieces of JavaScript cited above)

(请记住,目前该图表只有在您删除上面引用的那两个 JavaScript 片段之一时才能工作)

Thank you for any and all help.

感谢您的任何帮助。

采纳答案by Billy Moon

You should be able to include currency prefix in composition of label inside function...

您应该能够在函数内部的标签组合中包含货币前缀...

var options = {
    animation: false,
    scaleLabel:
    function(label){return  '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}
};

http://jsfiddle.net/vy0yhd6m/80/

http://jsfiddle.net/vy0yhd6m/80/

回答by Perry Tew

I'm new to chart.js, but here's what I had to do to make Billy Moon's answer work with the latest version 2.1.6.

我是 chart.js 的新手,但这是我必须做的才能使 Billy Moon 的答案适用于最新版本 2.1.6。

  var data = {
    labels: ["12 AM", "1 AM", "2 AM", "3 AM", "4 AM", "5 AM", "6 AM", "7 AM", "8 AM", "9 AM", "10 AM", "11 AM", "12 PM", "1 PM", "2 PM", "3 PM", "4 PM", "5 PM", "6 PM", "7 PM", "8 PM", "9 PM", "10 PM", "11 PM"],
    datasets: [
      {
        label: "Sales $",
        lineTension: 0,
        backgroundColor: "rgba(143,199,232,0.2)",
        borderColor: "rgba(108,108,108,1)",
        borderWidth: 1,
        pointBackgroundColor: "#535353",
        data: [65, 59, 80, 81, 56, 55, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40, 59, 80, 81, 56, 55, 40]
      }
    ]
  };

  //var myChart =
  new Chart(document.getElementById('sales-summary-today'), {
    type: 'line',
    data: data,
    options: {
      animation: false,
      legend: {display: false},
      maintainAspectRatio: false,
      responsive: true,
      responsiveAnimationDuration: 0,
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: true,
            callback: function(value, index, values) {
              if(parseInt(value) >= 1000){
                return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              } else {
                return '$' + value;
              }
            }
          }
        }]
      }
    }
  });

Again, credit goes to Billy Moon's Answer for the label formatting function.

再次感谢 Billy Moon 对标签格式化功能的回答。

回答by AJ Arora

I'm mostly summarizing what others have mentioned, but I think the cleanest solution to this exact (and frequently encountered) question is to utilize the toLocaleStringmethodwith USD currency formatting:

我主要是在总结其他人提到的内容,但我认为解决这个确切(也是经常遇到的)问题的最简洁的解决方案是使用美元货币格式toLocaleString方法

return value.toLocaleString("en-US",{style:"currency", currency:"USD"});

This works in all modern browsers. The Mozilla documentation for toLocaleStringlists specific browser compatibility and options for other locales, currencies, and formatting types (e.g. percentages).

这适用于所有现代浏览器。在Mozilla的文档toLocaleString列出了具体的浏览器的兼容性和其他语言环境,货币期权,和格式类型(例如百分比)。

Note Chart.js Version 2+ (released in April 2016) requires using the callbackmethodfor advanced tick formatting:

注意 Chart.js 版本 2+(2016 年 4 月发布)需要使用callback高级刻度格式方法

var chartInstance = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
     scales: {
       yAxes: [{
         ticks: {
           callback: function(value, index, values) {
             return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
           }
         }
       }]
     }
   }
 });

The syntax if you are using Chart.js Version 1.Xwould be:

如果您使用的是Chart.js 版本 1.X,则语法为:

var myLineChart = new Chart(ctx).Line(data, options);
var data = {
  ...
}
var options = {
  scaleLabel: function(label) {
    return value.toLocaleString("en-US",{style:"currency", currency:"USD"});
}

Credit to Perry Tew for referencing the syntax change, and to mfink for the ideato use toLocaleString.

感谢 Perry Tew引用了语法更改,感谢 mfink 提供使用的想法toLocaleString

回答by Ege Ersoz

Adding to Perry Tew's answer, if you have negative dollar amounts on your axes (e.g. when displaying a profit/loss chart), you can use this:

添加到 Perry Tew 的答案中,如果您的轴上有负的美元金额(例如,在显示利润/亏损图表时),您可以使用:

ticks: {
    callback: function(value, index, values) {
        if(parseInt(value) > 999){
            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        } else if (parseInt(value) < -999) {
            return '-$' + Math.abs(value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        } else {
            return '$' + value;
        }
    }
}

The correct format for displaying negative currencies is -$XXX, so we prepend -$to the value, and then run it through Math.abs(), which converts it to positive.

显示负货币的正确格式是 -$XXX,因此我们-$在该值前面加上,然后通过 Math.abs() 运行它,将其转换为正数。

回答by Son Dang

In chartjs v2.0, you can set a global options like this:

在 chartjs v2.0 中,您可以设置一个全局选项,如下所示:

Chart.defaults.global.tooltips.callbacks.label = function(tooltipItem, data) {
    return tooltipItem.yLabel.toLocaleString("en-US");
};

Chart.scaleService.updateScaleDefaults('linear', {
    ticks: {
        callback: function (value, index, values) {
            return value.toLocaleString();
        }
    }
});

回答by NickyTheWrench

If you are using Charts.js for Angular 2+ (ng2-charts) you can use CurrencyPipe. Here is how I formatted the label:

如果您将 Charts.js 用于 Angular 2+ (ng2-charts),您可以使用CurrencyPipe. 这是我格式化标签的方式:

Inject the dependency within your page.ts file:

在 page.ts 文件中注入依赖项:

import { CurrencyPipe } from '@angular/common';

Here is how I call it within my chart options:

以下是我在图表选项中的称呼:

public chartOptions: any = {
        responsive: true,
        legend: {
            display: false,
            labels: {
                display: false
            }
        },
        tooltips: {
          enabled: true,
          mode: 'single',
          callbacks: {
            label: function(tooltipItem, data) {
              let label = data.labels[tooltipItem.index];
              let datasetLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
              let currencyPipe = new CurrencyPipe('en');
              let formattedNumber = currencyPipe.transform(datasetLabel, 'USD', 'symbol');
              return label + ': ' + formattedNumber;
            }
          }
        }
    };

回答by Christhofer Natalius

Using chartjs v2.8.0, after looking around the docs, I found it here.

使用chartjs v2.8.0,在查看文档后,我在这里找到了它。

Instead of making my own formatter, I'm using numeraljsto format the number. So this is what I do:

我没有使用自己的格式化程序,而是使用numericjs来格式化数字。所以这就是我所做的:

import numeral from 'numeral'

import numeral from 'numeral'

options: {
  scales: {
    yAxes: [{
      ticks: {
        callback: function (value, index, values) {
          // add comma as thousand separator
          return numeral(value).format('0,0')
        },
      }
    }]
  },
  tooltips: {
    callbacks: {
      label: function (tooltipItem, data) {
        var label = data.datasets[tooltipItem.datasetIndex].label || ''

        if (label) {
          label += ': '
        }
        label += numeral(tooltipItem.yLabel).format('0,0')
        return label
      },
    },
  },
}

You can use format('$ 0,0')to add currency symbol along with comma thousand separator.

您可以使用format('$ 0,0')添加货币符号和逗号千位分隔符。

回答by jumpHyman

There is a specific javascript function to convert a long number into a number formatted according to system settings: toLocaleString().

有一个特定的 javascript 函数可以将长数字转换为根据系统设置格式化的数字:toLocaleString()。

You can specify that the label of each tick (or of a specific tick identified by its number index) must be built by your own function, by adding "callback:" keyword inside tick options:

您可以指定每个刻度(或由其编号索引标识的特定刻度)的标签必须由您自己的函数构建,方法是在刻度选项中添加“回调:”关键字:

Before:

前:

        ticks: {
                  max: maxAltitude,
                  min: 0
                }

After:

后:

        ticks: {
                  max: maxAltitude,
                  min: 0, // <--- dont' foget to add this comma if you already have specified ticks options
                    callback:  
                      function(value, index, valuesArray) {
                          // value: currently processed tick label
                          // index of currently processed tick label
                          // valuesArray: array containing all predefined labels
                          return  value.toLocaleString(); 
                      } // Function end
                } // Ticks options end

Without the comments and without unused variables:

没有注释也没有未使用的变量:

        ticks: {
                  max: maxAltitude,
                  min: 0, 
                  callback:  
                      function(value) {
                        return  value.toLocaleString(); 
                      }
                }