Using BigDecimal
The BigDecimal
class, which is a member of the java.math
library, is a fixed-precision representation of floating point numbers. This means that values represented as BigDecimal
do not suffer from the problem of approximation that can and does occur when calculations are carried out by the hardware floating point unit (FPU) of most CPUs.
The BigDecimal
class shares an important characteristic with a string. They are both immutable. This means that when a value becomes a BigDecimal
object, it cannot be changed. Any operation on a BigDecimal
object returns a new BigDecimal
object.
Let us look at an application that can calculate loan payments for money borrowed. The formula for this calculation is as follows:
Here:
- rate = the interest rate per period
- n = the number of periods
- PV = present value (amount of loan)
- PMT = payment (the monthly payment)
If we use doubles for all the values, the Java bean data object...