0

Ive used math.random() to create a random number, but i want it to be an integer and not have any decimal places heres what ive got for it:

var RandomNumber = function RandomNumber13() {
return Math.random() * (3 - 1) + 1;
}

3 Answers3

3
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
Stefan
  • 5,644
  • 4
  • 24
  • 31
2

Change:

return Math.random() * (3 - 1) + 1;

to

return Math.floor(Math.random() * 3 + 1);

in order to have random integer between 1 to 3.


Update:

For generating random number among 1, 2 or 3, you can also use this:

var numbers = [1,2,3];
return numbers[Math.floor(Math.random() * numbers.length)];
Raptor
  • 53,206
  • 45
  • 230
  • 366
2

Try this, with floor()

/**
 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

Floor : Round a number downward to its nearest integer

Source from Generating random whole numbers in JavaScript in a specific range?

Community
  • 1
  • 1
Donovan Charpin
  • 3,567
  • 22
  • 30