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

132
Views
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 answers
Answer question

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 Report

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 Report

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 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!