## Generating Random Numbers Using an Invocable Method

I’ve come across a handful of use-cases where I needed to generate random numbers in flows for things like random cohorting. I’m taking this as an opportunity to continue working on some “Admin Tools” scripts which would have saved me some time over the years.

The Class and Test Class above create an invocable method which can be used inside a flow to generate a random number within a range, and a specified number of decimal places.

Within the flow builder, the invocable looks like this:

You can enter a Lower Bound, which is the smallest number that the invocable will generate.

The Upper Bound is the largest number that the invocable will generate.

Scale is the number of decimal places.

For some examples of how this works:

Example 1:

- Lower Bound = 1
- Upper Bound = 10
- Scale = 0
- Result = 1, 2, 3, …, 8, 9, 10

Example 2:

- Lower Bound = 1
- Upper Bound = 10
- Scale = 1
- Result = 1.0, 1.1, 1.2, 1.3, … , 9.8, 9.9, 10.0

Example 3:

- Lower Bound = 1
- Upper Bound = 100
- Scale = -1
- Result = 10, 20, 30, …, 80, 90, 100

## Generating Random Numbers using Formulas

Sometimes using an invocable method is overkill and you just need something that appears random and doesn’t need to be particularly performant. For that, you can use a formula to generate a random number.

Taking inspiration from old random number generators which used nth digits of pi, I’ve written this formula which uses the same principle, and uses the record id and created dates as seeds to ensure uniqueness. Because these fields will exist on ALL records this solution is more portable than other random number generator formulas you might find on google.

If you need to change the number of returned values, you can simply change the number within the outer-most RIGHT() formula.

You’ll notice some ASCII(RIGHT(Id, #)) formulas being added together. This is because we expect these IDs to increment when the record is created, resulting in uniqueness across records, even those that are created in bulk. The ASCII formula converts the first text value in the string to a number. We don’t so much care what the result is, so much as that it translates letter values to numbers (which we can do math on!). The fact that it is case-sensitive is a nice bonus that enhances the “randomness”.

Note: The ASCII formula only processes the first character in the string, we’re using 3 of these in a row, grabbing 1 additional character each time. Since the formula only operates on the first character, it simply acts as though we’re grabbing the last 3 characters and performing some math on their ASCII value.