Add Grouping Specifiers for Large Numbers in Java



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
Updated on: 2019-07-30T22:30:24+05:30

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements