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

Safari 13以下版本调用Intl.NumberFormat.formatToParts未定义如何兼容?

问题原因

iOS 12.5.5 对应的内置 Safari 以及 WKWebView 最高版本为 12,Intl.NumberFormat.prototype.formatToParts 为 Safari 13 以上才支持的原生 API,低版本环境调用不存在的方法就会抛出你遇到的类型错误。

兼容解决方案

1. Polyfill 补全方案

你可以直接使用符合 ECMA-402 规范的 Intl 系列 polyfill 实现,在项目入口文件顶部引入后,会自动在不支持的环境下补全 formatToParts 方法,无需修改原有业务代码,完全兼容原生 API 的所有入参和返回值格式,支持 Safari 10 及以上所有版本。

2. 轻量自定义实现方案(无额外依赖)

如果你的业务场景仅需要基础的数字格式化拆分,不需要复杂多语言适配,也可以自行实现简易替代方法,代码如下:

// 替代原生formatToParts的简易实现,适配基础数字格式化场景
function customFormatToParts(locale, options = {}, number) {
  let formattedStr = Intl.NumberFormat(locale, options).format(number);
  const parts = [];
  // 处理负号
  if (formattedStr.startsWith('-')) {
    parts.push({ type: 'minusSign', value: '-' });
    formattedStr = formattedStr.slice(1);
  }
  // 匹配当前语言的小数分隔符和千分位分隔符
  const testFormatted = Intl.NumberFormat(locale).format(1000.1);
  const groupSeparator = testFormatted.charAt(1);
  const decimalSeparator = testFormatted.charAt(5);
  // 拆分整数、小数部分
  const [integerSeg, fractionalSeg] = formattedStr.split(decimalSeparator);
  // 处理整数部分和千分位
  integerSeg.split(groupSeparator).forEach((chunk, idx, arr) => {
    parts.push({ type: 'integer', value: chunk });
    if (idx !== arr.length - 1) parts.push({ type: 'group', value: groupSeparator });
  });
  // 处理小数部分
  if (fractionalSeg !== undefined) {
    parts.push({ type: 'decimal', value: decimalSeparator });
    parts.push({ type: 'fraction', value: fractionalSeg });
  }
  return parts;
}

// 调用示例,和原生API逻辑对齐
const parts = customFormatToParts('zh-CN', { minimumFractionDigits: 2 }, 1234.5);
  • 该方法返回值结构和原生formatToParts完全一致,直接替换原有调用即可
  • 支持自适应不同语言的分隔符规则,满足绝大多数常规业务场景

3. WKWebView 专属优化方案

如果你的应用是内嵌在iOS客户端的H5页面,也可以由客户端开发在WKWebView初始化时全局注入对应polyfill代码,不需要修改前端业务代码即可全局生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:39:04