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

Intl.NumberFormat十进制格式无法处理17位以上数字的解决方案咨询

问题:Intl.NumberFormat处理17位以上印尼盾数字时显示混乱

我尝试用Intl.NumberFormat以十进制格式创建印尼盾金额格式化工具,但输入数字超过17位时,显示的数字和输入不符,出现混乱。我的格式化代码如下:

export const convertWithDelimiter = (value: string): string => {
  const amountValue = parseFloat(value)
  const formatter = Intl.NumberFormat('id-ID', {
    style: 'decimal',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  });

  return value ? formatter.format(amountValue) : '';
};

请问有没有办法让Intl.NumberFormat的十进制格式正确处理17位以上的数字?


解决方案

问题核心在于**parseFloat的精度限制**:JavaScript的Number类型是64位浮点数,最大安全整数为2^53 - 1(即9007199254740991,共16位)。当输入数字超出这个范围时,转成Number会丢失精度,导致Intl.NumberFormat输出错误结果。

要解决这个问题,避免将超长数字字符串转为Number类型,可以用以下两种方案:

方案1:手动实现印尼盾格式的千位分隔符

印尼盾的千位分隔符是.,直接对纯数字字符串按三位一组添加分隔符即可:

export const convertWithDelimiter = (value: string): string => {
  if (!value) return '';
  // 清除字符串中的非数字字符
  const cleanedValue = value.replace(/\D/g, '');
  // 从右往左每三位插入点分隔符
  return cleanedValue.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
};

方案2:用BigInt配合Intl.NumberFormat

如果运行环境支持BigInt(现代浏览器、Node.js 10+均支持),可以将字符串转为BigInt后再格式化:

export const convertWithDelimiter = (value: string): string => {
  if (!value) return '';
  try {
    const amountValue = BigInt(value);
    const formatter = Intl.NumberFormat('id-ID', {
      style: 'decimal',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0
    });
    return formatter.format(amountValue);
  } catch (e) {
    // 处理无效数字输入的情况
    return '';
  }
};

注意:使用BigInt时需确保输入是纯数字字符串,否则会抛出异常,建议添加错误捕获逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 23:47:05