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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.math.BigDecimal; import java.math.RoundingMode; public class Round2DecimalPlaces { public static double round(double val, int places){ if(places < 0) throw new IllegalArgumentException(); BigDecimal bigDecimal = new BigDecimal(val); bigDecimal = bigDecimal.setScale(places, RoundingMode.HALF_UP); return bigDecimal.doubleValue(); } public static void main(String[] args) { double x = 47.432643; System.out.println(x); System.out.println(round(x,2)); } } |
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:
1 2 3 4 |
47.432643 47.43 |