Oppdal - 3 months ago 26x

Javascript Question

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

**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. 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.

One can use `Number.isSafeInteger( # )`

to test for overflow:

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

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

Source (Stackoverflow)

Comments