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

341
Visualizações
generate 4 digit random number using substring

I am trying to execute below code:

var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);

I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

That's because a is a number, not a string. What you probably want to do is something like this:

var val = Math.floor(1000 + Math.random() * 9000);
console.log(val);

  • Math.random() will generate a floating point number in the range [0, 1) (this is not a typo, it is standard mathematical notation to show that 1 is excluded from the range).
  • Multiplying by 9000 results in a range of [0, 9000).
  • Adding 1000 results in a range of [1000, 10000).
  • Flooring chops off the decimal value to give you an integer. Note that it does not round.

General Case

If you want to generate an integer in the range [x, y), you can use the following code:

Math.floor(x + (y - x) * Math.random());
over 4 years ago · Santiago Trujillo Relatório

0

This will generate 4-digit random number (0000-9999) using substring:

var seq = (Math.floor(Math.random() * 10000) + 10000).toString().substring(1);
console.log(seq);
over 4 years ago · Santiago Trujillo Relatório

0

I adapted Balajis to make it immutable and functional.

Because this doesn't use math you can use alphanumeric, emojis, very long pins etc

const getRandomPin = (chars, len)=>[...Array(len)].map(
   (i)=>chars[Math.floor(Math.random()*chars.length)]
).join('');


//use it like this
getRandomPin('0123456789',4);
over 4 years ago · Santiago Trujillo 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