简体   繁体   中英

Number of bits in Javascript numbers

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 ?

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.

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

在此处输入图像描述

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

Welcome to Javascript!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM