Rounding BigDecimal values with specific Decimal Places in Java

Hey Everyone! In this article, we will learn how to round BigDecimal values in Java up to specific decimal places.

BigDecimal class in Java


The BigDecimal class in Java is useful for providing operations such as format conversion, hashing, and rounding operations on floating-point numbers in Java. It is used to handle and perform high precision operations such as arithmetic etc on double numbers in Java. It is usually used in finance applications to handle data.
The BigDecimal class in Java consists of two things:-

  1. Random precision integer unscaled value.
  2. 32-bit Integer scale.

The BigDecimal class objects are immutable.
Scale: The number of digits to the right of the decimal point.
For example:-
Consider the decimal number 2.141.
The unscaled value is 2141 and the scale is 3.
Now let us see how we can round BigDecimal values with specific decimal places in Java.

Rounding Off BigDecimal Values


We will be using the MathContext class to set the precision and round off the values.

Java Program To Round Off BigDecimal Values in Java

package program;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;


public class Program {

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        double no;
        int scale;
        System.out.println("Enter a double value");
        no=sc.nextDouble();
        System.out.println("The double value entered is "+no);
        BigDecimal obj1 = new BigDecimal(no);
        BigDecimal obj2 ;
        System.out.println("Enter the precision or scale value");
        scale=sc.nextInt();
        MathContext pr = new MathContext(scale);    
        obj2=obj1.round(pr);
        System.out.println("The rounded off BigDecimal value is "+obj2);
    }
       
}

Output:-

Enter a double value
6.8972
The double value entered is 6.8972
Enter the precision or scale value
3
The rounded off BigDecimal value is 6.90

 

In the above program, we set the scale or precision value with the help of the MathContext class in Java. Then the object of this class is passed as a parameter to the round method which returns the rounded off BigDecimal value.

Also read: How to convert String to BigDecimal in Java

Leave a Reply