The simplest way would be to use the native Number function to Convert strings to numbers in JavaScript. If that doesn’t work for you, then there are the parseInt, unary plus, parseFloat with the floor, and Math.round methods.
Example Convert string to number in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var num = "100";
var x = Number(num)
console.log(x);
console.log(typeof(x))
</script>
</body>
</html>
Output:
Using parseInt() function
The parseInt method parses a value as a string and returns the first integer. If the first character cannot be converted, NaN
is returned.
parseInt("5");
parseInt("10.00");
parseInt("10.73");
parseInt("34 45 66");
parseInt(" 100 ");
parseInt("35years");
parseInt("MOney 400");
There more ways to achieve it:
Using the unary plus operator:
var n = +str;
The Number
constructor:
var n = Number(str);
The parseFloat
function:
var n = parseFloat(str);
Do comment if you have any doubts or suggestions on this JS conversion of string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version