Java Reference
In-Depth Information
Any application that requires precise floating-point calculations—such as those in financial
applications—should instead use class BigDecimal (from package java.math ).
Interest Calculations Using BigDecimal
Figure 8.16 reimplements the interest calculation example of Fig. 5.6 using objects of class
BigDecimal to perform the calculations. We also introduce class NumberFormat (package
java.text ) for formatting numeric values as locale-specific String s—for example, in the
U.S. locale, the value 1234.56, would be formatted as "1,234.56" , whereas in many Eu-
ropean locales it would be formatted as "1.234,56" .
1
// Interest.java
2
// Compound-interest calculations with BigDecimal.
3
import java.math.BigDecimal;
4
import java.text.NumberFormat;
5
6
public class Interest
7
{
8
public static void main(String args[])
9
{
10
// initial principal amount before interest
BigDecimal principal = BigDecimal.valueOf( 1000.0 );
BigDecimal rate = BigDecimal.valueOf( 0.05 ); // interest rate
11
12
13
14
// display headers
15
System.out.printf( "%s%20s%n" , "Year" , "Amount on deposit" );
16
17
// calculate amount on deposit for each of ten years
18
for ( int year = 1 ; year <= 10 ; year++)
19
{
20
// calculate new amount for specified year
BigDecimal amount =
principal.multiply(rate.add( BigDecimal.ONE ).pow(year));
21
22
23
24
// display the year and the amount
25
System.out.printf( "%4d%20s%n" , year,
26
NumberFormat.getCurrencyInstance().format(amount)
);
27
}
28
}
29
} // end class Interest
Year Amount on deposit
1 $1,050.00
2 $1,102.50
3 $1,157.62
4 $1,215.51
5 $1,276.28
6 $1,340.10
7 $1,407.10
8 $1,477.46
9 $1,551.33
10 $1,628.89
Fig. 8.16 | Compound-interest calculations with BigDecimal .
 
Search WWH ::




Custom Search