Convert string to number
Given a string, convert the string to a number, using JavaScript.
Solution
To convert given string str
into a number using JavaScript, call Number()
constructor and pass the string as argument to the method.
Number(str)
If the string is a valid number, then the constructor returns a number created from the given string.
Programs
1. Given a string str
. Convert the string to number.
var str = '5421';
var n = Number(str);
console.log(n);
Since the string is a valid number, Number() returns a number.
2. Given a string str
. This string does contain some alphabets. Check programmatically if this string can convert into a number.
var str = '5421ab';
var n = Number(str);
console.log(n);
Since the given string is not a valid number, Number() returns NaN
.