Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does parseInt(1/0, 19) return 18?

I have an annoying problem in JavaScript.

> parseInt(1 / 0, 19) > 18 

Why does the parseInt function return 18?

like image 390
cebor Avatar asked Jul 05 '12 08:07

cebor


People also ask

What can I use instead of parseInt?

parseFloat( ) parseFloat() is quite similar to parseInt() , with two main differences. First, unlike parseInt() , parseFloat() does not take a radix as an argument. This means that string must represent a floating-point number in decimal form (radix 10), not octal (radix 8) or hexadecimal (radix 6).

Is parseInt fast?

Problem is parseInt seems to be very very slow (it's not the timeout issue, its set to 1). From what I can see, it seems to be skipping some data, so every now and then a band gets missed out. The only way I can fix this is to insert a delay between each coordinate being sent.


2 Answers

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:

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.

like image 164
Jon Avatar answered Sep 25 '22 21:09

Jon


Here's the sequence of events:

  • 1/0 evaluates to Infinity
  • parseInt reads Infinity and happily notes that I is 18 in base 19
  • parseInt ignores the remainder of the string, since it can't be converted.

Note that you'd get a result for any base >= 19, but not for bases below that. For bases >= 24, you'll get a larger result, as n becomes a valid digit at that point.

like image 35
Craig Citro Avatar answered Sep 22 '22 21:09

Craig Citro