Q:

math.random javascript

// Between any two numbers
Math.floor(Math.random() * (max - min + 1)) + min;

// Between 0 and max
Math.floor(Math.random() * (max + 1));

// Between 1 and max
Math.floor(Math.random() * max) + 1;
12
//To genereate a number between 0-1
Math.random();
//To generate a number that is a whole number rounded down
Math.floor(Math.random())
/*To generate a number that is a whole number rounded down between
1 and 10 */
Math.floor(Math.random() * 10) + 1 //the + 1 makes it so its not 0.
25
function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min)) + min + 1;
}
5
Math.floor(Math.random() * 6) + 1  
14
function getRandomNumberBetween(min,max){
    return Math.floor(Math.random()*(max-min+1)+min);
}

//usage example: getRandomNumberBetween(20,400); 
25
var random;
var max = 8
function findRandom() {
  random = Math.floor(Math.random() * max) //Finds number between 0 - max
  console.log(random)
}
findRandom()
7
Math.floor((Math.random() * 100) + 1);
//Generate random numbers between 1 and 100
//Math.random generates [0,1)
10
function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
11
//Returns a number between 1 and 0
  console.log(Math.random());
  
//if you want a random number between two particular numbers, 
//you can use this function
  function getRandomBetween(min, max) {
    return Math.random() * (max - min) + min;
  }
//Returns a random number between 20 and 170
  console.log(getRandomBetween(20,170));
  
//if you want a random integer number from one number to another 
//(including the min and the max numbers), you can use this function
  function getRandomIntBetween(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  
//Returns a random integer number from 0 to 25
  console.log(getRandomIntInclusive(0,25));
6
var RandomNumber = Math.ceil(Math.random() * 100);              
// Returns a random number between 1 and 100
5
Math.random() 
// will return a number between 0 and 1, you can then time it up to get larger numbers.
//When using bigger numbers remember to use Math.floor if you want it to be a integer
Math.floor(Math.random() * 10) // Will return a integer between 0 and 9
Math.floor(Math.random() * 11) // Will return a integer between 0 and 10

// You can make functions aswell 
function randomNum(min, max) {
	Math.floor(Math.random() * (max - min)) + min; // You can remove the Math.floor if you don't want it to be an integer
}
1
function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; // max & min both included 
}
2

New to Communities?

Join the community