We can use a precision specifier with %f, %e, %g, and %s format specifiers.
It follows the minimum field-width specifier with a period followed by an integer.
Its meaning is depending upon the type of data.
For floating-point data using the %f or %e specifiers, it sets the number of decimal places displayed.
For example, %10.4f displays a number at least ten characters wide with four decimal places.
For %g, the precision determines the number of significant digits.
The default precision is 6.
For strings, the precision specifier specifies the maximum field length.
For example, %5.7s displays a string of at least five and not exceeding seven characters long.
If the string is longer than the maximum field width, the end characters will be truncated.
The following program illustrates the precision specifier:
// Demonstrate the precision modifier. import java.util.*; public class Main { public static void main(String args[]) { Formatter fmt = new Formatter(); // Format 4 decimal places. fmt.format("%.4f", 12345.1234567); System.out.println(fmt); //from w w w . ja v a 2s. co m fmt.close(); // Format to 2 decimal places in a 16 character field. fmt = new Formatter(); fmt.format("%16.2e", 12345.1234567); System.out.println(fmt); fmt.close(); // Display at most 15 characters in a string. fmt = new Formatter(); fmt.format("%.15s", "demo2s.com has many examples."); System.out.println(fmt); fmt.close(); } }