tags:

views:

26365

answers:

6

How do you left pad an int with zeros in java when converting to a string?

I'm basically looking to pad out integers up to 9999 with the leading zeros.

E.g. 1 = "0001"

I know this is probably simple and as a parallel task I'm googling it, but SO is super quick when it comes to inane questions I should know the answer to...

A: 

pseudocode cause I haven't done java in a while but the following will work;

int number = whatever;

string num = (string)number;

while(num.length <4) num = "0" + num;

SnOrfus
Thats the inelegant way... Code must flow...
Omar Kooheji
Yuck. You're creating and throwing away 3 or 4 strings.
Paul Tomblin
Please ... be nice to your GC. Use a StringBuilder!
Mark Renouf
Maybe next time I'll think before I post. doh >|
SnOrfus
Wanna get a Peer Pressure badge?
asalamon74
oh! a Microsoft coder !
+4  A: 

Found this example... Will test...

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Tested this and:

String.format("%05",number);

Both work, for my purposes I think Stirng.Format is better and more succinct.

Cheers.

Omar Kooheji
Yes, I was going to suggest DecimalFormat because I didn't know about String.format, but then I saw uzhin's answer. String.format must be new.
Paul Tomblin
It's similar how you'd do it in .Net Except the .Net way looks nicer for small numbers.
Omar Kooheji
+68  A: 
String.format("%05d", yournumber);

for zero-padding with length=5.

see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html

Yoni Roit
Cheers that worksa charm and is more succinct than what I came up with.
Omar Kooheji
Then accept the answer, Omar.
Paul Tomblin
+7  A: 

If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

org.apache.commons.lang.StringUtils.leftPad(String str, int size)
Boris Pavlović
A: 
public class leftpadding {
public static void main(String[] args) {
    for (int i = 1; i < 10000; i++) {
        System.out.print(padded(i,5)+ " ");
}   
}
public static String padded(int x,int pad)
{
        String r="";
    for (int i=0; i<pad-(Integer.toString(x).length()); i++ )
    r+="0";
return r+x; 
}
}
A: 
public static final String zeroPad (int value, int size) {
  String s = "0000000000"+value;
  return s.substring(s.length() - size);
}