You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular ngChartjs柱状图tooltip数值无法保留两位小数问题求解

问题原因

你将tooltips配置错误嵌套在了yAxes的配置对象内部,Chart.js 2.x版本中tooltips属于顶层配置项,需要和scales平级放置;如果是Chart.js 3.x版本,tooltip配置需要放在plugins属性下。

同时你现有的格式化逻辑只实现了千分位分隔,没有处理保留两位小数的需求。

解决方案

1. Chart.js 2.x版本配置修正

将tooltips移到barChartOptions顶层,和scales平级,同时完善格式化逻辑:

barChartOptions: any = {
  scaleShowVerticalLines: false,
  responsive: true,
  // tooltips放在顶层,和scales平级
  tooltips: {
    callbacks: {
      label(tooltipItem, data) {
        // 先保留两位小数
        const formattedValue = Number(tooltipItem.yLabel).toFixed(2);
        // 添加千分位分隔符
        return formattedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }
    }
  },
  scales: {
    xAxes: [{
      display: true,
      scaleLabel: {
        display: false,
        labelString: 'Month'
      },
      gridLines: false,
      ticks: {
        display: true,
        beginAtZero: true,
        fontSize: 13,
        padding: 10
      }
    }],
    yAxes: [{
      display: true,
      scaleLabel: {
        display: false,
        labelString: 'Value',
      },
      gridLines: {
        drawBorder: false,
        offsetGridLines: false,
        drawTicks: false,
        borderDash: [3, 4],
        zeroLineWidth: 1,
        zeroLineBorderDash: [3, 4]
      },
      // 删除原来写在yAxes里的tooltips配置
      ticks: {
        display: true,
        beginAtZero: true,
        fontSize: 13,
        padding: 10,
        callback(value) {
          const ranges = [
            { divider: 1e6, suffix: 'M' },
            { divider: 1e3, suffix: 'k' }
          ];
          function formatNumber(n) {
            for (let i = 0; i < ranges.length; i++) {
              if (n >= ranges[i].divider) {
                return (n / ranges[i].divider).toString() + ranges[i].suffix;
              }
            }
            return n;
          }
          return ' ' + formatNumber(value);
        }
      }
    }]
  }
};

2. Chart.js 3.x版本适配

如果使用的是Chart.js 3.x版本,将tooltip配置放在plugins属性下即可:

barChartOptions: any = {
  scaleShowVerticalLines: false,
  responsive: true,
  plugins: {
    tooltip: {
      callbacks: {
        label(context) {
          const formattedValue = Number(context.parsed.y).toFixed(2);
          return formattedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
      }
    }
  },
  scales: {/* 其余scales配置保持不变 */}
};

修改完成后tooltip的数值即可按照「保留两位小数+千分位分隔」的要求正常展示。


内容的提问来源于stack exchange,提问作者core114

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:45:02