Number to string conversion error in javascript

Have you ever tried converting a large number to a string in javascript?

Please try the following:

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

      

Can you help me understand why?

+3


source to share


1 answer


10152557636804775

above the maximum integer that can be safely represented in JavaScript (it is Number.MAX_SAFE_INTEGER

). See also this post for more details.

From MDN (emphasis mine):

The MAX_SAFE_INTEGER constant has the value 9007199254740991. The rationale for this number is that JavaScript uses double precision floating point 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 (no presentation errors), you can use IsSafeInteger()

:

var n = 10152557636804775;
console.assert(Number.isSafeInteger(n) == false);

      

+3


source







All Articles