apex random number Salesforce

apex random number Salesforce

apex random number Salesforce

Many time we have requirement to generate random number in Apex. It can be achieved using Math.random() function. This method returnĀ a positive Double that is greater than or equal to 0.0 and less than 1.0.

This method only returns number between 0.0 and 1.0. Now its important how we can use this method to generate different variation of random number that we need based on our requirements. Lets see some examples of getting random number.

Get random number between 0 and 10 Apex

Integer randomNumber = Integer.valueof((Math.random() * 10));
System.debug('randomNumber  is'+randomNumber);

Get random number between 0 and 100 Apex

Integer randomNumber = Integer.valueof((Math.random() * 100));
System.debug('randomNumber is'+randomNumber);

Get random Boolean value Apex

Integer randomNumber = Integer.valueof((math.random() * 10));
Boolean randomBoolean = Math.mod(randomNumber,2) == 0 ? true : false;
System.debug('randomBoolean is'+randomBoolean);

Get random String from list of strings Apex

List<String> availableValues = new List<String>{'Red','Green','Blue','White','Black'};
Integer listSize = availableValues.size() - 1;
Integer randomNumber = Integer.valueof((Math.random() * listSize));
String randomString= availableValues[randomNumber];
System.debug('randomString is'+randomString);



Permanent link to this article: http://www.sfdcpoint.com/salesforce/apex-random-number-salesforce/