Java Data Type How to - Set format to two decimal places: set Maximum Fraction Digits








Question

We would like to know how to set format to two decimal places: set Maximum Fraction Digits.

Answer

import java.text.NumberFormat;
/*  ww  w.  jav  a 2 s  .c  o m*/
public class Main {
  public static void main(String args[]) {
    NumberFormat nf = NumberFormat.getInstance();

    System.out.println("Default format: " + nf.format(1234567.678));

    nf.setMaximumFractionDigits(2);

    System.out.println("Format with two decimal places: " + nf.format(1234567.678));

  }
}

The code above generates the following result.