0 votes
1 view
in Java by (3.5k 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
by (46.1k 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.

Related questions

0 votes
1 answer
asked Jul 22, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
asked Aug 16, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !