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

如何为千位数字添加逗号?JS数字计数函数格式化问题

实现数字千位分隔符的解决方案

你可以利用JavaScript内置的toLocaleString()方法快速实现数字的千位分隔格式化,修改计数更新逻辑即可解决问题:

修改后的JavaScript代码

let elements = document.querySelectorAll('#count-up-number');
let time = 5;

elements.forEach((element) => {
  element.textContent = '0';

  const updateCount = () => {
    const number = parseInt(element.getAttribute('data-value'));
    const value = +element.textContent.replace(/,/g, ''); // 移除逗号后转为数字,避免计算错误

    const increment = number / 200;
    if (value < number) {
      const newValue = Math.ceil(value + increment);
      element.textContent = newValue.toLocaleString(); // 格式化数字添加千位分隔符
      setTimeout(updateCount, time);
    } else {
      element.textContent = number.toLocaleString(); // 确保最终目标值也正确格式化
    }
  }
  updateCount();
})

关键说明

  • toLocaleString()是JS原生方法,会自动为数字添加千位分隔符,无需手动拼接字符串
  • 读取当前显示的数字时,必须用replace(/,/g, '')移除逗号,否则带逗号的字符串无法正确转为数字进行累加计算
  • 新增else分支,保证数字增长到目标值时,显示的是正确格式化后的最终结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:25:25