Skip to main content

APIzation: Replication Package

[Q#473282][A#473309] How can I pad an integer with zeros on the left?

https://stackoverflow.com/q/473282

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).

Answer

https://stackoverflow.com/a/473309

Use java.lang.String.format(String,Object…) like this: for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x". The full formatting options are documented as part of java.util.Formatter.

APIzation

String.format("%05d", yournumber);
package com.stackoverflow.api;

public class Human473309 {

  public static String getStringFormatting(double yournumber) {
    return String.format("%05d", yournumber);
  }
}

package com.stackoverflow.api;

/**
 * How can I pad an integer with zeros on the left?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/473309">https://stackoverflow.com/a/473309</a>
 */
public class APIzator473309 {

  public static void padInteger(int yournumber) throws Exception {
    String.format("%05d", yournumber);
  }
}