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?

3

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.