Wednesday, December 4, 2013

Java BigDecimal class tutorial: How to deal with monetary calculation in Java?

Lets take an example of computing a below mentioned financial operation using java program
 Chocolate cost = 5.52
                Tax = 0.84
 -----------------------------
Expected Total = 6.36

But if you do the above calculations using 'Double/float' primitive data type in Java, the total obtained will be 6.359999999999999.

We need to round of the total value to have a meaningful value in real life. Hence Java provides a class BigDecimal for this purpose.

Below is the simple program, which describes the usage of BigDecimal

----------------- BigDecimalExample.java -------------------------------
package blog.siddesh.basics;

import java.math.BigDecimal;

public class BigDecimalExample {

public static void main(String[] args) {
BigDecimal num = new BigDecimal("5.52");
BigDecimal tax = new BigDecimal("0.84");
BigDecimal total = num.add(tax); 

System.out.println("Total = "+total.toString());

double n = 5.52;
double t = 0.84;
double tot = n + t;
System.out.println("Double total = " + tot);


}

}
---------------------------------------------------------------------------