Pick a number 1-10, randomly, with Apex
In the past when we’ve had to come up with a random number, we’ve leveraged the randomness of when the user performed an operation. We would look at the minute or second that a function ran to come up with a number that would be somewhat random.
There’s actually a much easier way to do this and it’s built-in to Apex. The below code will pick a random number out of a range that you set. It’s extremely simple, enjoy!
public Integer randomNumber(Integer range)
{
Double x = math.random() * range;
return x.intValue();
}
Related posts:



May 18th, 2009 at 8:12 pm
Umm, should your post really be called “Pick a number 0-9″?
May 18th, 2009 at 8:18 pm
Good point, math.random() will always return a decimal greater than or equal to 0.0 and less than 1.0. In the implementation for our client, we were using this to randomly select a record in a list which, as you know, has a first member starting at 0, so it worked well. For use outside of a list, then I would recommend adding 1 to the final result.