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

将ILS货币输入值转换为数字时出现NaN问题求助

问题:CurrencyInput组件处理ILS格式值时转换数值出现NaN

我有一个格式化为ILS(以色列新谢克尔)的CurrencyInput组件,希望在onChange事件中记录其数值类型的值。我尝试了以下代码:

<CurrencyInput
  onChange={(e) =>
    setAmount(Number(e.target.value.replace("&#8362", "")))
  }
  decimalsLimit={2}
  intlConfig={{ locale: "he-IS", currency: "ILS" }}
></CurrencyInput>

但结果仍然是NaN(非数字),请问有什么解决办法?


解决方案

出现NaN的核心原因是:你替换的是HTML实体字符串&#8362,但组件渲染后实际返回的是真实的谢克尔符号₪,不是实体字符串,所以替换操作根本没生效,导致Number()无法解析带符号的字符串。

下面是几种可行的解决方法:

方法1:直接替换真实的谢克尔符号并适配locale格式

<CurrencyInput
  onChange={(e) => {
    // 移除谢克尔符号,把希伯来语中用的逗号小数点替换为英文点,同时去掉千位分隔空格
    const cleanValue = e.target.value
      .replace(/₪/g, '')
      .replace(/,/g, '.')
      .replace(/\s/g, '');
    setAmount(Number(cleanValue));
  }}
  decimalsLimit={2}
  intlConfig={{ locale: "he-IL", currency: "ILS" }}
></CurrencyInput>

注意:这里把he-IS修正为he-IL(以色列的正确Locale代码是he-IL,不是he-IS),避免Locale配置错误导致格式解析异常。

方法2:用Intl.NumberFormat做可靠解析(适配多Locale)

如果组件基于浏览器的Intl API渲染,推荐用Intl.NumberFormat的能力来解析,能自动适配不同Locale的货币格式:

// 封装通用的货币解析函数
const parseCurrency = (inputValue, locale, currency) => {
  const formatter = new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: currency,
  });
  // 获取当前Locale对应的货币符号
  const currencySymbol = formatter.formatToParts(0).find(part => part.type === 'currency').value;
  // 清理数值:移除符号、空格、千位分隔符,统一小数点为英文点
  const cleaned = inputValue
    .replace(new RegExp(currencySymbol, 'g'), '')
    .replace(/\s/g, '')
    .replace(/,/g, '.');
  return Number(cleaned);
};

// 组件中使用
<CurrencyInput
  onChange={(e) => {
    const numericValue = parseCurrency(e.target.value, 'he-IL', 'ILS');
    setAmount(numericValue);
  }}
  decimalsLimit={2}
  intlConfig={{ locale: "he-IL", currency: "ILS" }}
></CurrencyInput>

方法3:检查组件是否自带数值返回能力

很多第三方CurrencyInput组件会在onChange回调中直接返回数值类型的结果,不需要手动解析。比如:

// 部分组件的标准用法(示例)
<CurrencyInput
  onChange={(numericValue) => {
    // numericValue已经是处理好的数值类型
    setAmount(numericValue);
  }}
  decimalsLimit={2}
  intlConfig={{ locale: "he-IL", currency: "ILS" }}
></CurrencyInput>

建议查看你使用的CurrencyInput组件的官方文档,确认是否有直接返回数值的回调参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:10:14