How do I add left-padded zeros to a number in Java?

23,997

Solution 1

Try this:

String formattedNumber = String.format("%08d", number);

Solution 2

You can also use the class DecimalFormat, like so:

NumberFormat formatter = new DecimalFormat("00000000");
System.out.println(formatter.format(100)); // 00000100

Solution 3

Yet another way. ;)

int x = ...
String text = (""+(500000000 + x)).substring(1);

-1 => 99999999 (nines complement)

import java.util.concurrent.Callable;
/* Prints.
String.format("%08d"): Time per call 3822
(""+(500000000+x)).substring(1): Time per call 593
Space holder: Time per call 730
 */
public class StringTimer {
    public static void time(String description, Callable<String> test) {
        try {
            // warmup
            for(int i=0;i<10*1000;i++)
                test.call();
            long start = System.nanoTime();
            for(int i=0;i<100*1000;i++)
                test.call();
            long time = System.nanoTime() - start;
            System.out.printf("%s: Time per call %d%n", description, time/100/1000);
        } catch (Exception e) {
            System.out.println(description+" failed");
            e.printStackTrace();
        }
    }

    public static void main(String... args) {
        time("String.format(\"%08d\")", new Callable<String>() {
            int i =0;
            public String call() throws Exception {
                return String.format("%08d", i++);
            }
        });
        time("(\"\"+(500000000+x)).substring(1)", new Callable<String>() {
            int i =0;
            public String call() throws Exception {
                return (""+(500000000+(i++))).substring(1);
            }
        });
        time("Space holder", new Callable<String>() {
            int i =0;
            public String call() throws Exception {
                String spaceHolder = "00000000";
                String intString = String.valueOf(i++);
                return spaceHolder.substring(intString.length()).concat(intString);
            }
        });
    }
}

Solution 4

String.format uses a format string which is described here

Solution 5

If Google Guava is an Option:

String output = Strings.padStart("" + 100, 8, '0');

Alternatively Apache Commons Lang:

String output = StringUtils.leftPad("" + 100, 8, "0");
Share:
23,997
Stig Christian
Author by

Stig Christian

Updated on September 21, 2020

Comments

  • Stig Christian
    Stig Christian almost 4 years

    I have an integer 100, how do I format it to look like 00000100 (always 8 digits long)?

  • João Silva
    João Silva about 14 years
    +1 for the creative, though slow solution :-).
  • polygenelubricants
    polygenelubricants about 14 years
    Doesn't work with negatives, though.
  • Vishy
    Vishy about 14 years
    You might find it not as slow as other solutions, and the behaviour isn't defined for negatives. Just like the other solutions, there will be a non DDDDDDDD, where D is a digit, output for negative numbers.
  • Tomasz Gutkowski
    Tomasz Gutkowski over 6 years
    Each time it is called a new formater instance is created. So I have to admit that with large amounts of data it can cause big memory problems.