This post will discuss how to round up a double with 2 decimal places in Java.

1. Using Math.round() method

The Math.round() method returns the value of the specified double rounded to the nearest long value. The following solution demonstrates its usage to round up a double with 2 decimal places. Note that the number of zeros indicates the number of decimals.

Download  Run Code

 
Note that the number of zeros indicates the number of decimals. Therefore, to round upto 3 decimal places, do like:

Download  Run Code

 
Here’s an alternative, equivalent version of the above code:

Download  Run Code

 
The floating-point arithmetic can be very tricky, and this method also does not work as desired always. For instance, the value 296.335 gets rounded down to 296.33 instead of 296.34.

Download  Run Code

2. Using DecimalFormat.format() method

The idea here is to create a DecimalFormat using the specified pattern and call the DecimalFormat.format() method to get the formatted string. To restrict the double to 2-decimal points, you can use the pattern #.##. You can also set the RoundingMode using the setRoundingMode() method. This approach suffers the same problem as the first approach. i.e, the value 296.335 gets rounded down to 296.33 instead of 296.34.

Download  Run Code

3. Using String.format() method

Following is another approach that returns a formatted string from a double value using the String.format() method.

Download  Run Code

4. Using BigDecimal class

Finally, you can convert the double value to a BigDecimal and scale it using the setScale() method. This approach suffers the same concern as seen in some of the earlier approaches. i.e, the value 296.335 gets rounded down to 296.33 instead of 296.34.

Download  Run Code

That’s all about rounding up a float with 2 decimal places in Java.