8

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;
peterh
  • 11,875
  • 18
  • 85
  • 108
Shawn
  • 933
  • 4
  • 18
  • 29

4 Answers4

29

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, ''))
Petah
  • 45,477
  • 28
  • 157
  • 213
  • `/[^0-9\.]+/g` should really just be `/[^0-9.]/g`. – Matt Ball Jun 03 '11 at 05:34
  • 1
    You may want to pay attention to second solution, that would return the absolute value of a negative number. `parseFloat('$-148,326.00'.replace(/[^0-9\.]+/g, ''))` will return 148326 – Hazem Salama Feb 28 '13 at 19:54
5
var s = '$148,326.01';
parseFloat(s.replace(/[^\d.]/g, '')); // => 148326.01
maerics
  • 151,642
  • 46
  • 269
  • 291
  • i revised the coding a little, im actually pulling the string from an xml.. i should be able to put the var to that right – Shawn Jun 03 '11 at 05:21
0

Will this help

How to convert a currency string to a double with jQuery or Javascript?

Community
  • 1
  • 1
OnesimusUnbound
  • 2,886
  • 3
  • 30
  • 40
0

This might be of some help Convert Currency into number format--float/int

Misam
  • 4,320
  • 2
  • 25
  • 43