developernaren developernaren - 27 days ago 9
Javascript Question

JSON parse converts certain number to somethig else

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?

Answer

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);