Round number to fewer decimals in Java

Description

The following code shows how to round number to fewer decimals.

Example


//from  ww  w  .ja v  a2s  .co m
import java.text.DecimalFormat;

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.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization