Add grouping specifiers for large numbers in Java

Java 8Object Oriented ProgrammingProgramming

For using the Formatter class, import the following package −

import java.util.Formatter;

We can group specifiers as shown below −

Formatter f = new Formatter();
f.format("%,.2f", 38178.9889);

The above sets thousands separator and 2 decimal places.

The following is an example −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      f.format("%d", 50);
      System.out.println(f);
      f = new Formatter();
      f.format("%,.2f", 38178.9889);
      System.out.println(f);
   }
}

Output

50
38,178.99
raja
Published on 21-Dec-2018 12:03:41
Advertisements