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

问题描述 投票:1回答:1

要根据区域设置格式化数字,有一个标准的JavaScript API:Intl.NumberFormat

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

是否真的没有JavaScript标准API来根据区域设置将字符串解析为数字?

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

javascript parsing numbers locale
1个回答
1
投票

NPM包d2l-intl提供了一个区域敏感的解析器。

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

不幸的是,该库仅支持开箱即用的handful of locales。它还使用仅支持西方阿拉伯数字的parseInt,因此对于使用不同数字系统的语言环境,您将不得不变得更加聪明。 Here's one solution我发现Mike Bostock。我不想因为它而受到赞誉,但我在这里为后代再现了它(根据我自己的喜好略微调整):

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
© www.soinside.com 2019 - 2024. All rights reserved.