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

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
var str = "rn tv 123 rn";

// 123
var str = "123 456";

// NaN

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
var str = "345b";

// NaN

Leave a Reply

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