-2

What I'm talking about is reading a string into a Number, e.g.

"$107,140,946" ---> 107140946

"$9.99" ---> 9.99

Is there a better way than

dolstr.replace('$','');
dolstr.replace(',','');
var num = parseInt(dolstr,10);

???

Subpar Web Dev
  • 3,210
  • 7
  • 21
  • 35

4 Answers4

0

Using a simple regex and the string's replace function

parseFloat(dolstr.replace(/[^\d\.]/g, ''))

Breakdown

It replaces every instance of a character that is not a digit (0 - 9) and not a period. Note that the period must be escaped with a backwards slash.

You then need to wrap the function in parseFloat to convert from a string to a float.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

Using regex is much simpler to read and maintain

 parseFloat(dolstr.replace(/\$|,/g, ""));
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
0

You can just put all of this in oneliner:

parseFloat(dolstr.replace('$','').split(",").join(""))

Notice that I do not replace the second one, because this will remove just the first ','.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
0

Assuming input is always correct, just keep only digits (\d) and the dot (\.) and get rid of other characters. Then run parseFloat on the result.

parseFloat(dolstr.replace(/[^\d\.]/g, ''))
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52