You can convert string to int in Javascript using a parseint() function, but before the start, you must new about how javascript represent strings and integer. The parseInt() is an inbuilt function in JavaScript used to convert a string into an integer.
Below code of basic int and strings declaration in JS:-
int -> var num1 = 20;
string -> var num2 = '20';
Now let’s see JavaScript parseint() function
Syntax
A syntax for how string to int in JavaScript.
parseInt(Value, radix)
parseInt function accept two parameters:- Value and radix
Parameters
Value: Pass the string which will converted to an integer.
radix: This is an optional parameter and represents the radix or base to be used.
Return value:
The JS parseInt() function parses a string and returns an integer. But if it can’t convert the first character of the string then it will return “NaN”.
Need of Convert string to int javascript
At starting we see 2 types of data declaration in Javascript. Now see what are the problem and where we needed to convert a string to int:-
If you have to the comparison of the two variables, it would fail because they’re two different types of objects. Let’s see the problem in the example code.
<!DOCTYPE html>
<html>
<head>
<script>
var num1 = 20;
var num2 = '20';
if (num1 === num2) {
console.log(true);
} else {
console.log(false);
}
</script>
</head>
<body>
</body>
</html>
Output:
Let’s See the JavaScript parseint() function Example
In the example, we are passing two arguments. The first argument is the string and the second argument is called radix
<script>
var num1 = 20;
var num2 = '20';
var newNum = parseInt(num2, 10);
// returns 42
if (num1 === newNum) {
console.log(true);
} else {
console.log(false);
}
</script>
Output: In output you will see result is “true“.
Step to see console log:- Chrome and Safari browser’s
- Right-click on web page -> select inspect (inspect element for Safari)
- A bottom navigation window will open select -> Console option.
Browser Compatibility javascript string to int parseint() function
Answer: All three methods work in all modern browsers, and IE6 and up.
Question: What if a string argument is a combination of char and number?
Answer: There are many cases:-
- If pass only text -> Function will return
NaN
, an acronym for “Not a Number.” - If pass with text-number combination-> Return value will
NaN
. - Last if number-text combination -> Will return decimal values.
Code:
var num1 = 'abc'; var num2 = 'pp20'; var num3 = '20pp'; var newNum1 = parseInt(num1, 10); var newNum2 = parseInt(num2, 10); var newNum3 = parseInt(num3, 10); console.log(newNum1); // NaN console.log(newNum2); // NaN console.log(newNum3); // 20
Do comment if you have any doubts and suggestions on this tutorial.
Note: The How to convert String number value to int in JavaScript Examples are tested on Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version