How to round a double to n decimal places in Java

July 21, 2017

To round a double to n decimal places, we need to use the BigDecimal.doubleValue() method.

1. Creating a proper method

We can easily reach the rounding by creating the round method, like in the example below.

As you can see, this code allows us to round to a specific number of places. In the above example, we’ve rounded the number 47.432643 to 2 decimal places. Let’s talk a little bit about this code.

2. Analysis

The round method takes two arguments: val which is the value to round and places which is a number of places we want to round to. Next, if the places are given wrong the method throws an exception.

Then we must convert val to BigDecimal because it gives us complete control over rounding behavior. Further, we use the setScale method to reach our goal – rounding to specified places. RoundingMode gives us the opportunity to decide how we can round the number. Here, when we got the half of number it is rounded up but we can change it to down or to an even number.

In the end, the method returns the converted value to the previous type which is double.

As the result, in the main method, we can test our fresh method. The code prints:

Click here to add a comment

Leave a comment:

Privacy Preference Center