How can I convert a long integer (as a string) to a numerical format in Javascript without javascript rounding it?
var ThisInt = \'9223372036854775808\'
aler
With a little help from recursion, you can directly increment your decimal string, be it representing a 64 bit number or more...
/**
* Increment a decimal by 1
*
* @param {String} n The decimal string
* @return The incremented value
*/
function increment(n) {
var lastChar = parseInt(n.charAt(n.length - 1)),
firstPart = n.substr(0, n.length - 1);
return lastChar < 9
? firstPart + (lastChar + 1)
: firstPart
? increment(firstPart) + "0"
: "10";
}
You cannot do this with standard Javascript. But as always, there is a nifty little library to help us out, in this case BigInt.js, which will let you use arbitrary-precision integers.
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.
Just use Number(ThisInt) for this instead of Int or float
Have you tried using the Number class?
var num = new Number(parseFloat(ThisInt))