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);
???
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);
???
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.
Using regex is much simpler to read and maintain
parseFloat(dolstr.replace(/\$|,/g, ""));
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 ','.
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, ''))