The Class BigDecimal
In this lesson, we look at performing accurate decimal arithmetic.
Imprecision in calculations
In the Apples by the Box problem, we wrote a program that computes the money saved by buying apples by the box instead of individually. For a box of 24
apples, the savings should be the difference between $7.68
and $7.25
, or $0.43
. Instead of displaying $0.43
, the program displayed $0.4299999999999997
. This imprecision is the result of using the binary number system to represent decimal values. Although we can force the output to look like $0.43
, the internal representation of the result is not quite correct. If we used this value in subsequent computations, the error would propagate and likely get larger. Using binary arithmetic for monetary computations is not a good idea, and is certainly something that banks could not tolerate.
Accurate decimal arithmetic
The class BigDecimal
enables us to perform accurate decimal arithmetic and to work with
arbitrarily large numbers. This class is in the package java.math
. Do not confuse this package with the class Math
which is in the package java.lang
.
✏️ Programming tip:
To use the class
BigDecimal
in your program, be sure to precede your class with the following statement:import java.math.BigDecimal;
📝 Note:
An object of
BigDecimal
has a signed decimal value and a scale, both of which are integers. The value of the scale positions the decimal point within the value. Usually, this representation need not concern you, but the terms value and scale do appear within the description of some of the class’s methods.
Creating a BigDecimal
object
To create a new BigDecimal
object, we use:
BigDecimal price = new BigDecimal("2.97");
We write the desired value of the new object as a string to preserve its accuracy. Writing it as a double
is legal, but doing so would involve a conversion to binary and, therefore, an inaccuracy in its representation.
If we want to read the value of the BigDecimal
object from the user, we could read it as a string. For example:
Get hands-on with 1400+ tech skills courses.