force string made from integer to be n-digit

T

Thomas Jollans

Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
to "03"...? I will also need to do this with 4-digit numbers.

thomas
 
C

Christophe Vanfleteren

Thomas said:
Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
to "03"...? I will also need to do this with 4-digit numbers.

thomas

Something like:

int REQUIRED_LENGTH = 4;

String s = String.valueOf("5");
int sizeDiff = REQUIRED_LENGTH - s.size();

StringBuffer prefix = new StringBuffer();
for(int i = 0;i<sizeDiff;i++){
prefix.append("0");
}
prefix.append(s);

s = prefix.toString;


should work.
 
C

Carl Howells

Thomas said:
Is there a function (or way) to make 1 (an int) to "01", 16 to "16", 3
to "03"...? I will also need to do this with 4-digit numbers.

thomas

Take a look at java.text.DecimalFormat.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top