Using BigDecimals

As opposed to float or double, a BigDecimal allows you to store arbitrary precision signed decimal numbers.

Here’s a simple example that creates a BigDecimal.

Main.java:

import java.math.*;
import java.util.*;
 
public class Main {
   public static void main(String args[]) {
      BigDecimal bd1 = new BigDecimal(createLongDecimal());
      BigDecimal bd2 = new BigDecimal(createLongDecimal());
 
      BigDecimal total = bd1.add(bd2);
 
      System.out.println("  " + bd1);
      System.out.println("+ " + bd2);
      System.out.println("= " + total);
   }
 
   public static String createLongDecimal() {
      Random r = new Random();
      StringBuffer total = new StringBuffer();
      for (int i=0; i<15; i++) {
         total.append(Math.abs(r.nextInt()));
         if (i == 10) total.append('.');
      }
  
      return total.toString();
   }
}

outputs:

  720503977823516025489207568136178482425783671110507142011860888752101
66134093438986271599747576765999033.18149285701107649443668155859929740
+ 720503977823516025489207568136178482425783671110507142011860888752101
66134093438986271599747576765999033.18149285701107649443668155859929740
= 144100795564703205097841513627235696485156734222101428402372177750420
332268186877972543199495153531998066.36298571402215298887336311719859480

There are other ways to create a BigDecimal, a constructor that allows you to pass a double and one with a BigInteger.
The constructor that accepts a double is “somewhat inpredictable”, according to the API.
Consider the following program.

Main.java:

import java.math.*;
  
public class Main {
   public static void main(String args[]) {
      BigDecimal bd1 = new BigDecimal(.1);
 
      System.out.println(bd1);
   } 
}

outputs:

0.1000000000000000055511151231257827021181583404541015625