trycatch4j
trycatch4j

Reputation: 83

Format String become xxx1, xx10 or 1###, 10## etc

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###

Upvotes: 8

Views: 5623

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533520

For a perverse answer.

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

prints

0010

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

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

Upvotes: 4

BoxOfNotGoodery
BoxOfNotGoodery

Reputation: 1001

Take a look at this

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

Upvotes: 7

Michael
Michael

Reputation: 35341

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

This prints "0010".

Upvotes: 13

Related Questions