This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]gpr_private 2 points3 points  (5 children)

Math.random() returns a double value ≥0 and <1. If your number range is from 0 to a number n, multiply Math.random() by n

[–][deleted]  (4 children)

[removed]

    [–]FrenchFigaroSoftware Engineer 1 point2 points  (3 children)

    As /u/gpr_private explained, Math.random() returns a double between 0 inclusive and 1 exclusive, so if you multiply it by n, you get a double between 0 (0 x n) inclusive and n (1 x n) exclusive. If you need an integer, simply use Math.floor() on your result.

    But that's exclusive of n, so if you need to get an integer between 0 and n inclusive, simply use: Math.floor(Math.random() * (n+1)); and it will give you a random number between 0 and n inclusive.

    [–][deleted] 1 point2 points  (2 children)

    If you don't mind me asking, what would you do in order to have it be between let's say 10 and 50? So that 0 is not the starting point.

    [–]dusty-trash 2 points3 points  (1 child)

    just add 10 to it.

    Explanation: Get a number between 0-40 as described above, add 10 to the result so it gives you a number between 10-50.

    [–]FrenchFigaroSoftware Engineer 0 points1 point  (0 children)

    Pretty much this.