Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

438
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda