How to convert a string to an integer in JavaScript

3 ways to convert a string to an integer: 

  1. Using parseInt() method
  2. Using Unary operator (+)
  3. Using Number() method

Method 1: Using parseInt() method

The parseInt() method is used to convert string representations of numbers into their integer format. It parses a string and returns an integer according to the specified radix.

Syntax

parseInt(value, radix);

Visual Representation

 

Visual Representation of Passing a value parameter

Example 1: Passing a value parameter

let a = "11"
let b = "11.21" 
let c = "11 21 29" 
 
console.log(parseInt(a));
console.log(parseInt(b)); // ignoring the decimal part
console.log(parseInt(c)); //stop parsing at the first space (which it considers a non-integer character)

Output

11
11
11

Example 2: Passing a radix parameterVisual Representation of Passing a radix parameter

let a = "11";
let b = "1101";
let c = "17";

console.log(parseInt(a, 2)); // Parsing a binary string (base 2)
console.log(parseInt(b, 8)); // Parsing an octal string (base 8)
console.log(parseInt(c, 16)); // Parsing a hexadecimal string (base 16)

Output

3
577
23

Method 2: Using unary(+) operator

The unary plus (+) is a single-operand operator, converts its operand to a number if it’s not one already. It can convert strings representing integers or floats, as well as booleans (true or false) and null.

Syntax

+operator

Visual Representation

Visual Representation of Using unary(+) operator

Example

let a = "11";
let b = "AppDividend";
let c = "17.75";
let d = null;

console.log(+a);
console.log(+b);
console.log(+c);
console.log(+d);

Output

11
NaN
17.75
0

Method 3: Using Number() method

The JavaScript Number() method is used to convert any primitive data type into a number; if the conversion is not possible, it returns NaN.

Syntax

Number(value)

Visual Representation

Visual Representation of Using Number() method

Example

let a = "11";
let b = "AppDividend";
let c = "17.75";
let d = true;

console.log(Number(a));
console.log(Number(b));
console.log(Number(c));
console.log(Number(d));

Output

11
NaN
17.75
1

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.