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: https://www.sfdcpoint.com/salesforce/apex-random-number-salesforce/

2 comments

    • Pablo on April 8, 2020 at 3:07 pm
    • Reply

    Great info, thanks!

    • Diego on April 22, 2022 at 3:27 pm
    • Reply

    There is an issue with the method you are using to round the randomised index here.

    You are using `Integer.valueOf()` which will always round down, e.g. `Integer.ValueOf(9.9)` will return `9`.

    This makes it so that the only way you will retrieve the last element of the list is if `Math.random()` returns 1 which is a lower probability than any other element.

    so if you try and run this:

    List listLetters = new List{‘a’,’b’,’c’,’d’,’e’,’f’,’g’};

    for(Integer i=0; i<1000; i++){
    Double random = Math.random();
    Integer randomIndex = Integer.valueOf((listLetters.size() – 1 ) * random);
    System.debug(listLetters[randomIndex]);
    }

    you will see that 'g' is returned a number of times that approximates zero, so it's not truly random.

    Using `Math.round()` does not make it better as the items at index 0 and and index max have exactly half the chance of being selected as the others.

    The reason this is happening is because you are removing 1 from the list size before converting it to percentages, whereas you should want to remove one percentage point from the end result, so the correct randomisation should be:

    `Integer randomNumber = Integer.valueOf((Math.random() * availableValues.size()) – 0.01)`

Leave a Reply

Your email address will not be published.