Large Binary Numbers in Javascript

Have you ever wondered what the largest number is?  At one point it was a googolplex, but unless you write a custom class to deal with really large numbers, your dev environment will never count to a googolplex.

For http://loc.is I am reworking a geohash encoding algorithm today, and I wanted to see what Javascript could handle.  Strongly typed languages like Java have known upper limits, but languages like javascript are a bit more mysterious, so the only way to know is to find out.  I wrote this function to test it, and I ran it in the firebug console on a random webpage ( firebug won’t work unless the DOM is ready ).

for( i = 0 ; i < 500 ; i++){
    var value = Math.pow(2,i) +1;
    console.log (   i + "n" +
    value + "n" +  
    value.toString(2));
}

The output finally looks like this, and reveals that 2^52 is the largest number you can add 1 to and still represent it as an integer. Any larger and javascript will just use it as a float, and you will not have a sufficient number of bits to represent it.  I wonder if this is the same in all browser/ os combination pairs?

51
2251799813685249
1000000000000000000000000000000000000000000000000001

52
4503599627370497
10000000000000000000000000000000000000000000000000001

53
9007199254740992
100000000000000000000000000000000000000000000000000000

54
18014398509481984
1000000000000000000000000000000000000000000000000000000

So in this circumstance, javascript seems to have 54 bits of integer accuracy, a few short of a LONG 64 bit int, or IEEE 80 bit notation.


Test it yourself, and let me know.

Comments are closed.

Post Navigation