Search code examples
javascriptparsinglocale

Is it possible to convert locale string to decimal number with thousand separators in JS?


I'm trying to find a way to convert a string which has been outputted by Number.toLocaleString() to a float with thousand and decimal separators. The problem is that I can't find a way to do it for any locale : Chinese numbers have a separator every 4 digits, India starts with 3 then every 2 digits, German separators are exactly the opposite of English ones, French have spaces for thousands etc...

This is basically what I want :

Indian : '10,00,00,123' => '100000.123'
French : '123 456,789' => '123456.789'

Is there a library that can do this ? I do have the locale before parsing with

navigator.language

if it helps

Thanks in advance

UPDATE : This is what I came up with and it works great for Arabic Numerals :

let localeString = '123,45,67,89.57982';

console.log(reformat(localeString));

function reformat(str) {
    let rawNumber;
    let decimalIndex;
    let charToRemove = 0;
    for (let i = 0; i < str.length; i++) {
        if (!isNaN(str[i])) {
            //concatenating numbers
            rawNumber = parseInt(`${rawNumber ? rawNumber : ''}${str[i]}`);
        } else {
            decimalIndex = i;
            charToRemove++;
        }
    }

    return format(rawNumber, decimalIndex, charToRemove);
}

function format(number, decimalIndex, charToRemove) {
    if (decimalIndex) {
        // Adding decimal to the right place
        return number / Math.pow(10, number.toString().length - decimalIndex + charToRemove - 1);
    } else {
        return number;
    }
}

EDIT : it doesn't work as intended as there's no way to know if a separator is a decimal one or a thousand (no way to differentiate int numbers with thousand separators vs decimal number)


Solution

  • Run through the string one character at a time, check if the character is a number, add it to a string and insert your required field separators at your specified intervals (have a counter of 3 for commas maybe?)