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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements