+ 1

How to convert a string to an integer in JavaScript

I am a beginner in JavaScript and I see something which worked in C# doesn't work in JavaScript. Such as how to convert a string to an integer. I know x.toString() works but x.toInteger doesn't work.

19th Mar 2019, 9:50 AM
Matsumoto
Matsumoto - avatar
4 Answers
+ 7
console.log(parseInt("5")+5);//returns int
19th Mar 2019, 9:53 AM
D_Stark
D_Stark - avatar
+ 6
Joel Kronqvist 5.toString() wouldent work friend you need. var x = 5; console.log(x.toString()); if your wondering why its beacuse js dosent know what the dot means here as it causes ambiguitys, it could mean decimal point. a less clear way to prevent this would be to do. console.log(5..toString()+5); //55 or console.log(5+""+5) //55
19th Mar 2019, 10:46 AM
D_Stark
D_Stark - avatar
+ 2
Yeah, use parseInt. If you want to convert it back to a string use toString: console.log(5.toString());//output: 5 (string)
19th Mar 2019, 10:31 AM
Joel Kronqvist
Joel Kronqvist - avatar
+ 2
Thanks, D_Stark . I thought wtiting just 5 would directly instantiate a number. Had wrong.
19th Mar 2019, 12:46 PM
Joel Kronqvist
Joel Kronqvist - avatar