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?
printf("\t%20s", "str"); To increase the amount of whitespace, make the number (20) higher.
%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"
"%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.
%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.
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
int i = 0;
while (i < 12) {
System.out.printf("%4d", i);
++i;
}
The 4 is the width. You could also replace printf with format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With