javascript - 如何强制显式显示值的 ".0"部分 (Chart.JS)?

标签 javascript chart.js decimal-point trailing chart.js2

我的图表有以下数据:

datasets: [
{
    label: "Price Compliant",
    backgroundColor: "rgba(34,139,34,0.5)",
    hoverBackgroundColor: "rgba(34,139,34,1)",
    data: [99.0, 99.2, 99.4, 98.9, 99.1, 99.5, 99.6, 99.2, 99.7]
},
{
    label: "Non-Compliant",
    backgroundColor: "rgba(255, 0, 0, 0.5)",
    hoverBackgroundColor: "rgba(255, 0, 0, 1)",
    data: [1.0, 0.8, 0.6, 1.1, 0.9, 0.5, 0.4, 0.8, 0.3]
}
]

...看起来像这样:

enter image description here

如您所见,第一个数据点 (99.0) 显示为 99, chop 了“.0”部分。

当然,这有一些逻辑,但 GUI 纳粹希望保留“.0”。

我需要做什么才能强制显示数据的“无意义”部分?

更新

afterDraw() 事件,对于 Jaromanda X:

Chart.pluginService.register({
    afterDraw: function (chartInstance) {
        if (chartInstance.id !== 1) return; // affect this one only
        var ctx = chartInstance.chart.ctx;
        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(14, 'bold', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i] + "%", model.base + 180, model.y + 6);
                //ctx.fillText(dataset.data[i], model.base + 20, model.y + 6);
            }
        });
    }
});

最佳答案

@machineghost in his comment 所述, 这是一个 known issue .

但是您仍然有几种解决方法可以使其工作:

  • 只需将您的数据更改为字符串:( fiddle link )

    例如你的数据会是这样的:

    {
        label: "Price Compliant",
        backgroundColor: "rgba(34,139,34,0.5)",
        hoverBackgroundColor: "rgba(34,139,34,1)",
        data: ["99.0", "99.2", "99.4", "98.9", "99.1", "99.5", "99.6", "99.2", "99.7"]
    }
    

    Chart.js 会将其作为经典字符串处理,然后不会删除“.0”。

  • 在您的代码中添加“.0”,使用 plugins : ( fiddle link )

    一个小的条件(使用 ternaries )可以使编写和阅读变得容易:

    ctx.fillText(dataset.data[i] + (Number.isInteger(dataset.data[i]) ? ".0" : "") + "%", ((model.x + model.base) / 2 ), model.y + (model.height / 3));
    

    它主要检查值是否为整数(无小数),如果是,则在字符串中添加“.0”。


    这两个代码都会为您提供以下结果:

enter image description here

关于javascript - 如何强制显式显示值的 ".0"部分 (Chart.JS)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735695/

相关文章:

java - ChartJS "Unable to get property ' getTime' 未定义或空引用”

javascript - 无法使用MyChart功能

Chart.js - 如何在图表中间添加文本?

java - 四舍五入小数点

c# - 如何修复小数分隔符有问题的应用程序

javascript - 如果 div 的字符串长度大于 10,则字体大小较小

javascript - 输入类型上的 getElementById.value 返回未定义

java - 格式化后数字为10系列时看不到两位小数

javascript - 将图像附加到现有表头

javascript - 如何将不同文件夹中的多个 Javascript 文件合并到一个文件中?