Java Program to format to 2 decimal places in a 10-character field

Java 8Object Oriented ProgrammingProgramming

To format, use the Formatter class. Import the following package to work with the Formatter class in Java −

import java.util.Formatter;

Create a Formatter object and format to 2 decimal places in a 10-character field −

Formatter f = new Formatter();
System.out.println(f.format("%10.2e", 3989.7886));

The following is the complete example −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      System.out.println(f.format("%08d", 697));
      f = new Formatter();
      System.out.println(f.format("%03d", 9878));
      f = new Formatter();
      System.out.println(f.format("%10.2e", 3989.7886));
   }
}

Output

00000697
9878
3.99e+03
raja
Published on 26-Dec-2018 06:42:52
Advertisements