It's not advisable to heavily rely on regular expressions in this scenario. My approach would be divided into 2 steps.
Firstly, determine the correct decimal point based on the locale. This can easily be achieved by creating a function that adds a localized decimal point and returns it.
function findDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
The advantage of this function is that if no locale
is provided, the default one will be used (which is "en-GB" in my case).
Now that you have identified the decimal point, you can use it to split the formatted number into two parts - the whole numbers before the decimal and the decimals after it.
function convertNumber(number, locale) {
// Splitting the number based on the decimal point.
var numberParts = String(number).split(findDecimalPoint(locale));
// Removing all non-numeric characters from the whole numbers and parsing
// them as a number.
var converted = Number(numberParts[0].replace(/\D+/g, ""));
// Checking for decimals. If present, converting them into
// a decimal and adding them to the converted result.
var decimals = numberParts[1];
if (decimals && decimals.length) {
converted += decimals / Math.pow(10, decimals.length);
}
return converted;
}
To use this function, simply input your numbers.
convertNumber("1,000,000.00"); // -> 1000000
convertNumber("2'345',00", "fr"); // -> 2345
convertNumber("2'344'334.03"); // -> 2344344.03
// I am aware these numbers are not formatted in French, but feel free to adjust
// the format as needed.
function findDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
function convertNumber(number, locale) {
var numberParts = String(number).split(findDecimalPoint(locale));
var converted = Number(numberParts[0].replace(/\D+/g, ""));
var decimals = numberParts[1];
if (decimals && decimals.length) {
converted += decimals / Math.pow(10, decimals.length);
}
return converted;
}
console.log(convertNumber("1,000,000.00"));
console.log(convertNumber("2'345',00", "fr"));
console.log(convertNumber("2'344'334.03"));