-6

I would like to convert a string "$1,258.98" into a number 1258.98. How to use JavaScript to achieve this purpose?

zmxq
  • 242
  • 2
  • 6

1 Answers1

1
  1. Simply replace $ and , in the string with empty string and then use parseFloat function to convert it to a valid floating point number.

    var data = "$1,258.98";
    console.log(parseFloat(data.replace("$", "").replace(",", "")));
    
  2. Or replace just the , and then ignore the first character with substring(1) like this

    console.log(parseFloat(data.replace(",", "").substring(1)));
    
  3. Or you can use regular expression, to replace $ and ,, like this

    console.log(parseFloat(data.replace(/[$,]/g, "")));
    

Output

1258.98
thefourtheye
  • 233,700
  • 52
  • 457
  • 497