3

Did you ever try to convert a big number to a string in javascript?

Please try this:

var n = 10152557636804775;
console.log(n); // outputs 10152557636804776

Can you help me understand why?

Ram
  • 140,563
  • 16
  • 160
  • 190
Adriano Di Giovanni
  • 1,235
  • 1
  • 13
  • 30
  • 3
    `10152557636804775 > Number.MAX_SAFE_INTEGER === true` – Adriano Repetti Oct 24 '14 at 12:36
  • possible duplicate of [Why is JavaScript's number \*display\* for large numbers inaccurate?](http://stackoverflow.com/questions/25416544/why-is-javascripts-number-display-for-large-numbers-inaccurate) – Artjom B. Oct 24 '14 at 12:40
  • possible duplicate of [What is JavaScript's highest integer value that a Number can go to without losing precision?](http://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – user247702 Oct 24 '14 at 12:40

1 Answers1

3

10152557636804775 is higher than the maximum integer number that can be safely represented in JavaScript (it's Number.MAX_SAFE_INTEGER). See also this post for more details.

From MDN (emphasis is mine):

The MAX_SAFE_INTEGER constant has a value of 9007199254740991. The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1.

To check if a given variable can be safely represented as an integer (without representation errors) you can use IsSafeInteger():

var n = 10152557636804775;
console.assert(Number.isSafeInteger(n) == false);
Community
  • 1
  • 1
Adriano Repetti
  • 62,720
  • 18
  • 132
  • 197