Reputation: 1
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
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
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
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