34

I work in Javascript with integer numbers only (mainly adding numbers and shifting them). I wonder how big they can be without loosing any bits.

For example, how big X can be such that 1 << X will represent 2^X ?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • 3
    Duplicate: http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-to – Dolph May 10 '10 at 13:35

3 Answers3

40

All numbers in JavaScript are actually IEEE-754 compliant floating-point doubles. These have a 53-bit mantissa which should mean that any integer value with a magnitude of approximately 9 quadrillion or less -- more specifically, 9,007,199,254,740,991 -- will be represented accurately.


NOTICE: in 2018 main browsers and NodeJS are working also with the new Javascript's primitive-type, BigInt, solving the problems with integer value magnitude.

Peter Krauss
  • 13,174
  • 24
  • 167
  • 304
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 3
    @Revanth: Almost! The maximum integer that can be represented accurately is `(2^53)-1` or `9,007,199,254,740,991`. In practice, `2^53` will evaluate as `9,007,199,254,740,992` but this isn't, in theory, an accurate representation because 1 bit of precision is missing, meaning that `2^53` is indistinguishable from `(2^53)+1`. – LukeH Sep 15 '15 at 11:11
14

All answers are partially wrong - Maybe due the new ES6/ES7 specs - , read why:

First of all, in JavaScript, the representation of the number is 2^53 - 1 that is true for @Luke answer, we can prove that by running Number.MAX_SAFE_INTEGER that will show a big number, then we do log2 to confirm that the number of bits is the same :

Number.MAX_SAFE_INTEGER
// 9007199254740991

Math.log2(9007199254740991)
// 53

enter image description here

However, Bitwise operation are calculated on 32 bits ( 4 bytes ), meaning if you exceed 32bits shifts you will start loosing bits.

Welcome to Javascript!

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Marwen Trabelsi
  • 4,167
  • 8
  • 39
  • 80
  • 1
    There are [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) to workaround in the ECMA standard, and now all modern browsers are using it. – Peter Krauss Jan 19 '19 at 17:42
6

All numbers in JavaScript are 64-bit (double-precision) floating point numbers.

Here's a description of the format and what values can and can't be represented with it.

Syntactic
  • 10,721
  • 3
  • 25
  • 25
  • 1
    Somehow it took me forever to understand why I kept seeing "53 bits of precision" but only 52 bits of storage space for the significand. That link answered the question, an implicit value of 1. – robyoder Apr 23 '16 at 07:18