Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a native way to convert a string from any locale to a number?

Tags:

javascript

I know that I can convert a number to a string in a specified locale like so

(1.2).toLocaleString("de-DE") //-> "1,2"

What I don't know, or can't seem to find, is why there isn't a way to go in reverse. For example:

("1,2").fromLocaleString("de-DE").toFloat()

or

parseFloat("1,2", "de-DE")

The only solutions I have found to parse a number string from a different locale have been 3rd party plugins. If the browser can convert in one direction, is there a way for it to convert in the other direction?

like image 252
awbergs Avatar asked Nov 09 '22 19:11

awbergs


1 Answers

It may be easier to define your own function. Something like this:

function parseFloatSeparator(str, sep) {
    sep = sep || ".";
    str = str.replace(new RegExp("[^0-9"+sep+"]","g"),"");
    if( sep != ".") str = str.replace(sep,".");
    return parseFloat(str);
}
like image 165
Niet the Dark Absol Avatar answered Nov 15 '22 12:11

Niet the Dark Absol