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:

  1. Converting Strings to Integers with Apex
  2. Properly Formatting Names in Apex
  3. Dynamic Queries with Apex
  4. Apex Describe with Dynamic SOQl
  5. No More Weekend Tasks

2 Comments to “Pick a number 1-10, randomly, with Apex”

  1. The EnforcerNo Gravatar Says:

    Umm, should your post really be called “Pick a number 0-9″? :)

  2. mkaufmanNo Gravatar Says:

    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.

Post a Comment