The mistery behind parseInt(0.0000005)

The parseInt function produces an integral number dictated by the interpretation of the contents of the string argument according to the specified radix.

The mistery behind parseInt(0.0000005)
Photo by Ferenc Almasi / Unsplash

A bit of background

The parseInt() method parses a value as a string and returns the first integer.

A radix parameter specifies the number system to use (2 = binary, 10 = decimal, 16 = hexadecimal).
If radix is omitted, JavaScript assumes a radix of 10. If the value begins with 0x, it will assume radix 16.

The return type of parseInt is integer or NaN.
If not NaN, the return value will be the integer that is the first argument taken as a number in the specified radix.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters.

Solving the mistery...

Reading through the ECMAScript 2021 we'll see this:

When parseInt function is called, the following steps are taken:

  • Let inputString be ? ToString(string)
  • Let S be ! TrimString(inputString, start)
  • ...

I'll leave the rest of the steps to your discretion to read.

So let's look again at what parseInt(numericalString) does with its first argument: if it's not a string, then it is converted to a string, then parsed and if it encounters a character that is not a numeral - it ignores it and all succeeding characters

In our case, String(0.0000005) === "5e-7" and considering the above mentions, the return value of parseInt("5e-7") is 5


parseInt is a function that parses numerical strings to integers and you must be careful when trying to extract the integer part of a float.

A cool challenge before my next JavaScript post:
Can you explain why parseInt(999999999999999999999) equals 1?

Write your considerations in the comments section below!

Mastodon Romania