Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
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 Aug 16, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Jul 22, 2019 in Java by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...