Java Program to round a double passed to BigDecimal

Java 8Object Oriented ProgrammingProgramming

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 −

Example

 Live Demo

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);
   }
}

Output

9.19
raja
Published on 20-Dec-2018 15:34:49
Advertisements