javascript tutorial - [Solved-5 Solutions] parseInt - javascript - java script - javascript array
Problem:
Why does parseInt(1/0, 19) return 18 ?
Solution 1:
Solution 2:
- The result of
1/0
is Infinity. - parseInt treats its first argument as a string which means first of all
Infinity.toString()
is called, producing the string "Infinity
". So it works the same as if you asked it to convert "Infinity
" in base 19 to decimal. - Here are the digits in base 19 along with their decimal values:
Solution 3:
Here's the sequence of events:
-
1/0
evaluates toInfinity
-
parseInt
readsInfinity
and happily notes that I is 18 in base 19 -
parseInt
ignores the remainder of the string, since it can't be converted.
Solution 4:
Solution 5:
parseInt(1/0,19)
is equivalent toparseInt("Infinity",19)
- Within base 19 numbers
0-9
andA-I (or a-i)
are a valid numbers. So, from the "Infinity" it takesI
of base 19 and converts to base 10 which becomes 18 Then it tries to take the next character i.e.n
which is not present in base 19 so discards next characters (as per javascript's behavior of converting string to number) - So, if we write
parseInt("Infinity",19)
ORparseInt("I",19)
OR vparseInt("i",19) the result will be same i.e18
. - Now, if we write
parseInt("I0",19)
the result will be342
asI X 19 (the base)^1 + 0 X 19^0
=18 X 19^1 + 0 X 19^0
=18 X 19 + 0 X 1
=342
- Similarly,
parseInt("I11",19)
will result in6518