I've read an article about JavaScript parseInt, which had this question:
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(0.0000005); // => 5
Why is this happening?
Based on ecmascript standard:
The
parseInt
function produces an integralNumber
dictated by interpretation of the contents of thestring
argument according to the specified radix.
Part1 - Converting 0.0000005
to string
:
The first step of parseInt function is converting the input to string if it is not:
19.2.5 parseInt ( string, radix )
When the parseInt function is called, the following steps are taken:
Let inputString be ? ToString(string).
- Let S be ! TrimString(inputString, start).
...
In each case, the string output is as follows:
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'
Part2 - Converting 5e-7
to integer
:
So, it means 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.
So the answer will return 5
only because it is the only character which is a number till a noncharacter e
, so the rest of it e-7
will be discarded.
Thanks to @jcalz, I should mention that:
Don't use
parseInt(x)
forx
that isn’t astring
. If you already have anumber
presumably you wantMath.round()
orMath.floor()
or something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With