Convert double to BigDecimal in Java [2 ways]

In this post, I will be sharing how to convert double to BigDecimal in Java with examples. There are two ways to achieve our goal:

1. Using BigDecimal.valueOf() method [Recommended]

2. Using the BigDecimal constructor

Read Also: Convert BigDecimal to Double in Java

Let's dive deep into the topic:

Convert double to BigDecimal in Java

1. Using BigDecimal.valueOf() method


It is easy to convert double to BigDecimal using the BigDecimal class valueOf() method. The syntax of the method is given below:

 public static BigDecimal valueOf(double val)


The above method helps in converting double to BigDecimal in Java. Let's find out with the help of an example:

 import java.math.BigDecimal;
public class DoubleToBigDecimal {
    public static void main(String args[]) {
        double num = 123.456789;
        // Using BigDecimal class valueOf() method
        BigDecimal bd = BigDecimal.valueOf(num);
        System.out.println("Converted double to BigDecimal: " + bd);
    }
}


Output:
Converted double to BigDecimal: 123.456789


2. Using the BigDecimal constructor


We can convert double to BigDecimal using the BigDecimal class constructor. The syntax of the constructor is given below:

 BigDecimal(double val, MathContext mc)


The above constructor converts double to BigDecimal, with rounding according to context settings as shown below in the example:

 import java.math.MathContext;
import java.math.BigDecimal;
public class DoubleToBigDecimal2 {
    public static void main(String args[]) {
        double num = 12.345678;
        // Using BigDecimal class constructor
        BigDecimal bd = new BigDecimal(num, MathContext.DECIMAL64).stripTrailingZeros();
        System.out.println("Converted double to BigDecimal using constructor: " + bd);
    }
}


Output:
Converted double to BigDecimal using constructor: 12.345678

Converting double to BigDecimal with 2 Decimal places

After converting double to BigDecimal, you can easily restrict the BigDecimal to 2 decimal places by using BigDecimal class setScale() method as shown below in the example:

 import java.math.MathContext;
import java.math.BigDecimal;
public class DoubleToBigDecimal3 {
    public static void main(String args[]) {
        double num = 1.23456;
        // Using BigDecimal class constructor
        BigDecimal bd = new BigDecimal(num);
        // Using setScale() method to limit to 2 decimal places
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println("Converting double to BigDecimal with 2 Decimal places: " + bd);
    }
}


Output:
Converting double to BigDecimal with 2 Decimal places: 1.23


That's all for today. Please mention in the comments if you know any other way of converting double to BigDecimal 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