Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript converting and exploding string to number

Tags:

javascript

What can I use to convert this string into a number? "$148,326.00"

I am guessing that I need to explode it and take the dollar sign off, and then use parseFloat()? Would that be the wisest way?

This is how I am getting the number:

var homestead = xmlDoc.getElementsByTagName("sc2cash");
document.getElementById('num1').innerHTML = homestead[1].textContent;
like image 697
Shawn Avatar asked Jun 03 '11 05:06

Shawn


2 Answers

You need to remove the dollar signs and commas, (string replace), then convert to a float value

Try this:

parseFloat('$148,326.00'.replace(/\$|,/g, ''))

See: http://www.w3schools.com/jsref/jsref_parseFloat.asp

Or: http://www.bradino.com/javascript/string-replace/

To handle other currency symbols you could use the following instead (which will remove all non numeric values (excluding a . and -)):

parseFloat('$148,326.00'.replace(/[^0-9.-]+/g, ''))
like image 108
Petah Avatar answered Nov 14 '22 12:11

Petah


var s = '$148,326.01';
parseFloat(s.replace(/[^\d.]/g, '')); // => 148326.01
like image 39
maerics Avatar answered Nov 14 '22 13:11

maerics