为了根据语言环境格式化数字,有一个标准的JavaScript API:Intl.NumberFormat
但是对于相反的操作,将字符串解析为数字,我找不到支持语言环境的任何标准API:
真的没有JavaScript标准API可以根据语言环境将字符串解析为数字吗?
如果没有,那么是否有建立任何市场的开源库?
最佳答案
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