+ Start a Discussion
JaanuJaanu 

How to get the length of Integer field in Apex ?

I am generating random number of length 9 digits .. sometimes, the leading zero is dropped and I am getting less than 9 digits sometimes... so, I need to check the number length in apex ..if it;s less than 9 numbers I want to generate another one. How to get the length ?
Raj VakatiRaj Vakati

You are looking for DescribeFieldResult.getLength():



For string fields, returns the maximum size of the field in Unicode characters (not bytes).
 
Schema.DescribeFieldResult F = Account.AccountNumber.getDescribe();
Integer lengthOfField = F.getLength();

 
JaanuJaanu
Thanks Raj! I have defined the custom settings field .. where we need to enter the length of the random number (amximum 18). Based on this defination, I will generate the random number with that length. SO, I defined length as 9. So, I need to generate random number with 9 length. But sometimes, leading zero is getting dropped as it;s integer .. so, I have only 8 digits. But I need 9 digits length .. so, I want to check the random number length after generating .. if it's less .. then I need to generate another one ..in loop. How do I find the length . it's not a field on the custom object ..it's generated in Apex class ...temp variable basically.
PARAG BHOR 19PARAG BHOR 19
First convert the integer to string using string.ValueOf(integerValue). Then check if the length of the string is 9 or not . If not you can do your further code.

string p = string.ValueOf(intValue);
if(p.length() < 9){
      // Here wil be your code
}