How to generate a random number using Rand() and RandBetween() function in Canvas App

Sending
User Review
0 (0 votes)

Introduction

In this blog, we will learn how we can create one random color in RGBA format by generating random numbers.

Problem:

We have a Canvas App, where we have created one Display Form. Here, we have displayed the list of categories of All Accounts in the color-coded format as shown in the below screenshot. In the below screen we want categories of all Accounts to be shown in color-coded format, so it is necessary to display all categories of Accounts in Unique colors. For this, we want to generate random colors for each industry and assign them to a specific category.

Canvas App

Solution:

We can generate the random color using Rand() or RandBetween() function in Canvas App. Please find the below syntax for the above function.

Syntax:

Rand() = This function will generate one random number greater than 0 but less than 1. For example 0.26786, 0.65784.

RandBetween(START_RANGE, END_RANGE) = This function will return the whole number between the range that we provide to the function.

Where,

  1. START_RANGE – It is a numeric value that states the starting range of the random number which we want to generate.
  2. END_RANGE – It is a numeric value that state the ending range of the random number which we want to generate.

Note: After applying the above Power Fx function, one whole number will be generated between the range that we provide to the RandBetween() function.

Please find the below Power Fx formulas that we have used to generate the random color for each category checkbox.

UpdateContext({red:RandBetween( 0, 99 )});

UpdateContext({green:RandBetween( 0, 99 )});

UpdateContext({blue:RandBetween( 0, 99 )});

In the above code we have generated the three random numbers for each industry and assigned a color to that category legend by using generated numbers in RGBA format as shown in the above screenshot:

RGBA(red,green,blue,1)

Conclusion:

In this way, by using Rand() or RandBetween() function we can create or generate a random number to process any operation in Canvas App.