-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,122
  • 5
  • 19
  • 33

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
  • 24,108
  • 10
  • 56
  • 82
0

Using regex is much simpler to read and maintain

 parseFloat(dolstr.replace(/\$|,/g, ""));
Muhammad Soliman
  • 18,833
  • 5
  • 99
  • 70
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
  • 199,541
  • 138
  • 677
  • 738
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,178
  • 3
  • 37
  • 50