How to Convert Values to Numbers in Javascript

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”.

See also  Pure CSS Presentation With Rotate Animation

undefined to Number

If undefined is passed as parameter, Number() returns NaN.

var a = undefined;

// NaN

null to Number

If null is passed to Number(), it returns 0.

var a = null;

// 0

boolean to Number

A boolean true is returned as 1, false is returned as 0.

var a = true;

var b = false;

// 1

// 0

string to Number

An empty string passed to Number() is returned as 0.

var a="";

// 0

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 tt"));

// NaN

// NaN

number to Number

If a number is passed to Number(), the same value is returned.

// 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);

    console.log('Not a Number');
    console.log('Valid Number');

Leave a Reply

Your email address will not be published. Required fields are marked *