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 ...