Blog

Generating random numbers in Apex / force.com

2

There are a few different ways to generate a random number(s) in Apex, so I thought it would be worth writing these up on here for those who are new to the language (and for my own benefit of course!). The first, most common approach is to use the Math standard class and call the random method:

Math.random();

This returns a positive Double that is greater than or equal to 0.0 and less than 1.0, with 16 decimal points. Sample output: 0.4996432128719458

You can easily create your own method as below:

public double getRandom() {
return Math.random();
}

If you then need to edit the number of decimal places returned, you can do this in your visualforce page altering the value formatting as desired. It’s also possible to get random numbers from the Crypto standard class, by using either getRandomInteger or getRandomLong. Note that unlike Math.random these methods can return negative values and are returned as an Integer:

Crypto.getRandomInteger();
Crypto.getRandomLong();

getRandomInteger, 10 characters. Sample ouput: -1799290961
getRandomLong, 19 characters. Sample output: 1762765866534117364

I’m sure this post could be expanded somewhat, but thats all for now – please feel free to add any comments / suggestions.