Precision Specifier

Java-Precision Specifier

Precision Specifier

A precision specifier can be applied to the %f, %e, %g, and %s format specifiers, among others. It follows the minimum field-width specifier (if there is one) and consists of a period followed by an integer. Its exact meaning depends upon the type of data to which it is applied. When you apply the precision specifier to floating-point data using the %f or %e specifiers, it determines the number of decimal places displayed. For example:

Precision Specifier

The %16.3f displays a number at least sixteen characters wide with three decimal places. When using %g, the precision determines the number of significant digits. The default precision is 6. Applied to 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. For example:

Precision Specifier


Program

Precision Specifier

Program Source

import java.util.Formatter;

public class Javaapp {

    public static void main(String[] args) {

        Formatter fmt = new Formatter();
        double d = 12345.12121121;
        fmt.format("d = %f",d);
        fmt.format("%nd = %12.4f", d);
        fmt.format("%nd = %16.3f", d);
        String str1 = "ABCDEFGHIJKLMN";
        String str2 = "ABC";
        fmt.format("%nstr1 = %5.8s", str1);
        fmt.format("%nstr2 = %5.8s", str2);
        System.out.println(fmt);
        fmt.close();
    }
}

Leave a Comment