Java int type format add leading zero
//package com.demo2s; import java.text.DecimalFormat; public class Main { public static void main(String[] argv) throws Exception { int num = 2; System.out.println(addLeadingZero(num)); }//from ww w . jav a 2s . c o m public static String addLeadingZero(int num) { DecimalFormat df = new DecimalFormat("00000"); return df.format(num); } }
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String aString = ""; int aAmountOfZeros = 2; System.out.println(addLeadingZero(aString, aAmountOfZeros)); }/*from w w w . j a v a 2s. co m*/ public static String addLeadingZero(String aString, int aAmountOfZeros) { final int stringLength = aString.length(); if (stringLength < aAmountOfZeros) { for (int i = 0, l = aAmountOfZeros - stringLength; i < l; ++i) { aString = "0" + aString; } } return aString; } }
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { int integer = 2; System.out.println(addLeadingZeroIfNecessary(integer)); }//from w w w . ja v a 2s . co m public static String addLeadingZeroIfNecessary(int integer) { if (integer < 10) { return "0" + integer; } else { return "" + integer; } } }