Java Reference
In-Depth Information
and performance requirements, it might be worth using Math.round() to achieve ba-
sic rounding if performance becomes an issue.
To provide specific rounding with the BigDecimal class, you should use a
MathContext object or the RoundingMode enumeration values. In either case,
such precision can be omitted by using a currency-formatting solution such as the one
demonstrated in the solution example. BigDecimal objects have mathematical im-
plementations built into them, so performing such operations is an easy task. The arith-
metic operations that you can use are described in Table 4-5 .
Table 4-5 . BigDecimal Arithmetic Methods
Method
Description
Adds one BigDecimal object value to another.
add()
Subtracts one BigDecimal object value from another.
subtract()
Multiplies the value of one BigDecimal object by another.
multiply()
Returns the absolute value of the given BigDecimal object value.
abs()
pow(n)
Returns the BigDecimal to the power of n ; the power is computed to un-
limited precision.
After performing the calculations you require, call the doubleValue() method
on the BigInteger object to convert and obtain a double . You can then format the
double using the NumberFormat class for currency results.
4-6. Randomly Generating Values
Problem
An application that you are developing requires the use of randomly generated num-
bers.
Solution #1
 
 
Search WWH ::




Custom Search