IntParsingError

A Little explanation of the famous Javascript parseInt(0.0000005); error meme.

GPL-3.0 License

Stars
2

Explaining the meme

Internet is made of millions of memes flowing everyday, so, devs create a ton of new images showing how their code doesn't work, the server is down or even the programming language is broken or annoying. ๐Ÿค”

This particular meme comes from Javascript enviroments inside web and application development.

Javascript lack variable types, so casting, parsing and all that stuff is pretty tough

So someone discovered that using the default parseInt(); function with a number 0.0000005 returns the 5 as result instead of 0.

Ok, but how is that even possible? ๐Ÿ’ญ

To solve this mistery I make two scripts in javascript and python that share the same logic.

Python uses int() to parse so I use it here. But I realized that the function is protected against using a float as an input, showing the following error.

Ok so, thats it, javascript is broken ๐Ÿ”ฅ๐Ÿ’”

Maybe this is not that simple.

Okay so python is protected. But I solve this issue using float() function and now is running:

Code:

Output:

The output is showing, but using scientific notation

Getting closer to the solution ๐Ÿ’ก

SO! python is using another notation when parsing number is small enought. Let's try parsing with parseFloat() in javascript instead.

Excellent! The number is shown in the correct way now. BUT IN SCIENTIFIC NOTATION

Okay but what's Javascript doing inside the getInt() function? ๐Ÿ’ป

That's the funny part, it seems that javascript is using the parseFloat() function that returns 5e-7 and then getting the first numbers before the 'ilegal characters'

We can see this behaivour here with the following snipet:

Code:

Output:

The conclusion ๐Ÿ’ฌ

Using javascript parseInt() to parse a float inside a String is extremelly incorrect. You MUST be using parseFloat() and then trunc the number if you want.

So using the right tools to do the right things, that's the key.

How amazing is that?

I hope you enjoy this experiment!๐Ÿงช

  • Akrck02