Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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

function realParseFloat(s)
{
    s = s.replace(/[^d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
    if (navigator.language.substring(0, 2) !== "de" && /^-?(?:d+|d{1,3}(?:,d{3})+)(?:.d+)?$/.test(s)) // if not in German locale and matches #,###.######
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
    else if (/^-?(?:d+|d{1,3}(?:.d{3})+)(?:,d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
    {
        s = s.replace(/./g, ''); // strip out dots
        s = s.replace(/,/g, '.'); // replace comma with dot
        return parseFloat(s);
    }
    else // try #,###.###### anyway
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #convert #string #dot #comma #decimal #separator #number #javascript
ADD COMMENT
Topic
Name
3+7 =