我找到了一个解决方法:
/**
* Parse a localized number to a float.
* @param {string} stringNumber - the localized number
* @param {string} locale - [optional] the locale that the number is represented in. Omit this parameter to use the current locale.
*/
function parseLocaleNumber(stringNumber, locale) {
var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');
return parseFloat(stringNumber
.replace(new RegExp('\\' + thousandSeparator, 'g'), '')
.replace(new RegExp('\\' + decimalSeparator), '.')
);
}
像这样使用它:
parseLocaleNumber('3.400,5', 'de');
parseLocaleNumber('3.400,5'); // or if you have German locale settings
// results in: 3400.5
不是最好的解决方案,但它有效:-)
如果有人知道实现这一目标的更好方法,请随时发布您的答案。
更新
- 包裹在一个完整的可重用函数中
- 使用正则表达式类
\p{Number}
来提取分隔符。因此它也适用于非阿拉伯数字。
- 使用 5 位数字来支持数字每四位分隔的语言。