How to Convert String to Number in Javascript

Use-Cases of this Tutorial

  • Know how to convert a string to a number on which mathematical operations can be performed.

The Number() method can be used to convert a string to a number upon which numerical operations can be done.

Empty String to Number

Passing an empty string to the Number() method returns 0.

var str = "";

// 0
Number(str);

Numeric String to Number

If the string passed has only numeric characters Number() returns the number. If the string contains leading and trailing whitespace characters (tabs, newlines, spaces), they are removed and the represented number is returned. Note that whitespace characters inside the string are not removed and NaN is returned in such a case.

var str = "5432";

// 5432
Number(str);
var str = "\r\n \t\v 123 \r\n";

// 123
Number(str);
var str = "123 456";

// NaN
Number(str);

String of Non-Numeric Characters to Number

If the string contains a single non-numeric character also, Number() returns NaN — which represents it is not a number.

var str = "UsefulAngle";

// NaN
Number(str);
var str = "345b";

// NaN
Number(str);
How to Convert Values to Numbers in Javascript
Loading Comments