function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC_EvolveSFDC_Evolve 

Need Code to Generate 10 digit random number

Double N = math.random()*1000000000;
Long l = integer.valueof(N)*100;
string SNumber = string.valueof(l);

 

I have to insert that in a Text (External Id) fields.

 

Thanks 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
SFDCpassionSFDCpassion

try this :

 

system.debug(crypto.getRandomLong()+'***');

All Answers

SFDCpassionSFDCpassion

try this :

 

system.debug(crypto.getRandomLong()+'***');

This was selected as the best answer
jwhartfieldjwhartfield

Here is a more convoluted way that I came up with.  It impresses the ladies. ;-)

 

   public static string GenerateRandomNumber(integer length) {
    	string result = '';
    	while(result.length() < length){
    	     blob privateKey = crypto.generateAesKey(256);
	     string randomString = EncodingUtil.base64Encode(crypto.generateMac('hmacSHA512',privateKey,privateKey));
	     result += randomString.replaceAll('[^0-9]','');
    	}
        result = result.substring(0,length);
        return result;
    }

 

By the way, with a little tweak, this is also an great way just to get a really long random GUID-like string.  I use it to make security tokens.

 

// Builds a GUID-like token
    public static string GenerateGUID() {
    	blob privateKey = crypto.generateAesKey(256);
	string randomString = EncodingUtil.base64Encode(crypto.generateMac('hmacSHA512',privateKey,privateKey));
        randomString = randomString.ReplaceAll('[^\\w]','');
        //White spaces
        randomString = randomString.ReplaceAll('\\s', '');
	return randomString;
    }