Javascript parsing int64

Oppdal picture Oppdal · Mar 18, 2011 · Viewed 40.9k times · Source

How can I convert a long integer (as a string) to a numerical format in Javascript without javascript rounding it?

var ThisInt = '9223372036854775808'
alert(ThisInt+'\r' +parseFloat(ThisInt).toString()+'\r' +parseInt(ThisInt).toString());

I need to perform an addition on it before casting it back as a string & would prefer not to have to slice it two if at all possible.

Answer

Alnitak picture Alnitak · Mar 18, 2011

All Numbers in Javascript are 64 bit "double" precision IEE754 floating point.

The largest positive whole number that can therefore be accurately represented is 2^53 - 1. The remaining bits are reserved for the exponent.

Your number is exactly 1024 times larger than that, so loses 3 decimal digits of precision. It simply cannot be represented any more accurately.

In ES6 one can use Number.isSafeInteger( # ) to test a number to see if its within the safe range:

var ThisInt = '9223372036854775808'; 
console.log( Number.isSafeInteger( parseInt( ThisInt ) ) );

There is also a BigInteger library available which should be able to help, though, and avoid you having to do all the string and bit twiddling yourself.

EDIT 2018/12 there's now a native BigInt class (and new literal syntax) landed in Chrome and NodeJS.