Zero fill a string

Hi,

I'm converting an integer to a string, but always need it to be exactly four characters long, zero filling from the left. For example:

    Integer n = 25;
    String out  =   "00" + 25 ;    // "0025"

My integers will always be less than 5 characters long, I just need them to always be zero filled when less than 4 characters long. What can I do to accomplish it?

Thanks
   
DJ_AM_JuiceboxAsked:
Who is Participating?
 
Bart CremersConnect With a Mentor Java ArchitectCommented:

NumberFormat nf = new DecimalFormat("0000");
String out = nf.format(25);
System.out.println("out = " + out);

Open in new window

0
 
ysnkyCommented:

		 int n = 25;
		 String str = Integer.toString(n);
		 String desStr = "0000".substring(str.length()) + str;
		 
		 System.out.println(desStr);

Open in new window

0
All Courses

From novice to tech pro — start learning today.