Convert String with Dot or Comma as decimal separator to number in JavaScript Convert String with Dot or Comma as decimal separator to number in JavaScript javascript javascript

Convert String with Dot or Comma as decimal separator to number in JavaScript


Do a replace first:

parseFloat(str.replace(',','.').replace(' ',''))


I realise I'm late to the party, but I wanted a solution for this that properly handled digit grouping as well as different decimal separators for currencies. As none of these fully covered my use case I wrote my own solution which may be useful to others:

function parsePotentiallyGroupedFloat(stringValue) {    stringValue = stringValue.trim();    var result = stringValue.replace(/[^0-9]/g, '');    if (/[,\.]\d{2}$/.test(stringValue)) {        result = result.replace(/(\d{2})$/, '.$1');    }    return parseFloat(result);}

This should strip out any non-digits and then check whether there was a decimal point (or comma) followed by two digits and insert the decimal point if needed.

It's worth noting that I aimed this specifically for currency and as such it assumes either no decimal places or exactly two. It's pretty hard to be sure about whether the first potential decimal point encountered is a decimal point or a digit grouping character (e.g., 1.542 could be 1542) unless you know the specifics of the current locale, but it should be easy enough to tailor this to your specific use case by changing \d{2}$ to something that will appropriately match what you expect to be after the decimal point.


The perfect solution

accounting.js is a tiny JavaScript library for number, money and currency formatting.

Check this for ref