How to convert a string to an integer in JavaScript

Q & ACategory: AllHow to convert a string to an integer in JavaScript
Luci Staff asked 3 years ago

Solution:

There are many ways to convert string to integer in Javascript.
Use native Number function #
This is the simplest way would be to use the native Number function:

var num = Number("9999")
// num will be 9999
num === 9999
// true

Another example:

var num = Number("1234")
// num will be 1234
num === 1234
// true

Use parseInt #
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Syntax:

parseInt(string [, radix])

Example:

var num = parseInt("1234", 10); 

num === 1234
// true

Use unary plus #
if the string is already in the form of an integer, for example “5678”, we can use unary plus to convert the string to integer. Let see the examples below:

 var num = +"5678";
num === 5678
// true

num = +"1234"
num === 1234
// true

Use parseFloat with floor #
If the string is or might be a float and we want an integer:

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

or, if we are going to be using Math.floor several times:

var floor = Math.floor;
 var num = floor("1000.01");

We can use parseFloat and round it:

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

Use Math.round #
Interestingly, Math.round will do a string to number conversion, so if we want the number rounded (or if you have an integer in the string), this is a great way,:

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