Precision on a number format in Java


You can include a precision specifier to the following format specifiers −

%f
%e
%g
%s

On floating point, the number of decimal places is known.

Let’s say we declared a Formatter object −

Formatter f1 = new Formatter();

Now, we want 3 decimal places. For that, use 1.3f −

f1.format("%1.3f", 29292929.98765432);

The above will return the number with 3 decimal places −

29292929.988

The following is the final example −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
    public static void main(String args[]) {
       Formatter f1, f2, f3;
       f1 = new Formatter();
       f1.format("%1.3f", 29292929.98765432);
       System.out.println(f1);
       f2 = new Formatter();
       f2.format("%1.7f", 29292929.98765432);
       System.out.println(f2);
       f3 = new Formatter();
       f3.format("%1.9f", 29292929.98765432);
       System.out.println(f3);
    }
}

Output

29292929.988
29292929.9876543
292929.987654320

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements