Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

424
Views
What property of Typescript's number or Math.ceil() causes this arithmetic error?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!