Java Reference
In-Depth Information
In the end, the same results will be returned using either
compareTo()
or
com-
pare()
.
4-5. Calculating Monetary Values
Problem
You are developing an application that requires the use of monetary values and you are
not sure which data type to use for storing and calculating currency values.
Solution
Use the
BigDecimal
data type to perform calculation on all monetary values. Format
the resulting calculations using the
NumberFormat.getCurrencyInstance()
helper method. In the following code, three monetary values are calculated using a
handful of the methods that are part of the
BigDecimal
class. The resulting calcula-
tions are then converted into
double
values and formatted using the
Number-
Format
class. First, take a look at how these values are calculated:
BigDecimal currencyOne = new BigDecimal("25.65");
BigDecimal currencyTwo = new BigDecimal("187.32");
BigDecimal currencyThree = new BigDecimal("4.86");
BigDecimal result = null;
String printFormat = null;
// Add all three values
result = currencyOne.add(currencyTwo).add(currencyThree);
// Convert to double and send to formatDollars(),
returning a String
printFormat = formatDollars(result.doubleValue());
System.out.println(printFormat);
// Subtract the first currency value from the second
result = currencyTwo.subtract(currencyOne);
printFormat = formatDollars(result.doubleValue());
System.out.println(printFormat);