While working with javascript strings and numbers, there is often a requirement to convert string to numbers. This article demonstrates easy ways to convert strings to number in javascript using different methods and example illustrations.

Table of Contents:

Convert string to number using Number()

Example:-

Convert string “100” to number 100

Code:-

Output:-

var stringNum = "100"
console.log(stringNum+1)
stringNum = Number(stringNum);
console.log(stringNum+1)
1001
101

Note that the first line prints two strings concatenated as output while the second line shows that stringNum is now converted to number and sum is printed. 

Convert string to number using Math.floor

Example:-

Convert “100” to number 100

Code:-

var stringNum = "100"
var floor = Math.floor
console.log(stringNum+1)
var x = floor(stringNum)
console.log(x+1)

Output:-

1001
101

Note that the first line prints two strings concatenated as output while the second line shows that stringNum is now converted to number and sum is printed. 

Convert string to number using parseInt()

Example:-

Convert “100” to number 100

Code:-

var stringNum = "100"
console.log(stringNum+1);
var x = parseInt(stringNum); //returns 10
console.log(x+1);

Output:-

1001
101

Note that the first line prints two strings concatenated as output while the second line shows that stringNum is now converted to number and sum is printed. 

Convert string to number using preceding operator

Example:-

Convert “100” to number 100

Code:-

var stringNum = "100"
console.log(stringNum+1)
var x = +stringNum;
console.log(x+1);

Output:-

1001
101

Note that the first line prints two strings concatenated as output while the second line shows that stringNum is now converted to number and sum is printed. 

Read More:

I hope this article helped you in converting string to number in javascript. Good Luck !!!