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

140
Visualizações
How to generate a random number from 2 numbers

I've searched a lot for generating a random number but all I got is generating for a range between a or b.

I'm trying to get a number from a or b, i.e. either a or b, none from in between.

This returns the first value only var number = 1 || 9; \\9

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

So Math.random() randomly generates a number between 0.0 and 1.0. Math.random() < 0.5 has a 50% percent chance of either being true or false. This way you can select one of two numbers with equal probability.

let number = Math.random() < 0.5 ? 1 : 9;
console.log(number)

about 4 years ago · Santiago Gelvez Relatório

0

You can store your two numbers in an array and get a random index of that array. Here's an example:

var yourTwoNumbers = [2,5]
console.log(yourTwoNumbers[Math.floor(Math.random() * yourTwoNumbers.length)]);

about 4 years ago · Santiago Gelvez Relatório

0

The same asked here: How to decide between two numbers randomly using javascript?

There is already an answer with explanations.

The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.

const value1 = 1
const value2 = 9;
const chosenValue = Math.random() < 0.5 ? value1 : value2;
console.log(chosenValue)

about 4 years ago · Santiago Gelvez 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