In this post, we will see how to convert BigDecimal to Double in java.
Convert BigDecimal to Double in Java
You can simple use BigDecimal’s doubleValue()
to convert BigDecimal to Double in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog.entry; import java.math.BigDecimal; public class BigDecimalToDoubleMain { public static void main(String[] args) { BigDecimal bigDecimal = new BigDecimal("22.2345"); Double doubleVal=bigDecimal.doubleValue(); System.out.println("Double value: "+doubleVal); } } |
Output:
Double value: 22.2345
Further reading:
BigDecimal to double with 2 decimal places
If you want to restrict double to 2 decimal places, you can use BigDecimal’s setScale()
method. You can use RoundMode to specify rounding behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog.entry; import java.math.BigDecimal; import java.math.RoundingMode; public class BigDecimalToDoubleRoundMain { public static void main(String[] args) { double d = 2.3262; BigDecimal bigDecimal=new BigDecimal(d); bigDecimal = bigDecimal.setScale(2,RoundingMode.HALF_DOWN); Double doubleVal=bigDecimal.doubleValue(); System.out.println("Double upto 2 decimal places: "+doubleVal); // Rounding down BigDecimal bigDecimal1=new BigDecimal(d); bigDecimal1 = bigDecimal1.setScale(2,RoundingMode.DOWN); System.out.println("Double upto 2 decimal places - RoundingMode.DOWN: "+bigDecimal1.doubleValue()); // Rounding up BigDecimal bigDecimal2=new BigDecimal(d); bigDecimal2 = bigDecimal2.setScale(2,RoundingMode.UP); System.out.println("Double upto 2 decimal places - RoundingMode.UP: "+bigDecimal2.doubleValue()); } } |
Output:
Double upto 2 decimal places: 2.33
Double upto 2 decimal places – RoundingMode.DOWN: 2.32
Double upto 2 decimal places – RoundingMode.UP: 2.33
Double upto 2 decimal places – RoundingMode.DOWN: 2.32
Double upto 2 decimal places – RoundingMode.UP: 2.33
That’s all about Java BigDecimal to Double.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.