Javascript parsing int64

前端 未结 5 1200
盖世英雄少女心
盖世英雄少女心 2020-12-03 17:19

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

var ThisInt = \'9223372036854775808\'
aler         


        
相关标签:
5条回答
  • 2020-12-03 17:55

    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";
    }
    
    0 讨论(0)
  • 2020-12-03 17:56

    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.

    0 讨论(0)
  • 2020-12-03 17:57

    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.

    0 讨论(0)
  • 2020-12-03 17:58

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

    0 讨论(0)
  • 2020-12-03 18:01

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

    0 讨论(0)
提交回复
热议问题