How to use the parseInt() Function in JavaScript

parseInt() is a native JavaScript function that is used to convert strings into integers. In this tutorial, we will learn how to use it with int, float and hexadecimal strings.

 

The parseInt() Syntax

The parseInt() function accepts the string to convert and an optional radix.

 

parseInt(string[, radix])

 

  • string – the string to convert.
  • radix (optional) – the numerical system of the string.

 

Convert Int String to Number

In the example below, we will convert a string containing an int into the data type of number.

 

var output = parseInt('222');

console.log(output);
console.log(typeof(output));
222
number

 

Convert Decimal String to Number

When a decimal string is supplied to parseInt() everything after the decimal will be removed.

 

var output = parseInt('222.222');

console.log(output);
console.log(typeof(output));
222
number

 

Convert Hexadecimal Number in a String to Number

A hex number is a base 16 number, to convert it into an integer with the data type of number in JavaScript supply the radix as the second argument like this:

 

var output = parseInt("0xF", 16);

console.log(output);
console.log(typeof(output));
15
number

 

Things to Watch Out for with parseInt()

Here are some behaviours of parseInt() to watch out for:

 

parseInt('222kk222'); // everything after first non number is cut
222
parseInt('s123'); // strings starting with non-numerical value will return NaN
NaN