The most efficient and direct way to convert a string to a number or integer is to use the built-in parseInt() method. It accepts a string with a specified radix argument and returns a number based on the arguments.
By default, the radix value is 10 if not provided, but it can be risky if the string starts with 0.
let a = "11" let b = "11.21" let c = "11 21 29" console.log(parseInt(a)); // Output: 11 console.log(parseInt(b)); // ignoring the decimal part // Output: 11 console.log(parseInt(c)); //stop parsing at the first space (which it considers a non-integer character) // Output: 11
Invalid string (no digits)
If the string contains only alphabetic characters and no numbers, it returns NaN in the output.
str = "xav"; num = parseInt(str, 10); console.log(num); // Output: NaN console.log(isNaN(num)); // Output: true
String with trailing non-digits (stops parsing)
Let’s say we have a string like “21krunal”, parseInt() will stop parsing when it encounters the characters.
alpha_numeric_string = "21krunal"; num = parseInt(alpha_numeric_string, 10); console.log(num); // Output: 21
In this code, it parsed numeric values and removed all characters from the output.
What if the characters are in the leading and numbers are in the trailing in the input string? In that case, it counts a string with characters and returns NaN in the output.
num_alpha_string = "krunal21"; num = parseInt(num_alpha_string, 10); console.log(num); // Output: NaN
Negative and Empty String
If the string contains a negative number, it returns the negative number in the output after the conversion. For example, “-19” returns -19.
negative_str = "-19"; num = parseInt(negative_str, 10); console.log(num); // Output: -19
If the string is empty, the output is NaN.
empty_str = ""; num = parseInt(empty_str, 10); console.log(num); // Output: NaN
Alternate approaches
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.
let a = "11"; let b = "AppDividend"; let c = "17.75"; let d = null; console.log(+a); // Output: 11 console.log(+b); // Output: NaN console.log(+c); // Output: 17.75 console.log(+d); // Output: 0
Using Number()
The Number() method accepts a valid string and converts it into a number. If it fails to convert, it returns NaN.
let a = "11"; let b = "AppDividend"; let c = "17.75"; let d = true; console.log(Number(a)); // Output: 11 console.log(Number(b)); // Output: NaN console.log(Number(c)); // Output: 17.75 console.log(Number(d)); // Output: 1
That’s all!