Java Reference
In-Depth Information
B IG N UMBERS
Although Java does not define a primitive data type similar to COBOL's familiar
packed decimal, Java defines two classes that are similar. These support math functions
for numbers of arbitrary (and user-defined) precision. When you use these classes in-
stead of the primitive float and double intrinsic data types, there is no requirement to
work around the precision problems of traditional floating-point arithmetic. The Big-
Integer class supports arbitrary precision integer arithmetic, and BigDecimal supports
arbitrary precision arithmetic with scale (that is, decimal positions). With Java 1.5,
BigDecimal also supports fixed precision floating-point computation.
Both BigInteger and BigDecimal have constructors with a String as a parame-
ter. This is often how a BigNumber is initialized:
BigInteger customerNumber =
new BigInteger ("123456789012345678901234567890");
BigDecimal currencyValue =
new BigDecimal ("4.567890123456789012345");
BigDecimal customerOrder =
new BigDecimal (customerNumber, 10);
In the example, currencyValue will have a scale attribute (that is, the number
of digits to the right of the decimal) of 11. customerOrder would contain the nu-
meric value in customerNumber , with a scale of 10. You can also use the static
method valueOf() to set a BigNumber to a value:
BigInteger currencyValue = BigInteger.valueOf(123);
BigDecimal currencyValue = BigDecimal.valueOf(123, scale);s
These classes do come with a cost, however. Math functions using these classes
are considerably slower than math functions that use the primitive data types. An-
other inconvenience: You have to use the math functions the classes provide rather
than the native Java operators (+, -, *, /, and so forth).
Search WWH ::




Custom Search