0

Is there anybody could explain the reason why the following is happening in JavaScript?

let x212 = 154688977320418212;
// returns 154688977320418200

let x230 = 154688977320418230;
// returns 154688977320418240

let x256 = 154688977320418256;
// returns 154688977320418240

let x257 = 154688977320418257;
// returns 154688977320418270

Does it mean that there is no way to store long integer value, without converting it to string?

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
  • 1
    Those numbers are higher than `Number.MAX_SAFE_INTEGER` (`9007199254740991`) so, they are (as you can guess), not safe to use. You need a big number library and/or represent them as a string. – VLAZ Jan 08 '19 at 13:09

1 Answers1

1

In JavaScript, all numbers are 64 bits floating point numbers.

The size of the mantissa is about 53 bits, which means that your number, 154688977320418257, can't be exactly represented as a JavaScript number. What you see is an approximation, because it's a number higher than MAX_SAFE_INTEGER (i.e 9007199254740991).

If you really need big numbers, you could use a lib such as https://github.com/peterolson/BigInteger.js.

rap-2-h
  • 30,204
  • 37
  • 167
  • 263