Specifying Precision
In this chapter you will learn:
- 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
Precision modifier
A precision specifier can be applied to the %f, %e, %g, and %s format specifiers and follows the minimum field-width specifier if there is one. A precision specifier consists of a period followed by an integer.
The precision specifier added to floating-point data using the %f or %e specifiers, the precision specifier determines the number of decimal places displayed.
import java.util.Formatter;
//from j a va 2 s. com
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
// Format to 2 decimal places in a 16 character field.
fmt = new Formatter();
fmt.format("%16.2e", 123.1234567);
System.out.println(fmt);
}
}
The output:
Specifying Precision and decimal value
For example, %10.4f displays a number at least ten characters wide with four decimal places.
// Demonstrate the precision modifier.
import java.util.Formatter;
/*j a v a2s. c om*/
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
// Format 4 decimal places.
fmt.format("%.4f", 123.1234567);
System.out.println(fmt);
}
}
The output:
%g and number of significant digits
The %g format specifier causes Formatter to use either %f or %e, whichever is shorter.
When using %g, the precision determines the number of significant digits. The default precision is 6.
import java.util.Formatter;
//from j a va 2 s . c om
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("%g\n", 123.1234567);
// Format 4 decimal places.
fmt.format("%.4g", 123.1234567);
System.out.println(fmt);
}
}
The output:
precision specifier to format strings
When the precision specifier is applied to strings, the precision specifier specifies the maximum field length. For example, %5.7s displays a string 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.
import java.util.Formatter;
//from j a v a 2 s . c om
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
// Display at most 15 characters in a string.
fmt = new Formatter();
fmt.format("%.15s", "12345678901234567890");
System.out.println(fmt);
}
}
Next chapter...
What you will learn in the next chapter:
- What are format flags
- How to justify Output
- How to append a + sign before positive numeric values
- How to use space flag to line up output values
- How to show negative numeric inside parentheses
- How to pad with zeros rather than spaces
- How to add grouping specifiers for large value numbers
- How to give output an alternate conversion format