Here's an example for a locale aware number parser:
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), '.')
);
}
It uses the passed locale (or the current locale of the browser if locale parameter is undefined) to replace thousand and decimal separators.
With a German locale setting
var n = parseLocaleNumber('1.000.045,22');
n
will be equal to 1000045.22
.
Update:
- Addressed Pointy's comment by using the regex class
p{Number}
for removing digits. So that it also works with non-arabic digits.
- Addressed Orion Adrian's comment to support languages where numbers are separated at every fourth digits.
- Added locale parameter to sepcify different locales for parsing.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…