parseInt and other options for parsing numbers in javaScript

In javaScript parseInt is one of several ways to convert a string to a number. parseInt does convert a string or number to an integer, but technically it is still a float as all numbers in javaScript a double precision floating point numbers. So it is really just a float with the fraction part removed. There are other was to parse to an integer, or float in javaScript as well so lets take a look at the options.

1 - parseInt basic examples

parseInt works by just passing a string of a number, or a number and it will attempt to parse what is passed to it as a number.

1
2
3
4
console.log( parseInt('42') ); // 42
console.log( parseInt('6' * '7') ); // 42
console.log( parseInt(42) ); // 42
console.log( parseInt(42.1234) ); // 42

2 - parseInt converts to String first

The parseInt method might not always return expected results in some situations. For example the parseInt method converts to a string first and if it is a number the goes off into notation, then the letter e char will not be recognized as a number and will parse an int based on what comes before it.

1
2
3
4
5
6
7
8
9
10
11
// parseInt may not always work as expected
console.log(parseInt( Math.pow(10,21) ) ); // 1
// because it converts to string first
let str = String(Math.pow(10,21));
// and it does not consider the letter e to
// be a number
console.log(str); // 1e+21
console.log(parseInt(str)); // 1
console.log( parseInt('12e45') ); // 12

3 - The deal with max safe integer

There is also the nature of the max safe integer, when adding anything to that and going beyond the max safe int that too can result in unexspected results as well.

1
2
3
let n = Number.MAX_SAFE_INTEGER;
console.log(n); // 9007199254740991
console.log(parseInt(n + 100)); // 9007199254741092

4 - parseInt and Number

The Number function can be used to convert a string to a number as well. However it will not parse to an integer, at least not my itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let str = '42.1234';
// number will parse to float if there
// is a fraction
console.log( Number(str) ); // 42.1234
// paser Int will not
console.log( parseInt(str) ); // 42
let str2 = '42abc';
// Number will result in NaN
// if there are non number chars
// in the end of a string
console.log( Number(str2) ); // NaN
// parseInt will not
console.log( parseInt(str2) ); // 42