/*** @param in The integer value* @param fill The number of digits to fill* @return The given value left padded with the given number of digits*/public static String lPadZero(int in, int fill){
boolean negative = false;int value, len = 0;
if(in >= 0){value = in;} else {negative = true;value = - in;in = - in;len ++;}
if(value == 0){len = 1;} else{for(; value != 0; len ++){value /= 10;}}
StringBuilder sb = new StringBuilder();
if(negative){sb.append('-');}
for(int i = fill; i > len; i--){sb.append('0');}
sb.append(in);
return sb.toString();}
性能
public static void main(String[] args) {Random rdm;long start;
// Using own functionrdm = new Random(0);start = System.nanoTime();
for(int i = 10000000; i != 0; i--){lPadZero(rdm.nextInt(20000) - 10000, 4);}System.out.println("Own function: " + ((System.nanoTime() - start) / 1000000) + "ms");
// Using String.formatrdm = new Random(0);start = System.nanoTime();
for(int i = 10000000; i != 0; i--){String.format("%04d", rdm.nextInt(20000) - 10000);}System.out.println("String.format: " + ((System.nanoTime() - start) / 1000000) + "ms");}
NumberFormat formatter = new DecimalFormat("0000"); //i use 4 Zero but you can also another numberSystem.out.println("OUTPUT : "+formatter.format(811));
/**** @author Dinesh.Lomte**/public class AddLeadingZerosToNum {
/**** @param args*/public static void main(String[] args) {
System.out.println(getLeadingZerosToNum(0));System.out.println(getLeadingZerosToNum(7));System.out.println(getLeadingZerosToNum(13));System.out.println(getLeadingZerosToNum(713));System.out.println(getLeadingZerosToNum(7013));System.out.println(getLeadingZerosToNum(9999));}/**** @param num* @return*/private static String getLeadingZerosToNum(int num) {// Initializing the string of zeros with required sizeString zeros = new String("0000");// Validating if num value is less then zero or if the length of number// is greater then zeros configured to return the num value as isif (num < 0 || String.valueOf(num).length() >= zeros.length()) {return String.valueOf(num);}// Returning zeros in case if value is zero.if (num == 0) {return zeros;}return new StringBuilder(zeros.substring(0, zeros.length() -String.valueOf(num).length())).append(String.valueOf(num)).toString();}}