+ Start a Discussion
Fajer NaqeebFajer Naqeeb 

Random number generator in apex

Danish HodaDanish Hoda
Hi Fajer,

You can generate a random number between 0 and 1000 with below method using Math class as below:
Integer IntrandomNumber = Integer.valueof((Math.random() * 1000));

If you want to generate a random string, plz refer the post: https://thesalesforcedev.blogspot.com/2019/12/generate-random-string-in-apex-public.html
Fajer NaqeebFajer Naqeeb
Hi Danish,
How can i populate new custom field with the random number generated by this script
Danish HodaDanish Hoda
Yes, ofcourse
Fajer NaqeebFajer Naqeeb
I am a beginner and I know nothing about how to write code in apex but I have one field name as random which should automatically generate one number populate that field how can i accomplish it.
Danish HodaDanish Hoda
If you want that on record creation, you can refer writing below trigger:
//Assuming Obj__c is the Object's API Name and random__c is the field's name

Trigger ObjTrigger on Obj__c (before insert){        
		
		for(Obj__c obj : Trigger.New){
			Integer IntrandomNumber = Integer.valueof((Math.random() * 1000));	//generates a random number from 0 to 1000
			obj.random__c = IntrandomNumber;
			IntrandomNumber += 1;
		}
}

 
Fajer NaqeebFajer Naqeeb
so instead of writing apex class i can write trigger only
Fajer NaqeebFajer Naqeeb
Hi Danish,
I wrote code under triggers it worked fine but Its giving an error as the datatype for the random field is text. so can I convert the output to string/ text so as to avoid decimal values.
 
Danish HodaDanish Hoda
Hi Fajer,
You can change the line #7 as below:

obj.random__c = String.valueOf(IntrandomNumber);