How to format numbers with leading spaces in Java

user3437460 picture user3437460 · Mar 20, 2014 · Viewed 27.9k times · Source

I have the following Java codes to generate numbers padded by zeroes.

    DecimalFormat fmt = new DecimalFormat("000");
    for (int y=1; y<12; y++)
    {
        System.out.print(fmt.format(y) + " ");
    }

The output is as follows:

001 002 003 004 005 006 007 008 009 010 011

My question is: how do I generate numbers with padded spaces instead of leading zeroes?

1 2 3 4 5 6 7 8 9 10 11

Note: I know there are several quesitons achieved in StackOverflow asking for padding spaces in String. I know how to do it with String. I am asking is it possible to format NUMBERS with padded space?

Answer

Raul Guiu picture Raul Guiu · Mar 20, 2014
    for (int y=1; y<12; y++)
    {
        System.out.print(String.format("%1$4s", y));
    }

It will print Strings of length 4, so if y=1 it will print 3 spaces and 1, " 1", if y is 10 it will print 2 spaces and 10, " 10"

See the javadocs