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

React中Chart.js如何阻止Tooltip自动将数值四舍五入到三位小数?

解决Chart.js Tooltip自动四舍五入问题

要让Tooltip显示完整的原始数值,只需在Chart的配置项里自定义Tooltip的标签渲染逻辑,具体操作如下:

修改配置项

在你的options对象中补充tooltip相关配置,通过回调函数直接返回原始数据:

const options = {
  "responsive": true,
  "plugins": {
    "legend": {
      "display": false
    },
    "title": {
      "display": true,
      "text": 'Price',
    },
    // 新增Tooltip自定义配置
    "tooltip": {
      "callbacks": {
        "label": function(context) {
          return `Price: ${context.parsed.y}`;
        }
      }
    }
  },
};

完整组件代码

const LineChart = () => {

    const [dataForChart, setDataForChart] = useState<any[]>([1.0023, 1.0231, 1.0347412, 1.03541, 1.0434, 1.04001, 1.0459])
    const [labelsForChart, setlabelsForChart] = useState<any[]>(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July'])
    
    const options = {
        "responsive": true,
        "plugins": {
          "legend": {
            "display": false
          },
          "title": {
            "display": true,
            "text": 'Price',
          },
          "tooltip": {
            "callbacks": {
              "label": (context) => `Price: ${context.parsed.y}`
            }
          }
        },
      };
      
      const data = {
        "labels": labelsForChart,
        "datasets": [
          {
            "label": 'Price',
            "data": dataForChart,
            "borderColor": 'green',
            "backgroundColor": 'green',
          },
        ],
      };


    return (
        <div>
          <Line options={options} data={data} />
        </div>
    );
};

export default LineChart;

原理说明

Chart.js默认会自动对Tooltip中的数值进行格式化和四舍五入,通过tooltip.callbacks.label自定义渲染逻辑,直接读取context.parsed.y获取未经过处理的原始数值,就能让Tooltip完整显示你传入的原始数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:12:29