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

Converting double to integer in Java

is there a possibility that casting a double created via Math.round() will still result in a truncated down number No, round() will always round your double to the correct value, and then, it will be cast to an long which will truncate any decimal places. But after rounding, there will not be any fractional parts remaining. Here are the docs from Math.round(double): … Read more

Round a double to 2 decimal places

Here’s an utility that rounds (instead of truncating) a double to specified number of decimal places. For example: round(200.3456, 2); // returns 200.35 public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); long factor = (long) Math.pow(10, places); value = value * factor; long tmp = Math.round(value); return (double) tmp / factor; … Read more

Always Round UP a Double

You can use Math.ceil() method. See JavaDoc link: https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html#ceil(double) From the docs: ceil public static double ceil(double a) Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. Special cases: If the argument value is already equal to a mathematical integer, then the … Read more