3 ways to convert a string to an integer:
- Using parseInt() method
- Using Unary operator (+)
- 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
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 parameter![Visual Representation of Passing a radix parameter](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20903%20440'%3E%3C/svg%3E)
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 that converts its operand to a number if it’s not one already. It can convert strings representing integers or floats, booleans (true or false) and null.
Syntax
+operator
Visual Representation
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
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