Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Big numbers are not represented accurately #2268

Closed
nourziady opened this issue Nov 3, 2019 · 2 comments
Closed

Big numbers are not represented accurately #2268

nourziady opened this issue Nov 3, 2019 · 2 comments
Labels

Comments

@nourziady
Copy link

  • Version:v10.16.0
  • Platform: Darwin MacBook-Pro.local 19.0.0 Darwin Kernel Version 19.0.0: Wed Sep 25 20:18:50 PDT 2019; root:xnu-6153.11.26~2/RELEASE_X86_64 x86_64

Issue is simple as

let int = 36028797018963973;
console.log(int) // 36028797018963976

how is that?

@Hakerh400
Copy link

JavaScript stores all numbers as double-precision binary IEEE 754 floating point values. Each number is internally stored on 64 bits: 1 bit for sign, 52 for mantissa and 11 for exponent. Given that it has limited number of bits available, it can therefore represent only a limited number of different values. Integers are just a small subset of that.

The maximal integer you can safely represent (without losing the precision) is Number.MAX_SAFE_INTEGER, whose value is 9007199254740991. You are trying to represent 36028797018963973, which is larger than max safe integer, so you lost precision. That is expected.

To solve the problem, you can use BigInt (simply add n to the end of your number).

@devsnek devsnek transferred this issue from nodejs/node Nov 3, 2019
@tniessen
Copy link
Member

As @Hakerh400 explained, this is a known deficiency of the number type in JavaScript. Representing your number as a binary sequence requires 56 bits, but the JavaScript number type cannot represent integers with more than 52 bits accurately. Sadly, the only true integer type provided by JavaScript is BigInt.

This is a common problem and appears to have been answered sufficiently.

@tniessen tniessen changed the title bug in assigning big numbers to variable Big numbers are not represented accurately Nov 15, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants