I have a problem convert string 1,200
to integer 1200
i need convert 1,200
to 1200 integer
how to solve my problem using javascript ?
I have a problem convert string 1,200
to integer 1200
i need convert 1,200
to 1200 integer
how to solve my problem using javascript ?
You can split on the comma, rejoin and parse into a number, or remove the commas with a regex and parse into a number
Note that both of these methods allow for more than 1 ',' eg if 1,000, 000 - that's what the g
is for in the regex.
const str = '1,200'
const option1 = parseInt(str.split(',').join(''), 10);
const option2 = parseInt(str.replace(/,/g,''), 10);
console.log('option1 - split and join - then parse: ' + option1);
console.log('option2 - replace with regex - then parse: ' + option2);
To work in node and browser, use replace with regex.
const num = "1,200"
const parsed = Number(num.replace(/,/g, ""))
You can first replace all commas (with String.replaceAll
), then parse:
const str = "1,200"
const parsed = +str.replaceAll(',', '')
console.log(parsed)