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;
}
1
  • 2
    I prefer the xkcd method :) Commented Oct 30, 2013 at 8:27

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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?

1 Comment

remember to provide source if you copy from somewhere.
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)];

1 Comment

Thanks, I also wanted it to generate between 1 and 3, so what have i done wrong there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.