https://dmitripavlutin.com/parseint-mystery-javascript/

cover-3.png

parseInt() is a built-in JavaScript function that parses integers from numerical strings. For example, let’s parse the integer from the numeric string '100':

const number = parseInt('100');
number; // 100

As expected, '100' is parsed to integer 100.

parseInt(numericalString, radix) also accepts a second argument: the radix at which the numerical string argument is. The radix argument allows you to parse integers from different numerical bases, the most common being 2, 8, 10, and 16.

Let’s use parseInt() to parse a numerical string in base 2:

const number = parseInt('100', 2);
number; // 4

parseInt('100', 2) parses '100' as an integer in numerical base 2: thus it returns the value 4 (in decimal).

That’s pretty much a short introduction to parseInt().

parseInt(numericalString) always converts its first argument to a string (if it’s not a string), then parses that numeric string to the integer value.

That’s why you can (but should’t!) use parseInt() to extract the integer part of float numbers:

parseInt(0.5);      // => 0
parseInt(0.05);     // => 0
parseInt(0.005);    // => 0
parseInt(0.0005);   // => 0
parseInt(0.00005);  // => 0
parseInt(0.000005); // => 0

Try the demo.

Extracting the integer part of floats like 0.5, 0.05, etc. results in 0. This works as expected.

What about extracting the integer part of 0.0000005?

parseInt(0.0000005); // => 5

Try the demo.

parseInt() parses the float 0.0000005 to… 5. Interesting and kind of unexpected…