Understanding BigDecimal round() Method in Java

Hello Learners, today we are going to learn about the BigDecimal round method in Java. The round method belongs to the BigDecimal class. The class resides under java.math package.

BigDecimal class provides methods to operate on larger or even very smaller floating-point numbers. The round method is one of those methods that used to round off a floating-point number up to the given precision.

Let’s see a simple code to check how the round function works.

import java.math.*; 

public class bigdeciround {
  public static void main(String[] args) {

        BigDecimal bg1 = new BigDecimal("23.426").round(new MathContext(4));
	BigDecimal bg2 = new BigDecimal("508.283").round(new MathContext(5));
        BigDecimal bg3 = new BigDecimal("57.05").round(new MathContext(3));
	BigDecimal bg4 = new BigDecimal("33.5").round(new MathContext(2));
			
	System.out.println("The value after rounding off "+bg1);
	System.out.println("The value after rounding off "+bg2);
	System.out.println("The value after rounding off "+bg3);
	System.out.println("The value after rounding off "+bg4); 
    
  }
}

OUTPUT:

The value after rounding off 23.43
The value after rounding off 508.28
The value after rounding off 57.1
The value after rounding off 34

Explanation

The round method follows the basic math rules to round off any number. Let’s examine these numbers.

  • First, you need to create an object of big decimal class with the value you want to round off under double-quotes. Then you have to call the round method.
  • Inside the round method, you must pass the object of MathContext class for passing the precision and you are done.
  • In the bg1, we passed 23.426 and gave the precision as 4. So the round method will round off the number after 4th digit from left. It will remove everything starting from the 5th position which is 6.
  • Here, 6 is greater than 2. So while rounding off it will add one at the last digit which is 2. Now the new number after rounding off is 23.43
  • Similarly, with bg2 we have given the precision as 5. It will remove everything after 5th digit. Now here, 3 is smaller than 8 so while rounding off one was not added to 8 and 3 is simply removed. The new number after rounding off is 508.28 and the same way the other numbers are rounded off.

That’s it, Done. Try to do it on your own, it’s a simple code.

So, that’s all for now about the BigDecimal round method in Java. Till then Keep Learning, Keep Practicing, Keep Reading, Keep Coding!

“THINK TWICE CODE ONCE!”

Leave a Reply

Your email address will not be published. Required fields are marked *