How to convert double to BigDecimal

Overview

In this tutorial, we show you how to convert an primitive double to an BigDecimal in Java.
How to convert double to BigDecimal


1: Using BigDecimal.valueOf()

 public static void main(String[] args) {
  double primitiveDouble = 68.88;
  
  BigDecimal numBigDecimal = BigDecimal.valueOf(primitiveDouble);;
  System.out.println(numBigDecimal);
 }
Output
68.88

2: Using new BigDecimal(double val, MathContext mc)

 public static void main(String[] args) {
  double primitiveDouble = 68.88;
  
  BigDecimal numBigDecimal = new BigDecimal(primitiveDouble, MathContext.DECIMAL64);
  System.out.println(numBigDecimal);
 }
Output
68.88000000000000

3: Using new BigDecimal().setScale()

 public static void main(String[] args) {
  double primitiveDouble = 68.88;
  
  BigDecimal numBigDecimal = new BigDecimal(primitiveDouble).setScale(2,BigDecimal.ROUND_HALF_UP);
  System.out.println(numBigDecimal);
 }
Output
68.88
Previous Post
Next Post

post written by: