Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers with leading spaces in Java

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?

like image 321
user3437460 Avatar asked Mar 20 '14 17:03

user3437460


People also ask

How do you add leading spaces in Java?

printf("\t%20s", "str"); To increase the amount of whitespace, make the number (20) higher.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What is %- 5d in Java?

"%5d" Format a string with the required number of integers and also pad with spaces to the left side if integers are not adequate. "%05d" Format a string with the required number of integers and also pad with zeroes to the left if integers are not adequate.

How does %D work in Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.


2 Answers

    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

like image 146
Raul Guiu Avatar answered Sep 25 '22 08:09

Raul Guiu


int i = 0;
while (i < 12) {
    System.out.printf("%4d", i);
    ++i;
}

The 4 is the width. You could also replace printf with format.

like image 42
user176692 Avatar answered Sep 22 '22 08:09

user176692