How to control precision in number format with Java Formatter
Description
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.
Syntax
fmt.format("%16.2e", 123.1234567);
Example
Precision Format
import java.util.Formatter;
/* www . j a v a 2s . c o m*/
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:
Example 2
For example, %10.4f displays a number at least ten characters wide with four decimal places.
// Demonstrate the precision modifier.
import java.util.Formatter;
//www .ja va 2 s . c o m
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:
Example 3
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;
/* ww w. j a v a 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:
Example 4
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;
/* w w w .jav a 2 s .c o m*/
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);
}
}
Example 5
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.
import java.util.Formatter;
// w w w . j av a 2 s . c o m
public class Main {
public static void main(String args[]) {
Formatter fmt = new Formatter();
fmt.format("%05d", 88);
System.out.println(fmt);
}
}
The code above generates the following result.