2

Can I write a batch apex to trim leading zeros from couple of fields. There are 2 number fields with around 1 million records with leading zeros.

Batch apex or any other way? Which should be much faster? Also do we have any apex methods that would handle the trimming part.

Thanks.

1
  • If you export data in excel and open the excel the leading zeros will be removed i guess and then you can update.Or One can also write macro in excel to do this Jan 20 '14 at 14:11
0

You could do this through a formula field or workflow field update also. if Raw_Number__c is your numeric Text field, this would be the formula for the same number with no leading zeroes:

TEXT( VALUE( Raw_Number__c ) )
2
  • The field will be converted from integer to string right here ? Jan 20 '14 at 14:32
  • Yes. The VALUE() OF "000123" (Text) is 123 (Number). Then this is converted back to "123" (Text). Jan 21 '14 at 14:27
3

You could also cast to integer and back to string to drop leading zeros.

String.valueOf(Integer.valueOf('00012'));
1
  • Yes. It is Working.
    – Anitha J J
    Mar 28 '16 at 11:54
1
 public class dropLeadingzero{

//removes leading zeros from a passed string 
public static Integer drop_leading_zeros(String passedValue) {
    String return_string = null; //return string for passing back
    if (passedValue != null) { //if the passed value is not null
        return_string=passedValue;
            if (return_string.startsWith('0') && return_string.length() > 1) { //if the string begins with a 0 and the length is greater than 1
                boolean keepChecking = true; //create a boolean variable
                while (keepChecking) { //if boolean is true
                    if (return_string.startsWith('0') && return_string.length() > 1) { //if the string begins with 0 and there is more than 1 character
                        return_string = return_string.substring(1); //drop the first character
                    } else { //either the string doesn't begin with 0 or the length is less than or equal to 1
                        keepChecking = false; //stop the loop
                    }
                }
            if (return_string == '0') { //if the resulting string is now a single '0'
                return_string ='0'; //set the string to null
            }
        } else { //otherwise the value passed was not valid
            return_string = passedValue; //set the string to null
        }
    }
    return Integer.valueof(return_string); //pass back a value
  }

}

Integer i=dropLeadingzero.drop_leading_zeros(String.valueof(00012));
system.debug('***'+i);

This is one of the solutions and i am sure there will be lot of other solutions as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.