简体   繁体   中英

Convert String to Integer in JavaScript

I have a string value of 41,123 and I want to convert it to an integer in JavaScript.

I tried parseInt(41,123, 10) and parseFloat, but nothing gives me correct answer.

ParseInt, parseFloat work well until comma is encountered, but to above the result is '41'.

Does anyone have an idea about the fix?

var myInt = parseInt("41,123,10".replace(/,/g,""));

Here is the solution:

Number(s.replace(/,/g, ""))

Regex is needed in replacement to remove all comma characters, otherwise only one comma will be replaced.

You can remove the comma, and then parse; let's say the number is variable s :

parseInt(s.replace(/,/g, '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM