Why does parseInt(0.0000005) in JavaScript print 5? An amazing question!
Preface
Recently, I have had a strange problem when developing a project, parseInt (0.0000005) === 5
😱. Normally, the output 0 is correct, but why 5? Let’s explore this problem together.
1. When do you use parseInt?
First of all, when do you usually use parseInt
? Most of the time, we use it to parse a string and return its integer part. With this question, let’s take a look at the parseInt method.
2. Some things about parseInt
As per the MDN docs, “the parseInt(string, radix) function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).”
Syntax
parseInt(string)
parseInt(string, radix)
Example
parseInt('0.5') // 0
parseInt('0.5') // 0
parseInt('0.05') // 0
parseInt('0.005') // 0
parseInt('0.0005') // 0
parseInt('0.00005') // 0
parseInt('0.000005') // 0
parseInt('015') // 15
parseInt('015', 8) // 13
parseInt('15px', 10) // 15
3. How does parseInt convert numbers?
When the first parameter of parseInt is a number, how does it parse?
The truth of parseInt(0.0000005) === 5
is also here…
3.1. The first step? Convert the number to a string.
Let’s check the values on string-based using the String function to see what is the output for each of these:
String(0.5); // => '0.5'
String(0.05); // => '0.05'
String(0.005); // => '0.005'
String(0.0005); // => '0.0005'
String(0.00005); // => '0.00005'
String(0.000005); // => '0.000005'
String(0.0000005); // => '5e-7' pay attention here
3.2. The second step is to do the rounding operation.
As the user SeyyedKhandon explains in his Stack Overflow answer:
“When we use parseInt(0.0000005)
, it is equal to parseInt('5e-7')
and based on the definition:
parseInt may interpret only a leading portion of string as an integer value; it ignores any code units that cannot be interpreted as part of the notation of an integer, and no indication is given that any such code units were ignored.
parseInt(0.0000005)
parseInt('5e-7') // 5
Finally, the answer will return 5 only because it is the only character that is a number till a noncharacter e, so the rest of it e-7 will be discarded.”
4. How to get the integer part of a floating-point number safely?
The following Math.floor() function is recommended:
Math.floor(0.5); // => 0
Math.floor(0.05); // => 0
Math.floor(0.005); // => 0
Math.floor(0.0005); // => 0
Math.floor(0.00005); // => 0
Math.floor(0.000005); // => 0
Math.floor(0.0000005); // => 0
5. Learn by analogy
Now, can you explain why parseInt(99999999999999999999999999)
is equal to 1?