-1

How to convert 1,000 to 1000 using JavaScript.

    console.log(parseInt(1,000));

is taking it as 1

Josh Adams
  • 2,113
  • 2
  • 13
  • 25
Shreyash Sharma
  • 310
  • 2
  • 11
  • You need to do the following, parseInt("1,000"); The second parameter is the base. You want to convert the string value – SPlatten Jan 15 '19 at 12:51
  • 6
    Possible duplicate of [How can I parse a string with a comma thousand separator to a number?](https://stackoverflow.com/questions/11665884/how-can-i-parse-a-string-with-a-comma-thousand-separator-to-a-number) – Karol Dowbecki Jan 15 '19 at 12:52
  • There are better solution but this would work: `var n = "1,000"; console.log(n.split(",").join(""));` – Osakr Jan 15 '19 at 12:53

4 Answers4

2

You should replace the "," and then doo the parseInt

parseInt("1,000".replace(/,/g,""));
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
0

You can use a regular expression to replace all non-digits except for - and . when passing the argument to parseInt:

function parseMyInt(str) {
  return parseInt(str.replace(/[^-\.\d]/g,''));
}

console.log(parseMyInt("1,000"));
console.log(parseMyInt("1,000,000"));
console.log(parseMyInt("1,000.1234"));
console.log(parseMyInt("-1,000"));

Edit

Expanded the regex to account for negative numbers and decimals.

Tim Klein
  • 2,538
  • 15
  • 19
0

You need to replace comma with empty character. Something like this below:

parseInt("1,000".replace(/,/g, ""))

Harish Mashetty
  • 433
  • 3
  • 13
0

Try this,

var num = parseInt("1,000".replace(/\,/g, ''), 10);

As, we need to remove "comma" from the string. We also need "10" as radix as the second parameter.

Thanks

dattebayo
  • 1,362
  • 9
  • 4