How to convert String to BigDecimal in Java

Hey Everyone! In this article, we will learn how to convert String to BigDecimal in Java.
Before directly getting into the code let us first understand BigDecimal class in Java.


BigDecimal Java

The BigDecimal class in java is used for various operations such as arithmetic, rounding, hashing, comparison, and manipulation operations. It is present in the java.math.BigDecimal package in java. The BigDecimal class is usually used where precise rounding off operations are required such as when dealing with financial or statistical data. The BigDecimal class consists of various constructors and methods that are used for the precise operations to be performed.
Example:-

package program;

import java.math.BigDecimal;  

public class Program {

   
    public static void main(String[] args) {
        
        int n,m;
        BigDecimal bd1 = new BigDecimal("8763");
        BigDecimal bd2 = new BigDecimal("7276");  
             
        n=bd1.intValueExact();
        m = bd2.intValue();  
        System.out.println("Exact Integer value is "+n); 
        System.out.println( "Integer value = "+m); 
    
    }
    
}

Output:

run:
Exact Integer value is 8763
Integer value = 7276
BUILD SUCCESSFUL (total time: 0 seconds)

Program to convert String to BigDecimal in Java

package program;

import java.math.BigDecimal;  

public class Program {

   
    public static void main(String[] args) {
        
        //creating various string variables such as integer double and long datatype variables 
        String double1="13.23";
        String int1="334";
        String long1 = "12323982782";
        
        
        //converting the string to bigdecimal using the BigDecimal() constructor by passing the String as an argument
  BigDecimal bd1=new BigDecimal(double1);
  System.out.println("String (double) ---> BigDecimal "+bd1); 
    
        BigDecimal bd2=new BigDecimal(int1);
  System.out.println("String (int) ---> BigDecimal "+bd2); 
        
        BigDecimal bd3=new BigDecimal(long1);
  System.out.println("String (long) ---> BigDecimal "+bd3); 

    }
    
}

Output


String (double) ---> BigDecimal 13.23
String (int) ---> BigDecimal 334
String (long) ---> BigDecimal 12323982782

In the above program, the String Variables are converted to BigDecimal using the BigDecimal constructor.


I hope this article was useful to you. Please leave a comment down below in case of any doubts or suggestions.

Also read:

Leave a Reply

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