The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
Firstly, let us pass a double to BigDecimal −
BigDecimal val = new BigDecimal(9.19456);
Now, we will round it −
val = val.setScale(2, BigDecimal.ROUND_HALF_EVEN);
Above, we have used the field ROUND_HALF_EVEN. It is a rounding mode to round towards the "nearest neighbor" unless both neighbours are equidistant, in which case, round towards the even neighbours
The following is an example −
import java.math.BigDecimal; public class Demo { public static void main(String args[]) { BigDecimal val = new BigDecimal(9.19456); val = val.setScale(2, BigDecimal.ROUND_HALF_EVEN); System.out.println(val); } }
9.19