skip to Main Content

I have an issue where a string containing a 64 bit number, is being parsed by parseInt and some bits are lost in the process. my application uses ES5 and so BigInt is not available. How can I parse it as a number of 64 bit then under ES5?

str = "72057594044342942"
console.log(parseInt(str));

2

Answers


  1. If you want to introduce a new function into an older version of software, we apply so-called polyfills for that purpose.

    You can also find such a thing for BigInt on the internet.

    big-integer (npmjs.com)

    // Original example
    var str = "72057594044342942";
    var bigIntNum = bigInt(str);
    console.log('original', bigIntNum.toString());
    
    // Calculate
    console.log('+3', bigIntNum.add(3).toString());
    console.log('-3', bigIntNum.minus(3).toString());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.52/BigInteger.min.js" integrity="sha512-9Ep9DTmyYR7ilaRntBdTgdiAWg/hDjwbkgxjt04LAZdHWdo5k0eQoxmvdjz99hPSvh7R2M2LWk3DvaWer6f9mA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    Login or Signup to reply.
  2. In ECMA5, without BigInt, handling 64-bit numbers precisely is tricky. Since parseInt loses precision with such large numbers, consider using a library like bignumber.js or decimal.js. These libraries can handle large integers safely, even in environments without BigInt support. Just replace parseInt with the appropriate method from the library you choose. This workaround maintains precision for your 64-bit numbers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search