Round a Number to N Decimal Places in Java


Formatting a Decimal Number

1
2
System.out.printf("Value with 3 digits after decimal point %.3f %n", PI);
// OUTPUTS: Value with 3 digits after decimal point 3.142

format the value with the DecimalFormat

1
2
DecimalFormat df = new DecimalFormat("###.###");
System.out.println(df.format(PI));

Rounding Doubles with BigDecimal

1
2
3
4
5
6
7
private static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();

BigDecimal bd = new BigDecimal(Double.toString(value));
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}

  doublejava
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×