+ 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.
4 Answers
+ 7
console.log(parseInt("5")+5);//returns int
+ 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
+ 2
Yeah, use parseInt. If you want to convert it back to a string use toString:
console.log(5.toString());//output: 5 (string)
+ 2
Thanks, D_Stark .
I thought wtiting just 5 would directly instantiate a number. Had wrong.