how to round double to 2 decimal places in java
/**
* @author lautturi.com
* Java example: java round up double to 2 decimal places
*/
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class Lautturi {
public static void main(String[] args) {
double pi = 3.14159;
double roundOff = Math.round(pi * 100.0) / 100.0;
// Or
// double roundOff = (double) Math.round(pi * 100) / 100;
// Or
String roundStr = String.format("%.2f", pi);
// Or
BigDecimal bd = BigDecimal.valueOf(pi);
bd = bd.setScale(2, RoundingMode.HALF_UP);
double roundPi = bd.doubleValue();
System.out.println(roundOff);
System.out.println(roundStr);
System.out.println(roundPi);
}
}Scruoe:www.lautturi.comoutput:
3.14 3.14 3.14