Java Reference
In-Depth Information
But at some point you will run into limits. Either the compiler will specify an
upper limit on the number of decimal positions available (traditionally 17 digits in
COBOL) or a limit is defined in the external representation of the number (for
printing or for storage in a database, for example).
In these cases, result values must be cast into smaller variables. The COBOL de-
veloper can control the precision of the result of this casting by defining the preci-
sion of the variables. The developer also has some ability to specify how rounding
should be handled.
01 DECIMAL-ITEMS USAGE IS COMP-3.
03 DOLLAR-AMOUNT PIC S9(7)V(2) VALUE "1234567.12".
03 CURRENCY-RATE PIC S9(3)V9(5) VALUE "123.12345".
03 EXCHANGE-AMOUNT PIC S9(10)V9(4).
MULTIPLY DOLLAR-AMOUNT BY CURRENCY-RATE GIVING
EXCHANGE-AMOUNT.
MULTIPLY DOLLAR-AMOUNT BY CURRENCY-RATE GIVING
EXCHANGE-AMOUNT ROUNDED.
In the first example, any digits beyond the 10-3 position will be truncated from
the (intermediate) result before being moved into EXCHANGE-AMOUNT. In the
second example, the digit in the 10-4 position will be evaluated. If greater than 4,
the previous digit will be incremented by 1. The remaining digits will be truncated.
Java allows for similar types of fixed-precision math functions with its Big-
Decimal object type and to a lesser extent its BigInteger object type. Both types are ex-
amples of arbitrary precision data types. This means they are automatically defined to
be the correct size and can, in theory, hold any result. Further, the developer can spec-
ify (even at runtime) any number of decimal positions (that is, the scale) in a Big-
Decimal number. As an added bonus, Java provides eight different rounding options,
allowing the developer to have complete control when moving intermediate results
into smaller target variables (for external storage or for printing, for example).
BigDecimal dollarAmount = new BigDecimal ("12345678901.12");
BigDecimal currencyRate = new BigDecimal ("123.12345");
BigDecimal exchangeAmount = new BigDecimal;
exchangeAmount = dollarAmount.multiply (currencyRate);
exchangeAmount = dollarAmount.multiply (currencyRate,
ROUND_HALF_UP);
The static integers shown in Table 8.5 can be passed into some of the math
functions of BigDecimal s to control their rounding functions.
Search WWH ::




Custom Search