使用 ChartJS 在 y 轴上显示美元符号

yoe*_*ven 7 javascript chart.js

我的 Chart.js 图表 Y 轴上的标签前面应该有一个美元符号,因为它们是金钱的价值。

该代码在文档中,但对我不起作用。

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value;
                    }
                }
            }]
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我的结果。“之前”表示没有此代码,“之后”表示有此代码。 在此输入图像描述 显然,这不仅仅是$在值之前添加一个,而且还发生了其他事情。

知道如何解决这个问题吗?

lil*_*zek 8

这里的问题是,chart.js 不会舍入字符串,因为它不应该为您执行此操作。

当您将字符串附加到数字时,JavaScript 会为您转换它,并且您无法控制精度。

您可以使用toFixed来解决您的问题:

// Define wherever decimals:
const decimals = 3;
// ...
var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                        return '$' + value.toFixed(decimals);
                    }
                }
            }]
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


Maj*_*jor 5

Chart JS 3+ 的语法已从当前接受的答案更改。新格式如下 -

options: {
    scales: {
        y: {
            ticks: {
                // Include a dollar sign in the ticks
                callback: function(value, index, ticks) {
                    return '$' + value;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

https://www.chartjs.org/docs/latest/axes/labelling.html