Matt Brittain
Matt Brittain

Reputation: 1

I want to create a random integer with javascript

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;
}

Upvotes: 0

Views: 79

Answers (3)

Raptor
Raptor

Reputation: 54212

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)];

Upvotes: 2

Donovan Charpin
Donovan Charpin

Reputation: 3397

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?

Upvotes: 2

Stefan
Stefan

Reputation: 5672

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

Upvotes: 3

Related Questions