How to Convert a String into an Integer in JavaScript?

Answer

parseInt or unary plus or even parseFloat with floor or Math.round

parseInt:

var x = parseInt(\"1000\",10);// you want to use radix// of 10 so you get a decimal number even with a leading 0

unary plus if your string is already in the form of an integer:

var x =+\"1000\";

if your string is or might be a float and you want an integer:

var x =Math.floor(\"1000.01\");//floor automatically converts string to number

or, if you\'re going to be using Math.floor several times:

var floor =Math.floor;var x = floor(\"1000.01\");

If you\'re the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.

var floor =Math.floor;var x = floor(parseFloat(\"1000.01\"));

Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:

var round =Math.round;var x = round(\"1000\");//equivalent to round(\"1000\",0)

You don\'t see this much. valueOf is used mostly internally, according to w3c

var x =\"1000\".valueOf();

All string Questions

Ask your interview questions on string

Write Your comment or Questions if you want the answers on string from string Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---