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()
- Convert string to number using Math.floor
- Convert string to number using parseInt()
- Convert string to number using preceding operator
Convert string to number using Number()
Example:-
Convert string “100” to number 100
Code:-
var stringNum = "100" console.log(stringNum+1) stringNum = Number(stringNum); console.log(stringNum+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.
Frequently Asked:
- JavaScript: Check if String Starts with UpperCase
- Javascript: 4 ways to do case-insensitive comparison
- Remove first N characters from string javascript
- Remove character at a specific index from a string in javascript
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:
- Javascript: Insert an item to array at specific index
- Javascript: Check if an array is empty
- Javascript: Convert array to string (4 ways)
I hope this article helped you in converting string to number in javascript. Good Luck !!!