Convert BigDecimal to BigInteger in Java [2 ways]

In this post, I will be sharing how to convert BigDecimal to BigInteger in Java. We can achieve our goal in the following ways:

1. Using BigDecimal class toBigInteger() method [Recommended]

2. Using the BigInteger constructor

Read Also: Convert BigInteger to BigDecimal in Java

Let's dive deep into the topic:

Convert BigDecimal to BigInteger in Java

1. Using BigDecimal class toBigInteger() method


You can easily convert BigDecimal to BigInteger using BigDecimal class toBigInteger() method.

Note: According to Oracle docs, the toBigInteger() method will discard any fractional part of the BigDecimal and you will lose precision while converting from BigDecimal to BigInteger in Java.

 import java.math.BigDecimal;
import java.math.BigInteger;
public class BigDecimalToBigInteger {
    public static void main(String args[]) {
      BigDecimal bd = new BigDecimal("123456789.123456789");
      BigInteger bi = bd.toBigInteger();
      System.out.println("Converted BigDecimal to BigInteger: " + bi);
    }
}


Output:
Converted BigDecimal to BigInteger: 123456789

2. Using BigInteger constructor


You can easily convert BigDecimal to BigInteger using the BigInteger class constructor. The syntax of the constructor is given below:
 public BigInteger(String val)


You can find the code below to convert BigDecimal to BigInteger in Java:

 import java.math.BigInteger;
import java.math.BigDecimal;
public class BigDecimalToBigInteger2 {
    public static void main(String args[]) {
      BigDecimal bd2 = new BigDecimal("3456789");
      BigInteger bi2 = new BigInteger(bd2.toString());
      System.out.println("Converted BigDecimal to BigInteger: " + bi2);
    }
}


Output:
Converted BigDecimal to BigInteger: 3456789

The only downside of using a constructor is that it will throw java.lang.NumberFormatException if the BigDecimal contains any decimal places as shown below:

 import java.math.BigInteger;
import java.math.BigDecimal;
public class BigDecimalToBigInteger3 {
    public static void main(String args[]) {
      BigDecimal bd3 = new BigDecimal("123.01234");
      BigInteger bi3 = new BigInteger(bd3.toString());
      System.out.println("Converted BigDecimal to BigInteger: " + bi3);
    }
}


Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "123.01234"

That's all for today. Please mention in the comments in case you have any questions related to how to convert BigDecimal to BigInteger in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry