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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements