Convert Javascript string to int | javascript parseint() function

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.

Convert Javascript string to int parseint function

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


A syntax for how string to int in JavaScript.

parseInt function accept two parameters:- Value and radix


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 first character of string then it will return “NaN”.

Need of Convert string to int javascript

At starting we see 2 type 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.


Convert string to int javascript Example

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 the radix. Radix is for base number used in mathematical systems. 

Output: In output you will see result is “true“.

JavaScript parseint function Example

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.


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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.