Minimum Field Width
In this chapter you will learn:
Specifying a Minimum Field Width
An integer between the %
sign and the format conversion code acts as a minimum field-width specifier.
The default padding is done with spaces.
If you want to pad with 0's, place a 0 before the field-width specifier.
For example, %05d
will pad a number of less than five digits
with 0's so that its total length is five.
The field-width specifier can be used with all format specifiers except %n
.
The following program demonstrates the minimum field-width specifier by applying it to the %f conversion:
The following code displays numbers in right justify format.
import java.util.Formatter;
//from j av a 2 s . co m
public class MainClass {
public static void main(String args[]) {
Formatter fmt = new Formatter();
// Right justify by default
fmt.format("|%10.2f|", 123.123);
System.out.println(fmt);
}
}
The output:
Produce formatted table
The minimum field-width modifier is often used to produce tables in which the columns line up.
import java.util.Formatter;
/*from j a v a 2 s . co m*/
public class Main {
public static void main(String args[]) {
Formatter fmt;
for (int i = 1; i <= 10; i++) {
fmt = new Formatter();
fmt.format("%4d %4d %4d", i, i * i, i * i * i);
System.out.println(fmt);
}
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- How to use precision modifier
- How to format decimal value in precision
- How to control the number of significant digits for %g
- How to control string length with precision specifier
Home » Java Tutorial » String