问题描述:

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)

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

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/

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

Thank you for any and all help.

网友答案:

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/

网友答案:

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.

  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.

网友答案:

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:

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.

网友答案:

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 toLocaleString method with USD currency formatting:

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

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

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

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.X would be:

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 idea to use toLocaleString.

相关阅读:
Top