Converting Strings to Number

How to turn a String to an Int in Javascript

You can convert string to number in a number of ways. But there are two main ways to convert a string to a number in javascript. One way is to parse it and the other way is to change its type to a Number.

JavaScript parseInt() Function

parseInt( string , radix )

convert string to digits in javascript

The parseInt() function parses a string and returns an integer. The first argument is the value to parse and the second argument base, if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36.

var num = parseInt("100");

The above Javascript code returns number 100.

If you pass more than one string, then only the first number in the string is returned

var num = parseInt("100 200 300");

The above Javascript code returns number 100 only and other two string will be omitted.

Leading and trailing spaces are allowed while the parsing the string.

var num = parseInt(" 200 ");

The above Javascript code returns number 200.

If you pass a string and it is not a number format, it will return NaN.

var num = parseInt("number");

The above Javascript code returns number NaN.

If you enter a floating format string , it will return the first integer part only.

var num = parseInt("100.99");

The above Javascript code returns 100.

If you enter a comma separated string , then the first number only parse and returned

var num = parseInt("100,200");

The above Javascript code returns 100.

radix

string to int

The second parameter base, if present, specifies the base (radix) of the number whose string representation is contained in the string. An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. The default 10 for the decimal numeral system commonly used by humans. Always specify this parameter (10) to eliminate reader confusion and to guarantee predictable behavior.

radix 10 - default

var num = parseInt("56,10");

The above code will return 56.

That is : 5*10 + 6 = 56

radix 8

var num = parseInt("56",8);

The above code will return 46.

That is : 5*8 + 6 = 46

var num = parseInt("56",16);

The above code will return 86.

That is : 5*16 + 6 = 86

Note: parseInt is occasionally used as a means of turning a floating point number into an integer.

var num = parseInt("100.99");

The above code will return 100.