I have just observed that the parseInt
function doesn't take care about the decimals in case of integers (numbers containing the e
character).
Let's take an example: -3.67394039744206e-15
> parseInt(-3.67394039744206e-15)
-3
> -3.67394039744206e-15.toFixed(19)
-3.6739e-15
> -3.67394039744206e-15.toFixed(2)
-0
> Math.round(-3.67394039744206e-15)
0
I expected that the parseInt
will also return 0
. What's going on at lower level? Why does parseInt
return 3
in this case (some snippets from the source code would be appreciated)?
In this example I'm using node v0.12.1
, but I expect same to happen in browser and other JavaScript engines.
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .
parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the , . parseFloat will parse a decimal number, but only understands .
Number() converts the type whereas parseInt parses the value of input. As you see, parseInt will parse up to the first non-digit character. On the other hand, Number will try to convert the entire string.
parseInt method as a parameter. The method throws an error if the string cannot be parsed into an integer. Note, that the code within the catch block is executed only if an exception is thrown. Let's make our integer parser a bit more useful.
I think the reason is parseInt
converts the passed value to string by calling ToString
which will return "-3.67394039744206e-15"
, then parses it so it will consider -3
and will return it.
The mdn documentation
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN
parseInt(-3.67394039744206e-15) === -3
The parseInt
function expects a string as the first argument. JavaScript will call toString
method behind the scene if the argument is not a string. So the expression is evaluated as follows:
(-3.67394039744206e-15).toString()
// "-3.67394039744206e-15"
parseInt("-3.67394039744206e-15")
// -3
-3.67394039744206e-15.toFixed(19) === -3.6739e-15
This expression is parsed as:
-
operator3.67394039744206e-15
.toFixed()
-- property accessor, property name and function invocationThe way number literals are parsed is described here. Interestingly, +/- are not part of the number literal. So we have:
// property accessor has higher precedence than unary - operator
3.67394039744206e-15.toFixed(19)
// "0.0000000000000036739"
-"0.0000000000000036739"
// -3.6739e-15
Likewise for -3.67394039744206e-15.toFixed(2)
:
3.67394039744206e-15.toFixed(2)
// "0.00"
-"0.00"
// -0
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