Convert Double to BigInteger in Java [2 ways]

In this short post, I will be sharing how to convert Double to BigInteger in Java.

1. Using BigDecimal class valueOf() and toBigInteger() methods

2. Using the BigDecimal constructor and toBigInteger() method

Read Also: Convert String to BigInteger in Java

Let's dive deep into the topic:

Convert Double to BigInteger in Java

1. Using BigDecimal class valueOf() and toBigInteger() methods


We can easily convert Double to BigInteger in Java by performing two steps:

1. Convert Double to BigDecimal, using the BigDecimal class valueOf() method

2. Convert BigDecimal to BigInteger, using the BigDecimal class toBigInteger() method as shown below in the example:

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


Output:
Converted Double to BigInteger: 5342

2. Using the BigDecimal constructor and toBigInteger() method


Just like above, we can easily convert Double to BigInteger in Java by performing two steps:

1. Convert Double to BigDecimal, using the BigDecimal class constructor

2. Convert BigDecimal to BigInteger, using BigDecimal class toBigInteger() method as shown in the example below:

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


Output:
Converted Double to BigInteger: 7894

That's all for today. Please mention in the comments if you have any questions related to how to convert Double to BigInteger in Java with examples.

About The Author

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