Use-Cases of this Tutorial
- Convert any variable to a number.
- Preventing error cases by making sure that code is dealing only with valid numbers, and not over other types such as string, boolean etc.
While dealing with mathematical calculations we need to make sure that the variable in question is actually a number. For this we can convert the variable into a number.
A value can be converted to a number using the global Number() method. This method accepts a value of any type as parameter and converts it to a number following a set of rules. If it cannot be converted to a number, it returns NaN which basically means "not a number".
undefined to Number
If undefined is passed as parameter, Number() returns NaN.
var a = undefined;
// NaN
console.log(Number(a));
null to Number
If null is passed to Number(), it returns 0.
var a = null;
// 0
console.log(Number(a));
boolean to Number
A boolean true is returned as 1, false is returned as 0.
var a = true;
var b = false;
// 1
console.log(Number(a));
// 0
console.log(Number(b));
string to Number
An empty string passed to Number() is returned as 0.
var a = '';
// 0
console.log(Number(a));
A non-empty string is parsed to get a number from it. Trailing and leading whitespaces (including tabs and newlines) are removed. After removal if the contents represent a number, it is returned. If it does not represent a number then NaN is returned.
// 23.5
console.log(Number("\t 23.5 \t\t"));
// NaN
console.log(Number("abc"));
// NaN
console.log(Number("23abc"));
number to Number
If a number is passed to Number(), the same value is returned.
// 100
console.log(Number(100));
Checking for NaN
When Number() returns NaN, it needs to be handled. The method Number.isNaN() checks whether the value passed represents NaN or not.
var a = 'abc';
// NaN
var a_numeric = Number(a);
if(Number.isNaN(a_numeric))
console.log('Not a Number');
else
console.log('Valid Number');