12.4 Big Decimal Numbers

   

 
Java Number Cruncher: The Java Programmer's Guide to Numerical Computing
By Ronald  Mak

Table of Contents
Chapter  12.   Big Numbers

12.4 Big Decimal Numbers

BigDecimal values are useful for dealing with very large decimal values and when we must have "exact arithmetic." The prototypical example is keeping track of the U.S. national debt down to the last penny.

Like BigInteger , class BigDecimal values have arbitrary precision. BigDecimal values also have a fractional part. The scale of a BigDecimal value is the number of digits in the fractional part, all of which are considered significant digits.

BigDecimal includes methods to perform the basic arithmetic operations, and these methods all create new BigDecimal objects. They include abs() , add() , divide() , max() , min() , multiply() , negate() , and subtract() . The scale of a result object depends on the scale of the operands it's always large enough so that no digits of precision are lost.

Like the BigInteger class, there are also the methods signum () and compareTo() , as well as the factory method valueOf() , which creates a BigDecimal value from a double value. Methods scale() and setScale() get and set the value's scale, respectively, with the latter returning a new object. Methods movePointLeft() and movePointRight() return new objects where the decimal point has been moved to the left or right by a specified number of digits.

A unique feature of class BigDecimal is that it allows you to choose how the arithmetic operations, such as division, round the fractional parts of their results to a given scale. There are eight rounding modes, two of which are of interest in this chapter. ROUND_DOWN rounds toward zero. Fractional digits beyond the specified scale are simply dropped. ROUND_HALF_EVEN rounds a value toward its nearest neighbor with the given scale. If the value being rounded is exactly halfway between two neighbors, the chosen value is that of the neighbor whose rightmost digit is even. These rounding constants are passed as arguments, along with the desired scale, to methods such as divide() and setScale() .


   
Top
 


Java Number Cruncher. The Java Programmer's Guide to Numerical Computing
Java Number Cruncher: The Java Programmers Guide to Numerical Computing
ISBN: 0130460419
EAN: 2147483647
Year: 2001
Pages: 141
Authors: Ronald Mak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net