Home > Blockchain >  What property of Typescript's number or Math.ceil() causes this arithmetic error?
What property of Typescript's number or Math.ceil() causes this arithmetic error?

Time:10-20

I'm trying to create a function to generate a unique number every time using Typescript. The arithmetic is often incorrect for some reason. I've expanded the logic below and suspect that it has something to do with Typescript/Javascript's number type or Math.ceil(). I'd be grateful if someone could educate me.

function nonce(){
    const millidate = (new Date()).getTime();
    const factor:number = 10000;
    const codeTime:number =  millidate*factor;
    const codeEnd:number = Math.ceil(Math.random()*factor);
    const codeMult:number = Math.ceil(Math.random()*10);
    const codeBody:number = codeTime codeEnd;
    const code:number =  codeBody*codeMult;
    console.log("Breakdown of "   code   ": ", codeTime, codeEnd, codeBody, codeMult);
    return code;
};


nonce();

Image of some tests in Playground

Image of some tests in Playground

I was using Typescript's Playground to test this, but its performance seems to be the same across different environments.

CodePudding user response:

As pointed out in the comments, your numbers are way over the system limit. Number.MAX_SAFE_INTEGER on my 64-bit system:

9007199254740991 <- MSI
163469121917820770 <- your number

Dial it down, or make strings.

CodePudding user response:

To work with large numbers (more than Number.MAX_SAFE_INTEGER), you need to use BigInt()

Without BigInt:

9007199254740991   1 = 9007199254740992 // Right
9007199254740991   2 = 9007199254740992 // Wrong
9007199254740991   3 = 9007199254740994 // Right

Using BigInt:

9007199254740991n   1n = 9007199254740992n //Right
9007199254740991n   2n = 9007199254740993n //Right
9007199254740991n   3n = 9007199254740994n //Right
  • Related