Explore Courses Blog Tutorials Interview Questions
0 votes
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 (46k 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)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories