views:

148

answers:

4

Hi all,

I have following numbers : 1, 2, 3, 4, 10

But I want to print those numbers like this:

0001
0002
0003
0004
0010

I have searched in Google. the keyword is number format. But I've got nothing, I just get, format decimal such ass 1,000,000.00. I hope you can suggest me a reference or give me something to solve this problem.

Thanks

Edit, we can use NumberFormat, or String.format("%4d", somevalue); but it just for adding 0 character before integer. How If I wanna use character such as x, # or maybe whitespace. So the character become: xxxx1 xxx10 or ####1 ###10 or 1#### 10###

+10  A: 
NumberFormat nf = new DecimalFormat("0000");
System.out.println(nf.format(10));

This prints "0010".

Michael Angstadt
+6  A: 

Take a look at this

What you want to do is "Pad" your result.
e.g. String.format("%04d", myValue);

JohnFly
+4  A: 

You can use String.format();

public static String addLeadingZeroes(int size, int value)
{
    return String.format("%0"+size+"d", value);
}

So in your situation:

System.out.println(addLeadingZeroes(4, 75));

prints

0075
Martijn Courteaux
I think it would read more natural: `"...Zeroes( int zeros, int value ) "` to be used like: `addLeadingZeroes( 4, 75 )`
OscarRyz
@Oscar: I don't think so. Because you can pass `4` for size and `75` for value. Then you will have only two zeroes and not four.
Martijn Courteaux
Maybe, but reading `addLeadingZeroes( 75, 4 )` gives me the impression there would be 74 zeros in front of the number 4. :-/ Mangst answer makes sense :)
OscarRyz
@Oscar: Oh, that is what you mean. Better?
Martijn Courteaux
Yes, ...........
OscarRyz
A: 

For a perverse answer.

int i = 10;
System.out.println((50000 + i + "").substring(1));

prints

0010
Peter Lawrey