Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this is true: parseInt(1111111111111111,2) === parseInt(11111111111111111,2)

Tags:

javascript

This question is simply to curiosity.

Via console

parseInt(1111111111111111,2) // 16 1's

returns

65535

and

parseInt(11111111111111111,2) // 17 1's

returns

65535

Also

//          16 1's                           17 1's
if(parseInt(1111111111111111,2) === parseInt(11111111111111111,2))

returns

true

Where is the trick?

Thanks

like image 695
Federico Avatar asked Apr 06 '15 20:04

Federico


1 Answers

11111111111111111 is a decimal number literal for a number that is too large for Javascript to encode precisely.

parseInt(, 2) will stop at the first character that isn't 1 or 0, so it stops parsing once the precision degrades.

Change that to a string and you'll be fine.

like image 192
SLaks Avatar answered Nov 11 '22 22:11

SLaks