Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

437
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda