Java Reference
In-Depth Information
10.13.2 BigDecimal
BigDecimal contains internally an arbitrary precision integer - unscaled-
Value - and a 32-bit scale value - scale . The value represented by a BigDec-
imal object then corresponds to
unscaledValue / 10 scale
So for the following instance of BigDecimal :
BigDecimal one = new BigDecimal (new BigInteger("1"),
Integer.MAX - VALUE);
the decimal point is 2 31
1 (i.e. 2 147 483 648) places to the left of the 1. You
can obtain a new BigDecimal value with the scale increased by n places with
the method
BigDecimal movePointLeft (int n)
Similarly, you can obtain a new value with the scale decreased by n places using
BigDecimal movePointRight (int n)
Note that in both cases the precision of the unscaled value remains unchanged.
Only the decimal point has moved.
Other methods provide the scale value (as an int ) and the unscaled value (as
an instance of BigInteger ). There are also methods that return a float and a
double type value, with the precision truncated as necessary to fit the narrower
fractional range of these floating-point types.
As with BigInteger , the BigDecimal class contains methods that provide
all the basic arithmetic operations such as add, subtract, multiply, and divide.
However, for the division, one of eight rounding options must be chosen. For
example,
BigDecimal bd1 = new BigDecimal (
new BigInteger ( " 1143209523490543953412323238479 " , 12345);
BigDecimal bd2 = new BigDecimal
( " 3.4548738754398454599999997876786578479 " );
BigDecimal bd4
= bd2.divide (bd1, BigDecimal.ROUND - DOWN);
// = bd2/bd1
Here the division rounds towards zero. Other rounding style constants defined in
the BigDecimal class include ROUND - UP , ROUND - FLOOR , ROUND - CEILING ,
etc. See the API documentation for rounding details.
Search WWH ::




Custom Search