Google charts display Money not Percentages

2019-04-07 19:14发布

问题:

Given the data for a pie chart:

data = new google.visualization.arrayToDataTable([
    ['Sales', 'Revenue Distribution'],
    ['Author', 5],
    ['Company', 2],
    ['Tax', 0.4],
    ['Payment Processors', 0.9]
]);
drawChart();

How can I make it display as dollar amounts? Either in the tooltip or on the actual graph itself (both would be preferable!)

For example, ideally this would work:

data = new google.visualization.arrayToDataTable([
    ['Sales', 'Revenue Distribution'],
    ['Author', '$5'],
    ['Company', '$2'],
    ['Tax', '$0.4'],
    ['Payment Processors', '$0.9']
]);
drawChart();

回答1:

It is possible and it will apply it to both the slice and the tooltip. What you need to include is a number formatter.

The key things are to apply the following before you 'create' the chart.

var formatter = new google.visualization.NumberFormat({
    prefix: '$'
});
formatter.format(data, 1);

var options = {
    pieSliceText: 'value'
};

This first creates the formatter and applies it to the data, the next option then forces the pie chart to show the formatted value, rather than the calculated percentage. You can see it working in this jsfiddle.

Inspired and adapted by the answer here: Formatting google charts programmatically