2

This has happens when I convert a large number to string in Javascript, it seems to give me a result which i do not expect:

var x=1234567890123456;

console.log(x) //1234567890123456 --equal...

console.log(x.toString()) //1234567890123456 --equal...

var x=12345678901234567;

console.log(x) // 12345678901234568 --different!

console.log(x.toString()) //12345678901234568 --different!

var x=123456789012345678;

console.log(x) //123456789012345680 --different!

console.log(x.toString()) //123456789012345680 --different!

console.log(x+"") //123456789012345680 --different!

Can anyone could tell me the reason for this, and how to deal with it?

2 Answers 2

5

The reason is the maximum of numbers in javascript (+/- 9007199254740992) without losing precision. Also see this question.

Sign up to request clarification or add additional context in comments.

Comments

3

Javascript does not have infinite numeric precision. There is a limit to the number of significant digits that it will keep track of in the 8 byte double precision floating point values.

See the actual ECMA Number spec section 8.5 for more specific details. Quoted from that spec:

Note that all the positive and negative integers whose magnitude is no greater than 2^53 are representable in the Number type

2^53 == 9007199254740992

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.