开发者

Javascript parsing int64

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.


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.


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.


Have you tried using the Number class?
var num = new Number(parseFloat(ThisInt))


Just use Number(ThisInt) for this instead of Int or float

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜