0 votes
1 view
ago in Java by (1.7k points)

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

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

1 Answer

0 votes
ago by (6.7k points)

I use  java.lang.String.format(String, Object...)  to pad an integer with zeros on the left like this:

String.format("%03d", mynumber);

for zero-padding with a length of 3. For hexadecimal output replace the d with an x as in "%03x".

To read more about this format click here.

...