Java Data Type How to - Round number to fewer decimals








Question

We would like to know how to round number to fewer decimals.

Answer

import java.text.DecimalFormat;
// w w w . java2  s  .  com
public class Main {

  public static void main(String[] args) {
    double numberToRound = 12345.6789;

    DecimalFormat df = new DecimalFormat("0.000");
    System.out.println("Rounded number = " + df.format(numberToRound));

    System.out.println(String.format("Rounded number = %.3f", numberToRound));

  }
}

The code above generates the following result.