gotchajavascriptCritical
Why does parseInt(1/0, 19) return 18?
Viewed 0 times
whydoesparseintreturn
Problem
I have an annoying problem in JavaScript.
Why does the
> parseInt(1 / 0, 19)
> 18Why does the
parseInt function return 18?Solution
The result of
Here are the digits in base 19 along with their decimal values:
What happens next is that
Therefore it behaves as if you called
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:
Base 19 Base 10 (decimal)
---------------------------
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
a 10
b 11
c 12
d 13
e 14
f 15
g 16
h 17
i 18
What happens next is that
parseInt scans the input "Infinity" to find which part of it can be parsed and stops after accepting the first I (because n is not a valid digit in base 19).Therefore it behaves as if you called
parseInt("I", 19), which converts to decimal 18 by the table above.Context
Stack Overflow Q#11340673, score: 1308
Revisions (0)
No revisions yet.