BigDecimal
class and numeric formatting. The first step to teaching you both of those topics is to first create BigDecimal
objects.
BigDecimal
class in the
java.math
library to hold values. You can create a
BigDecimal
object in the following manner:
BigDecimal amount = new BigDecimal("1115.37");
String
argument to the
BigDecimal
constructor determines the value of the object created. The value of
"1115.37"
might represent, for example, a monthly mortgage payment in dollars, or a checkbook balance. To display the amount, you can use the
BigDecimal
class's
toString()
method:
System.out.println(amount.toString());
BigDecimal
amount is shown below:
import java.math.*;
public class Mortgage {
public static void main(String[] args) {
BigDecimal payment = new BigDecimal("1115.37");
System.out.println(payment.toString());
}
}
1115.37
BigDecimal
objects properly formatted, which for US currency would include a dollar sign and a comma as a thousands separator. (For other currencies, please see the section
Currency of Other Countries below). The
NumberFormat
class, found in the
java.text
library, can create an appropriate object for US currency with the following code:
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
Locale
class, used as an argument for the
getCurrencyInstance()
method above, is found in the
java.util
library.
NumberFormat
's
format()
method, which we will be using next, takes a double or long primitive as an argument, so first we will turn the
BigDecimal
object into a
double
using
BigDecimal
's
doubleValue()
method:
double doublePayment = payment.doubleValue();
NumberFormat
's
format()
method to create a
String
:
String s = n.format(doublePayment);
import java.math.*;
import java.text.*;
import java.util.*;
public class Mortgage2 {
public static void main(String[] args) {
BigDecimal payment = new BigDecimal("1115.37");
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double doublePayment = payment.doubleValue();
String s = n.format(doublePayment);
System.out.println(s);
}
}
$1,115.37
double
value involves a small loss in the value's accuracy. While the inaccuracies are too small to be seen in this article's examples, they are visible in very large amounts. Therefore, you cannot rely upon
NumericFormat
to produce accurate results with very large numbers (about 13 or more digits).
Locale.US
as the argument passed to the
getCurrencyInstance()
method to specify the currency of the country (United States) with which we'd be working. Java is not limited to working with US currency however. For example, you would use
Locale.GERMANY, Locale.FRANCE
, or
Locale.ITALY
to specify the currencies of Germany, France, and Italy, respectively. The topic of internationalization is a subject in its own right; see the Resources section for a link to more information.
BigDecimal
methods for adding and subtracting numbers are
add()
and
subtract()
, respectively. For example, to add 1,115.37 and 115.37, we could do the following:
BigDecimal balance = new BigDecimal("1115.37");
BigDecimal transaction = new BigDecimal("115.37");
BigDecimal newBalance = balance.add(transaction);
BigDecimal
's
newBalance
object now holds the value of 1,230.74. Similarly, to subtract 115.37 from 1,115.37, we could use this code:
BigDecimal balance = new BigDecimal("1115.37");
BigDecimal transaction = new BigDecimal("115.37");
BigDecimal newBalance2 = balance.subtract(transaction);
BigDecimal
's
newBalance2
object now holds the value of 1,000.00. (Naturally, if we are talking about checkbook balances in real life, the
subtract()
method will be used much more often than the
add()
method, and the total amount subtracted from the checkbook balance will exceed the total amount added, or so it often seems.) You can accomplish multiplying and dividing with
BigDecimal
's
multiply()
and
divide()
methods. Multiplying is demonstrated in the following program:
import java.math.*;
import java.text.*;
import java.util.*;
public class Multiply {
public static void main(String[] args) {
BigDecimal d = new BigDecimal("1115.32");
BigDecimal taxRate = new BigDecimal("0.0049");
BigDecimal d2 = d.multiply(taxRate);
System.out.println("Unformatted: " + d2.toString());
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double money = d2.doubleValue();
String s = n.format(money);
System.out.println("Formatted: " + s);
}
}
Unformatted: 5.465068
Formatted: $5.46
BigDecimal
object as compared to the formatted output. In addition, formatting the value of the
BigDecimal
object causes the fraction -- greater than one half -- to be dropped. To manage the extra decimal places and the lack of rounding, we can use
BigDecimal
's
setScale()
method to set the number of decimal places. When using
setScale()
, we need to specify not only the number of decimal places, but how the number will be rounded, if rounding is necessary. The most common way of rounding -- round up fractions half or greater, and round down all other fractions -- can be specified with
BigDecimal
's constant
ROUND_HALF_UP
. Therefore, to set the number of decimal places to two and specify that fractions half and greater will be rounded up, we can write:
d2 = d2.setScale(2, BigDecimal.ROUND_HALF_UP);
setScale()
, we now have:
import java.math.*;
import java.text.*;
import java.util.*;
public class Multiply2 {
public static void main(String[] args) {
BigDecimal d = new BigDecimal("1115.32");
BigDecimal taxRate = new BigDecimal("0.0049");
BigDecimal d2 = d.multiply(taxRate);
d2 = d2.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("Unformatted: " + d2.toString());
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double money = d2.doubleValue();
String s = n.format(money);
System.out.println("Formatted: " + s);
}
}
Unformatted: 5.47
Formatted: $5.47
BigDecimal
value is rounded to two digits, rounding the value up, and the formatted
String
correctly displays the rounded value. Other constants useful in rounding are
ROUND_HALF_DOWN
and
ROUND_HALF_EVEN
. The first,
ROUND_HALF_DOWN
, rounds fractions of half and under down, and all others up. The second,
ROUND_HALF_EVEN
, rounds half fractions to the even number (e.g., 2.5 rounds to 2, while 3.5 rounds to 4), and fractions greater or less than half to the closest integer. When dividing
BigDecimal
objects, we are required to specify how the result will be rounded. For this article, we will round halves up. The following program shows some sample division:
import java.math.*;
import java.text.*;
import java.util.*;
public class Divide {
public static void main(String[] args) {
BigDecimal d = new BigDecimal("1115.32");
BigDecimal days = new BigDecimal("30");
BigDecimal d2 = d.divide(days, 2, BigDecimal.ROUND_HALF_UP);
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double money = d2.doubleValue();
String s = n.format(money);
System.out.println(s);
}
}
$37.18
import java.math.*;
import java.text.*;
import java.util.*;
public class Interest {
public static void main(String[] args) {
BigDecimal principal = new BigDecimal("9500.00");
BigDecimal rate = new BigDecimal("0.067");
BigDecimal time = new BigDecimal("0.25");
BigDecimal temp = principal.multiply(rate);
BigDecimal interest = temp.multiply(time);
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double money = interest.doubleValue();
String s = n.format(money);
System.out.println("First quarter interest: " + s); }
}
First quarter interest: $159.12
import java.math.*;
import java.text.*;
import java.util.*;
public class Mutual {
public static void main(String[] args) {
BigDecimal shares = new BigDecimal("754.495");
BigDecimal purchaseAmount = new BigDecimal("200.00");
BigDecimal pricePerShare = new BigDecimal("10.38");
BigDecimal sharesPurchased = purchaseAmount.divide(pricePerShare, 3, BigDecimal.ROUND_HALF_UP);
shares = shares.add(sharesPurchased);
BigDecimal accountValue = shares.multiply(pricePerShare);
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double dAccountValue = accountValue.doubleValue();
String sAccountValue = n.format(dAccountValue);
System.out.println("Number of shares = " + shares.toString());
System.out.println("Account value = " + sAccountValue); }
}
Number of shares = 773.763
Account value = $8,031.66
NumberFormat
object to format numbers in the US style (commas separate thousands, periods separate decimals) by using:
NumberFormat n2 = NumberFormat.getInstance(Locale.US);
import java.math.*;
import java.text.*;
import java.util.*;
public class Mutual2 {
public static void main(String[] args) {
BigDecimal shares = new BigDecimal("1754.495");
BigDecimal purchaseAmount = new BigDecimal("2000.00");
BigDecimal pricePerShare = new BigDecimal("10.38");
BigDecimal sharesPurchased = purchaseAmount.divide(pricePerShare, 3, BigDecimal.ROUND_HALF_UP);
shares = shares.add(sharesPurchased);
BigDecimal accountValue = shares.multiply(pricePerShare);
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
double dAccountValue = accountValue.doubleValue();
String sAccountValue = n.format(dAccountValue);
NumberFormat n2 = NumberFormat.getInstance(Locale.US);
double dShares = shares.doubleValue();
String sShares = n2.format(dShares);
System.out.println("Number of shares = " + sShares);
System.out.println("Account value = " + sAccountValue); }
}
Number of shares = 1,947.173
Account value = $20,211.66
BigDecimal
objects, which represent values, can be added, subtracted, multiplied, and divided. While you can display
BigDecimal
objects using the
toString()
method, it is often preferable to create a
NumberFormat
object to format
doubles
obtained from
BigDecimal
. Now you can add the value of making simple interest calculations and mutual fund transactions in your Java programs.
0人
|
了这篇文章 |
点击图片可刷新验证码请点击后输入验证码博客过2级,无需填写验证码
同时赞一个