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?

Fraser
  • 15,275
  • 8
  • 53
  • 104
james li
  • 174
  • 1
  • 6

2 Answers2

5

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

Community
  • 1
  • 1
scessor
  • 15,995
  • 4
  • 43
  • 54
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

jfriend00
  • 683,504
  • 96
  • 985
  • 979