Javascript parsing int64

前端 未结 5 1226
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题