In this tutorial, we will discuss how to use the Java BigDecimal class to deal with calculations that require a high degree of precision, such as when dealing with currency conversion, taxes or even high accuracy mathematical calculations.

If you fancy an assistant on your desk to entertain you, tell you about the weather or your appointments, then I recommend the Anki Cozmo – Collector’s Edition robot (click to check the price on Amazon). The Anki Cozmo will entertain you during those boring or lonely moments at work, or while studying, and will help you to keep your schedule and be more alert throughout the day.

## Why do we need the BigDecimal class

In Java a floating point or a fractional number can be stored using two types, doubles and floats. Both primitive data types have a limited size of 64 and 32 bit respectively. Having a limited bit length also means that these data types have a limited accuracy.

Consider the following task: You are now a mathematical scientist hired by NASA and your first job is to calculate the surface area of a spherical object up to 20 decimal places. The object has a radius of 123212 meters.

After reading the task above, we immediately discover a problem. In order to calculate the surface area of the object up to 20 decimal places, we would have to use the value of pi with an accuracy of 20 decimal places. Let us attempt to do this in Java using the double data type.

When we try to print the value of pi, we get the following value.

As we can see, even though we used the double data type, the last 5 decimal places got discarded. This is because of the limitations that the primitive data type “double” has and this is where a BigDecimal object comes in.

## What is a BigDecimal

A BigDecimal is a data structure that is used to store floating point or fractional numbers with a high degree of accuracy. Such a data structure is important for developing several computer applications such as:

• Scientific and astronomical calculations
• Banking applications
• Statistics
• Stock market or commodity trading applications to name a few

Now that we know why the BigDecimal data structure is so important in Java, let us return to our previous example. We will start by first defining the value ofpi using BigDecimal.

In the program above, we instantiated a BigDecimal by using a String representation of the floating point number. Even though BigDecimal offers constructors with floats, integers, doubles, etc.. non of them (other than another BigDecimal) can hold the value of pi up to 20 decimal places.

Let us run the program and find how pi will be printed.

Notice how the number was printed completely, with no loss of precision. The next step would be to calculate the surface area of the spherical object. It should be noted that since BigDecimals are objects, we cannot use the arithmetic operations ” * + – / …”, instead, we would be using BigDecimal’s own “.add(BigDecimal bd)” , “.subtract(..)“, “.multiply(….)” and so on. Also, since a BigDecimal is an object, mathematical calculations can only be done with other BigDecimal objects (we cannot add a byte to a big decimal using +, for example).

Notice in the code how we instantiated a big decimal using an integer. Also notice that when we called the multiply method, we saved the result into the radius variable. This is because calling radius.multiply(xxxxx) does not change the value of either the object radius, or the method arguments, but rather the method returns the result of the multiplication into a new object which we assign to radius.

Running the program will result in the following output.

## Limiting a BigDecimal to a certain degree of precision

Let us say, we would like to calculate something, up to 3 decimal places, no more and no less, and independent of the number we used to instantiate the BigDecimal. In that case, we will have to specify two properties of a BigDecimal object. The rounding mode and the scaleThe scale defines the number of decimal places we want, and the rounding mode specifies how we would like to round a floating point number.

To illustrate, we will modify the our example as follows : “After you have created the program, your bosses at NASA have changed their minds, and they now want the result to be accurate up to no more than 3 decimal places. You are now required to change your program as we have run out of ink.”

To do so, we will use the “.setScale(…)” method just before the printing method with a scale value of 3 and a rounding mode of ROUND_CEILING. This will round up the number to the third decimal place.

The statement we added limited the number of decimal places to 3. In general, it is good practice to set a rounding mode for any big decimal object or one could risk an arithmetic exception being thrown as shown here. Now, after running the program, we receive the following output.

Notice how the number is now limited to 3 decimal places. Also notice that the decimal part is “.881”, this is because we defined a rounding mode of “ceiling”, where a decimal place is rounded up even if the next decimal place is low or zero.

## Comparing BigDecimals

As with primitive numeric data types, one will sometimes need to compare BigDecimals with each other. To do so, one will have to use the “x.compareTo( BigDecimal bd)” method. (Note: Do not use the .equals() method. It is a common mistake to do so, as it compares two pointers to determine if they point to the same object, and has nothing to do with numeric equality). The compareTo method works as follows: let us say we make the call “x.compareTo(y)”. The result of this call will be as follows:

-1 : if x is less than y
0 : if x is equal to y
+1: if x more than y

To illustrate, consider the following code, and it’s corresponding output:

Output:

Finally, as we mentioned before, we should not use .equals() for comparisonsThe .equals() method of the BigDecimal class is only used to compare if the two pointers point to the same object (in this case, the string representation of the number in the string pool). Consider the following example.

Output:

Here, even though a was 3 and b was 3.00 (essentially having the same value), using .equals returns false, since these two objects consist of 2 different string literals. On the other hand, a (“3”) and c (“3”) match because they are the exact same string literal. Always use .compareTo for value comparison.

## Summary

In this post, we discussed what is a BigDecimal and how to use it in Java to perform high accuracy calculations. We discussed some of the common applications that may require BigDecimals. Finally we discussed how to perform comparison operations on BigDecimals and the common pitfalls that you may encounter.

If you would like to improve your knowledge about Java and how to write high performance code like a pro, then I would recommend reading Java Performance: The Definitive Guide: Getting the Most Out of Your Code (click to check current price on Amazon).