Search code examples
javascriptmathbigint

Precision issue when doing math with BigInts


I'm having a bit of a strange issue... I'm using an API that requires me to do a bit of math... I need to generate an integer using the following code:

import time

id = long((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000L) << 22
#Output using 1578430631.86 as timestamp: 659137523812925440

The issue is that the example is in python, and I'm using Javascript... I tried converting it to JS like this:

var ts = (new Date()).getTime() / 1000;
var id = (BigInt((ts - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22).toString();
//Output using 1578430631.86 as timestamp: 659137520205824000

As you can see the outputs differ, and that is a big issue. If someone can point me in the right direction, that would be really appreciated! Thanks in advance!


Solution

  • The issue is that you've converted the number to a BigInt when it has already lost precision.

    So convert everything to BigInts before you do math:

    var ts = BigInt((new Date()).getTime()) / 1000n;
    var id = ((ts - 14n * 24n * 60n * 60n) * 1000n - 1420070400000n << 22n).toString();
    //Output using 1578430631.86 as timestamp: 659137520205824000