3

I have found that some number when passing through parseInt are changing to other number.

console.log( parseInt( 10153315281647662, 10 ) ); //10153315281647662
console.log( parseInt( 10153315281647663, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647664, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647665, 10 ) ); //10153315281647664
console.log( parseInt( 10153315281647666, 10 ) ); //10153315281647666
console.log( parseInt( 10153315281647667, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647668, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647669, 10 ) ); //10153315281647668
console.log( parseInt( 10153315281647660, 10 ) ); //10153315281647660


var str = '{ "id" : 10153315281647663 }';
console.log(  JSON.parse( str ) ) // id : 10153315281647664

I was working with few large numbers and parseInt or changing str to JSON with number is changing the numbers in result. This is not becasuse of integer stack overflow because the larger numbers 10153315281647666 is parsing correctly while 10153315281647663 is not, what can be the reason behind this?

I have fixed the issue by parsing everything into string, but what is the cause of this?

developernaren
  • 514
  • 5
  • 20

2 Answers2

1

The number you're trying to parse is too large. It can't be reliably stored as double-precision floating-point

console.log(10153315281647663 > Number.MAX_SAFE_INTEGER);
console.log(10153315281647663);
console.log(Number.MAX_SAFE_INTEGER);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • But the results do not seem to be "unexpected" or even random. Some are being parsed correctly and some are not and the results are always exactly the same for a given number. Is there a reason behind that? – developernaren Nov 11 '16 at 13:11
  • @developernaren: That's because the least significant bit is lost. I'll (try to) add in an explanation. – Cerbrus Nov 11 '16 at 13:12
  • I can't really come up with a proper explanation without it resulting in a wall of text. Here's a better resource that explains why you're seeing the numbers you're seeing: http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html – Cerbrus Nov 11 '16 at 13:28
0

No need to parse the numbers it is just the end of the maximal possible count of places without loosing precision of the IEEE 754 format.

console.log(10153315281647662); //10153315281647662
console.log(10153315281647663); //10153315281647664
console.log(10153315281647664); //10153315281647664
console.log(10153315281647665); //10153315281647664
console.log(10153315281647666); //10153315281647666
console.log(10153315281647667); //10153315281647668
console.log(10153315281647668); //10153315281647668
console.log(10153315281647669); //10153315281647668
console.log(10153315281647660); //10153315281647660
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392