So, recently I came across something weird about JavaScript (Which is not surprising) and i can't believe even though I kinda knew that concept of JavaScript, i never imagined it would do something like this.
Primeagen stream - twitch
If you still didn't get that, look carefully, for some reason
parseInt(0.0000005) given output as "5" instead of 0.
But why? The reason is pretty simple. We just need to take a small peak under the hood on how JavaScript actually executes "parseInt(0.0000005)"
It's explanation is present in how JavaScript handles floating-point number representations and string conversions.
- When you pass a floating-point number to parseInt(), JavaScript first converts the number to a string and then tries to parse that string into an integer.
- For very small floating-point numbers, JavaScript might use scientific notation when converting the number to a string.
Let's break it down with this example:
- 0.0000005 in scientific notation is 5e-7.
- When you pass 0.0000005 to parseInt(), JavaScript first converts it to the string "5e-7".
- Now, The parseInt function then tries to parse this string "5e-7" as an integer. It starts from the left and reads characters until it encounters a character that cannot be part of an integer, in this case the letter 'e'.
- So it only reads the first character, which is '5', and returns it as an integer, hence the result is 5.
On the other hand, numbers like 0.000005 or 0.00005 do not get represented in scientific notation when they are converted to strings in this context, so they convert to "0.000005" and "0.00005" respectively. parseInt() then reads these strings from the start and stops at the first non-integer character, which in this case is the decimal point. Therefore, the result is 0.
To put it in layman terms, think of parseInt() as a dumb machine that reads numbers character by character until it finds something it doesn't understand.