# Best way of generating a random number

In order to get fake IDs for testing needs I wrote something that works and is reusable, but I'd like to know if there is better ways because my code seems heavy.

n is the total caracters of the string I want.

First, I think about the conversion between number and strings I could do better.

Got some ideas ?

``````final integer STRING_LENGTH = 14;
String aleaNumberN=String.valueOf((integer)(Math.ceil(Math.random()*9)));
for(integer j = 1; j<n; j++) {
aleaNumberN += String.valueOf((integer)(Math.ceil(Math.random()*9)));
}
System.debug('aleaNumberN ? --> ' + aleaNumberN);
System.assert(aleaNumberN.length()==STRING_LENGTH);
``````
• Also, should I let the System.assert(condition) ? Or is it a best practise to have assertions only in test classes ? And is STRING_LENGTH well declared, as a final variable ? Commented Sep 20, 2018 at 10:05
• Asserts should generally only be in test methods, or while testing code. Final variables are constants, and typically used for that purpose.
– sfdcfox
Commented Sep 20, 2018 at 11:27

``````final integer STRING_LENGTH = 3;
final integer MIN = Math.pow(10,STRING_LENGTH -1); //Returns 100
final integer MAX = Math.pow(10,STRING_LENGTH) - 1; // Returns 999
String aleaNumberN = String.valueOf(Math.Round(Math.Random() * (MAX-MIN) + MIN));
``````

If you replace some vars:

``````final integer STRING_LENGTH = 3;
String aleaNumberN = String.valueOf(Math.Round(Math.Random() * ((Math.pow(10,STRING_LENGTH) - 1)-Math.pow(10,STRING_LENGTH -1)) + Math.pow(10,STRING_LENGTH -1)));
``````

Edit: Be carefull with string length, maybe using long is required

Update (Having 0's in the left):

``````final integer STRING_LENGTH = 3;
final integer MAX = Math.pow(10,STRING_LENGTH) - 1; // Returns 999
String aleaNumberN = String.valueOf(Math.Round(Math.Random() * MAX)).leftPad(STRING_LENGTH,'0');
``````
• Thanks ! The only thing I'd see, is that it's impossible to have a 0 in first character of the string. Also, you loose in lisibility when suppressing variables, is it better to have a more compact code, or to have one much more readable ? Is there a best practise about it ? Commented Sep 20, 2018 at 12:32
• I would completly go for readability. For some reason I thought you were seeking the most compact way. I have updated my answer with the possibility of having zeros in the left :) Commented Sep 20, 2018 at 12:35