是否有任何 JavaScript 标准 API 可以根据区域设置解析数字?

2024-01-13

为了根据区域设置格式化数字,有一个标准的 JavaScript API:国际数字格式 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

但对于相反的操作,将字符串解析为数字,我找不到任何支持语言环境的标准 API:

  • Number https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number不支持任何区域设置参数。
  • 解析浮点型 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat and parseInt https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt也不支持任何区域设置参数。

难道真的没有 JavaScript 标准 API 可以根据语言环境将字符串解析为数字吗?

如果没有:是否有任何市场成熟的开源库可以这样做?


NPM 包d2l-intl https://www.npmjs.com/package/d2l-intl提供区域设置敏感的解析器。此后它已被取代@brightspace-ui/intl https://www.npmjs.com/package/@brightspace-ui/intl(本质上是版本 3),因此下面的一些信息可能适用也可能不适用于其较新的咒语。

const { NumberFormat, NumberParse } = require('d2l-intl');
const formatter = new NumberFormat('es');
const parser = new NumberParse('es');
const number = 1234.5;
console.log(formatter.format(number));                 // 1.234,5
console.log(parser.parse(formatter.format(1234.5)));   // 1234.5

不幸的是,该库仅支持少数语言环境 https://github.com/Brightspace/intl/tree/master/src/locale-data盒子外面。它还使用parseInt它只支持西方阿拉伯数字,因此对于使用不同数字系统的区域设置,您将必须变得更加聪明。这是一种解决方案 https://observablehq.com/@mbostock/localized-number-parsing我发现通过迈克·博斯托克 https://bost.ocks.org/mike/。我不想把它归功于它,但我在这里为后代复制了它(根据我自己的喜好进行了一些细微的调整):

class NumberParser {
  constructor(locale) {
    const format = new Intl.NumberFormat(locale);
    const parts = format.formatToParts(12345.6);
    const numerals = Array.from({ length: 10 }).map((_, i) => format.format(i));
    const index = new Map(numerals.map((d, i) => [d, i]));
    this._group = new RegExp(`[${parts.find(d => d.type === "group").value}]`, "g");
    this._decimal = new RegExp(`[${parts.find(d => d.type === "decimal").value}]`);
    this._numeral = new RegExp(`[${numerals.join("")}]`, "g");
    this._index = d => index.get(d);
  }
  parse(string) {
    return (string = string.trim()
      .replace(this._group, "")
      .replace(this._decimal, ".")
      .replace(this._numeral, this._index)) ? +string : NaN;
  }
}

const formatter = new Intl.NumberFormat('ar-EG');
const parser = new NumberParser('ar-EG');
console.log(formatter.format(1234.5));               // ١٬٢٣٤٫٥
console.log(parser.parse(formatter.format(1234.5))); // 1234.5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有任何 JavaScript 标准 API 可以根据区域设置解析数字? 的相关文章

随机推荐