Add leading zeroes to number in Java? [duplicate]

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 – to pad with zeros
  • 3 – to set width to 3

Leave a Comment