convert string with dot or comma as decimal separator to number in javascript

Solutions on MaxInterview for convert string with dot or comma as decimal separator to number in javascript by the best coders in the world

showing results for - "convert string with dot or comma as decimal separator to number in javascript"
Cale
13 Aug 2017
1function realParseFloat(s)
2{
3    s = s.replace(/[^\d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
4    if (navigator.language.substring(0, 2) !== "de" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(s)) // if not in German locale and matches #,###.######
5    {
6        s = s.replace(/,/g, ''); // strip out commas
7        return parseFloat(s); // convert to number
8    }
9    else if (/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
10    {
11        s = s.replace(/\./g, ''); // strip out dots
12        s = s.replace(/,/g, '.'); // replace comma with dot
13        return parseFloat(s);
14    }
15    else // try #,###.###### anyway
16    {
17        s = s.replace(/,/g, ''); // strip out commas
18        return parseFloat(s); // convert to number
19    }
20}