How to round a number to n decimal places in Java
Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output. Example: DecimalFormat df = new DecimalFormat(“#.####”); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d)); } gives the output: 12 123.1235 0.23 0.1 2341234.2125 EDIT: … Read more