Why Does JavaScript’s parseInt(0.0000005)
Print “5”? 🤔
JavaScript’s parseInt()
function is quite handy for converting strings into integers, but it can sometimes lead to surprising results. One such mystery is when you call:
parseInt(0.0000005)
And the output is 5
! 😲
The Reason Behind It
Here’s the simple explanation: parseInt()
doesn't just look at the number itself. It first converts the value to a string. So, when we pass 0.0000005
, JavaScript automatically converts it to the string "5e-7"
. 🎢
Now, parseInt()
starts reading the string from the left and stops at the first non-numeric character. In "5e-7"
, it sees 5
first, so it stops there and returns 5
. It doesn’t process the scientific notation part (e-7
), which is why it ignores the decimals.
Summary 📜
-
parseInt()
processes numbers as strings. - It only reads up to the first non-numeric character.
- The result is the integer before the first non-digit character.
Final Trick Question! 🧩
What will console.log(0.1 + 0.2 == 0.3)
return? 🤨 Try it and see if you can crack this JavaScript mystery!