KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > math > BigDecimal


1 /*
2  * @(#)BigDecimal.java 1.56 06/02/08
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * @(#)BigDecimal.java 1.x 01/xx/xx
10  *
11  * Copyright 1996-2001 Sun Microsystems, Inc. All Rights Reserved.
12  * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
13  *
14  * This software is the proprietary information of Sun Microsystems, Inc.
15  * Use is subject to license terms.
16  *
17  */

18
19 package java.math;
20
21 /**
22  * Immutable, arbitrary-precision signed decimal numbers. A
23  * <tt>BigDecimal</tt> consists of an arbitrary precision integer
24  * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
25  * or positive, the scale is the number of digits to the right of the
26  * decimal point. If negative, the unscaled value of the number is
27  * multiplied by ten to the power of the negation of the scale. The
28  * value of the number represented by the <tt>BigDecimal</tt> is
29  * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
30  *
31  * <p>The <tt>BigDecimal</tt> class provides operations for
32  * arithmetic, scale manipulation, rounding, comparison, hashing, and
33  * format conversion. The {@link #toString} method provides a
34  * canonical representation of a <tt>BigDecimal</tt>.
35  *
36  * <p>The <tt>BigDecimal</tt> class gives its user complete control
37  * over rounding behavior. If no rounding mode is specified and the
38  * exact result cannot be represented, an exception is thrown;
39  * otherwise, calculations can be carried out to a chosen precision
40  * and rounding mode by supplying an appropriate {@link MathContext}
41  * object to the operation. In either case, eight <em>rounding
42  * modes</em> are provided for the control of rounding. Using the
43  * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
44  * represent rounding mode is largely obsolete; the enumeration values
45  * of the <tt>RoundingMode</tt> <tt>enum</tt>, (such as {@link
46  * RoundingMode#HALF_UP}) should be used instead.
47  *
48  * <p>When a <tt>MathContext</tt> object is supplied with a precision
49  * setting of 0 (for example, {@link MathContext#UNLIMITED}),
50  * arithmetic operations are exact, as are the arithmetic methods
51  * which take no <tt>MathContext</tt> object. (This is the only
52  * behavior that was supported in releases prior to 5.) As a
53  * corollary of computing the exact result, the rounding mode setting
54  * of a <tt>MathContext</tt> object with a precision setting of 0 is
55  * not used and thus irrelevant. In the case of divide, the exact
56  * quotient could have an infinitely long decimal expansion; for
57  * example, 1 divided by 3. If the quotient has a nonterminating
58  * decimal expansion and the operation is specified to return an exact
59  * result, an <tt>ArithmeticException</tt> is thrown. Otherwise, the
60  * exact result of the division is returned, as done for other
61  * operations.
62  *
63  * <p>When the precision setting is not 0, the rules of
64  * <tt>BigDecimal</tt> arithmetic are broadly compatible with selected
65  * modes of operation of the arithmetic defined in ANSI X3.274-1996
66  * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
67  * standards, <tt>BigDecimal</tt> includes many rounding modes, which
68  * were mandatory for division in <tt>BigDecimal</tt> releases prior
69  * to 5. Any conflicts between these ANSI standards and the
70  * <tt>BigDecimal</tt> specification are resolved in favor of
71  * <tt>BigDecimal</tt>.
72  *
73  * <p>Since the same numerical value can have different
74  * representations (with different scales), the rules of arithmetic
75  * and rounding must specify both the numerical result and the scale
76  * used in the result's representation.
77  *
78  *
79  * <p>In general the rounding modes and precision setting determine
80  * how operations return results with a limited number of digits when
81  * the exact result has more digits (perhaps infinitely many in the
82  * case of division) than the number of digits returned.
83  *
84  * First, the
85  * total number of digits to return is specified by the
86  * <tt>MathContext</tt>'s <tt>precision</tt> setting; this determines
87  * the result's <i>precision</i>. The digit count starts from the
88  * leftmost nonzero digit of the exact result. The rounding mode
89  * determines how any discarded trailing digits affect the returned
90  * result.
91  *
92  * <p>For all arithmetic operators , the operation is carried out as
93  * though an exact intermediate result were first calculated and then
94  * rounded to the number of digits specified by the precision setting
95  * (if necessary), using the selected rounding mode. If the exact
96  * result is not returned, some digit positions of the exact result
97  * are discarded. When rounding increases the magnitude of the
98  * returned result, it is possible for a new digit position to be
99  * created by a carry propagating to a leading &quot;9&quot; digit.
100  * For example, rounding the value 999.9 to three digits rounding up
101  * would be numerically equal to one thousand, represented as
102  * 100&times;10<sup>1</sup>. In such cases, the new &quot;1&quot; is
103  * the leading digit position of the returned result.
104  *
105  * <p>Besides a logical exact result, each arithmetic operation has a
106  * preferred scale for representing a result. The preferred
107  * scale for each operation is listed in the table below.
108  *
109  * <table border>
110  * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
111  * </h3></caption>
112  * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
113  * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
114  * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
115  * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
116  * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
117  * </table>
118  *
119  * These scales are the ones used by the methods which return exact
120  * arithmetic results; except that an exact divide may have to use a
121  * larger scale since the exact result may have more digits. For
122  * example, <tt>1/32</tt> is <tt>0.03125</tt>.
123  *
124  * <p>Before rounding, the scale of the logical exact intermediate
125  * result is the preferred scale for that operation. If the exact
126  * numerical result cannot be represented in <code>precision</code>
127  * digits, rounding selects the set of digits to return and the scale
128  * of the result is reduced from the scale of the intermediate result
129  * to the least scale which can represent the <code>precision</code>
130  * digits actually returned. If the exact result can be represented
131  * with at most <code>precision</code> digits, the representation
132  * of the result with the scale closest to the preferred scale is
133  * returned. In particular, an exactly representable quotient may be
134  * represented in fewer than <code>precision</code> digits by removing
135  * trailing zeros and decreasing the scale. For example, rounding to
136  * three digits using the {@linkplain RoundingMode#FLOOR floor}
137  * rounding mode, <br>
138  *
139  * <code>19/100 = 0.19 // integer=19, scale=2</code> <br>
140  *
141  * but<br>
142  *
143  * <code>21/110 = 0.190 // integer=190, scale=3</code> <br>
144  *
145  * <p>Note that for add, subtract, and multiply, the reduction in
146  * scale will equal the number of digit positions of the exact result
147  * which are discarded. If the rounding causes a carry propagation to
148  * create a new high-order digit position, an additional digit of the
149  * result is discarded than when no new digit position is created.
150  *
151  * <p>Other methods may have slightly different rounding semantics.
152  * For example, the result of the <tt>pow</tt> method using the
153  * {@linkplain #pow(int, MathContext) specified algorithm} can
154  * occasionally differ from the rounded mathematical result by more
155  * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
156  *
157  * <p>Two types of operations are provided for manipulating the scale
158  * of a <tt>BigDecimal</tt>: scaling/rounding operations and decimal
159  * point motion operations. Scaling/rounding operations ({@link
160  * #setScale setScale} and {@link #round round}) return a
161  * <tt>BigDecimal</tt> whose value is approximately (or exactly) equal
162  * to that of the operand, but whose scale or precision is the
163  * specified value; that is, they increase or decrease the precision
164  * of the stored number with minimal effect on its value. Decimal
165  * point motion operations ({@link #movePointLeft movePointLeft} and
166  * {@link #movePointRight movePointRight}) return a
167  * <tt>BigDecimal</tt> created from the operand by moving the decimal
168  * point a specified distance in the specified direction.
169  *
170  * <p>For the sake of brevity and clarity, pseudo-code is used
171  * throughout the descriptions of <tt>BigDecimal</tt> methods. The
172  * pseudo-code expression <tt>(i + j)</tt> is shorthand for &quot;a
173  * <tt>BigDecimal</tt> whose value is that of the <tt>BigDecimal</tt>
174  * <tt>i</tt> added to that of the <tt>BigDecimal</tt>
175  * <tt>j</tt>.&quot; The pseudo-code expression <tt>(i == j)</tt> is
176  * shorthand for &quot;<tt>true</tt> if and only if the
177  * <tt>BigDecimal</tt> <tt>i</tt> represents the same value as the
178  * <tt>BigDecimal</tt> <tt>j</tt>.&quot; Other pseudo-code expressions
179  * are interpreted similarly. Square brackets are used to represent
180  * the particular <tt>BigInteger</tt> and scale pair defining a
181  * <tt>BigDecimal</tt> value; for example [19, 2] is the
182  * <tt>BigDecimal</tt> numerically equal to 0.19 having a scale of 2.
183  *
184  * <p>Note: care should be exercised if <tt>BigDecimal</tt> objects
185  * are used as keys in a {@link java.util.SortedMap SortedMap} or
186  * elements in a {@link java.util.SortedSet SortedSet} since
187  * <tt>BigDecimal</tt>'s <i>natural ordering</i> is <i>inconsistent
188  * with equals</i>. See {@link Comparable}, {@link
189  * java.util.SortedMap} or {@link java.util.SortedSet} for more
190  * information.
191  *
192  * <p>All methods and constructors for this class throw
193  * <tt>NullPointerException</tt> when passed a <tt>null</tt> object
194  * reference for any input parameter.
195  *
196  * @see BigInteger
197  * @see MathContext
198  * @see RoundingMode
199  * @see java.util.SortedMap
200  * @see java.util.SortedSet
201  * @author Josh Bloch
202  * @author Mike Cowlishaw
203  * @author Joseph D. Darcy
204  */

205 public class BigDecimal extends Number JavaDoc implements Comparable JavaDoc<BigDecimal JavaDoc> {
206     /**
207      * The unscaled value of this BigDecimal, as returned by {@link
208      * #unscaledValue}.
209      *
210      * @serial
211      * @see #unscaledValue
212      */

213     private volatile BigInteger JavaDoc intVal;
214
215     /**
216      * The scale of this BigDecimal, as returned by {@link #scale}.
217      *
218      * @serial
219      * @see #scale
220      */

221     private int scale = 0; // Note: this may have any value, so
222
// calculations must be done in longs
223
/**
224      * The number of decimal digits in this BigDecimal, or 0 if the
225      * number of digits are not known (lookaside information). If
226      * nonzero, the value is guaranteed correct. Use the precision()
227      * method to obtain and set the value if it might be 0. This
228      * field is mutable until set nonzero.
229      *
230      * @since 1.5
231      */

232     private volatile transient int precision = 0;
233
234     /**
235      * Used to store the canonical string representation, if computed.
236      */

237     private volatile transient String JavaDoc stringCache = null;
238
239     /**
240      * Sentinel value for {@link #intCompact} indicating the
241      * significand information is only available from {@code intVal}.
242      */

243     private static final long INFLATED = Long.MIN_VALUE;
244
245     /**
246      * If the absolute value of the significand of this BigDecimal is
247      * less than or equal to {@code Long.MAX_VALUE}, the value can be
248      * compactly stored in this field and used in computations.
249      */

250     private transient long intCompact = INFLATED;
251
252     // All 18-digit base ten strings fit into a long; not all 19-digit
253
// strings will
254
private static final int MAX_COMPACT_DIGITS = 18;
255
256     private static final int MAX_BIGINT_BITS = 62;
257
258     /* Appease the serialization gods */
259     private static final long serialVersionUID = 6108874887143696463L;
260
261     // Cache of common small BigDecimal values.
262
private static final BigDecimal JavaDoc zeroThroughTen[] = {
263     new BigDecimal JavaDoc(BigInteger.ZERO, 0, 0),
264         new BigDecimal JavaDoc(BigInteger.ONE, 1, 0),
265         new BigDecimal JavaDoc(BigInteger.valueOf(2), 2, 0),
266         new BigDecimal JavaDoc(BigInteger.valueOf(3), 3, 0),
267         new BigDecimal JavaDoc(BigInteger.valueOf(4), 4, 0),
268         new BigDecimal JavaDoc(BigInteger.valueOf(5), 5, 0),
269         new BigDecimal JavaDoc(BigInteger.valueOf(6), 6, 0),
270         new BigDecimal JavaDoc(BigInteger.valueOf(7), 7, 0),
271         new BigDecimal JavaDoc(BigInteger.valueOf(8), 8, 0),
272         new BigDecimal JavaDoc(BigInteger.valueOf(9), 9, 0),
273         new BigDecimal JavaDoc(BigInteger.TEN, 10, 0),
274     };
275
276     // Constants
277
/**
278      * The value 0, with a scale of 0.
279      *
280      * @since 1.5
281      */

282     public static final BigDecimal JavaDoc ZERO =
283         zeroThroughTen[0];
284
285     /**
286      * The value 1, with a scale of 0.
287      *
288      * @since 1.5
289      */

290     public static final BigDecimal JavaDoc ONE =
291         zeroThroughTen[1];
292
293     /**
294      * The value 10, with a scale of 0.
295      *
296      * @since 1.5
297      */

298     public static final BigDecimal JavaDoc TEN =
299     zeroThroughTen[10];
300
301     // Constructors
302

303     /**
304      * Translates a character array representation of a
305      * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
306      * same sequence of characters as the {@link #BigDecimal(String)}
307      * constructor, while allowing a sub-array to be specified.
308      *
309      * <p>Note that if the sequence of characters is already available
310      * within a character array, using this constructor is faster than
311      * converting the <tt>char</tt> array to string and using the
312      * <tt>BigDecimal(String)</tt> constructor .
313      *
314      * @param in <tt>char</tt> array that is the source of characters.
315      * @param offset first character in the array to inspect.
316      * @param len number of characters to consider.
317      * @throws NumberFormatException if <tt>in</tt> is not a valid
318      * representation of a <tt>BigDecimal</tt> or the defined subarray
319      * is not wholly within <tt>in</tt>.
320      * @since 1.5
321      */

322     public BigDecimal(char[] in, int offset, int len) {
323         // This is the primary string to BigDecimal constructor; all
324
// incoming strings end up here; it uses explicit (inline)
325
// parsing for speed and generates at most one intermediate
326
// (temporary) object (a char[] array).
327

328         // use array bounds checking to handle too-long, len == 0,
329
// bad offset, etc.
330
try {
331             // handle the sign
332
boolean isneg = false; // assume positive
333
if (in[offset] == '-') {
334                 isneg = true; // leading minus means negative
335
offset++;
336                 len--;
337             } else if (in[offset] == '+') { // leading + allowed
338
offset++;
339                 len--;
340             }
341
342             // should now be at numeric part of the significand
343
int dotoff = -1; // '.' offset, -1 if none
344
int cfirst = offset; // record start of integer
345
long exp = 0; // exponent
346
if (len > in.length) // protect against huge length
347
throw new NumberFormatException JavaDoc();
348             char coeff[] = new char[len]; // integer significand array
349
char c; // work
350

351             for (; len > 0; offset++, len--) {
352                 c = in[offset];
353                 if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
354                     // have digit
355
coeff[precision] = c;
356                     precision++; // count of digits
357
continue;
358                 }
359                 if (c == '.') {
360                     // have dot
361
if (dotoff >= 0) // two dots
362
throw new NumberFormatException JavaDoc();
363                     dotoff = offset;
364                     continue;
365                 }
366                 // exponent expected
367
if ((c != 'e') && (c != 'E'))
368                     throw new NumberFormatException JavaDoc();
369                 offset++;
370                 c = in[offset];
371                 len--;
372                 boolean negexp = false;
373                 // optional sign
374
if (c == '-' || c == '+') {
375                     negexp = (c == '-');
376                     offset++;
377                     c = in[offset];
378                     len--;
379                 }
380                 if (len <= 0) // no exponent digits
381
throw new NumberFormatException JavaDoc();
382         // skip leading zeros in the exponent
383
while (len > 10 && Character.digit(c, 10) == 0) {
384             offset++;
385             c = in[offset];
386             len--;
387         }
388         if (len > 10) // too many nonzero exponent digits
389
throw new NumberFormatException JavaDoc();
390                 // c now holds first digit of exponent
391
for (;; len--) {
392                     int v;
393                     if (c >= '0' && c <= '9') {
394                         v = c - '0';
395                     } else {
396                         v = Character.digit(c, 10);
397                         if (v < 0) // not a digit
398
throw new NumberFormatException JavaDoc();
399                     }
400                     exp = exp * 10 + v;
401                     if (len == 1)
402                         break; // that was final character
403
offset++;
404                     c = in[offset];
405                 }
406                 if (negexp) // apply sign
407
exp = -exp;
408                 // Next test is required for backwards compatibility
409
if ((int)exp != exp) // overflow
410
throw new NumberFormatException JavaDoc();
411                 break; // [saves a test]
412
}
413             // here when no characters left
414
if (precision == 0) // no digits found
415
throw new NumberFormatException JavaDoc();
416
417             if (dotoff >= 0) { // had dot; set scale
418
scale = precision - (dotoff - cfirst);
419                 // [cannot overflow]
420
}
421             if (exp != 0) { // had significant exponent
422
try {
423             scale = checkScale(-exp + scale); // adjust
424
} catch (ArithmeticException JavaDoc e) {
425             throw new NumberFormatException JavaDoc("Scale out of range.");
426         }
427             }
428
429             // Remove leading zeros from precision (digits count)
430
int first = 0;
431             for (; (coeff[first] == '0' || Character.digit(coeff[first], 10) == 0) &&
432              precision > 1;
433          first++)
434                 precision--;
435
436         // Set the significand ..
437
// Copy significand to exact-sized array, with sign if
438
// negative
439
// Later use: BigInteger(coeff, first, precision) for
440
// both cases, by allowing an extra char at the front of
441
// coeff.
442
char quick[];
443         if (!isneg) {
444         quick = new char[precision];
445         System.arraycopy(coeff, first, quick, 0, precision);
446         } else {
447         quick = new char[precision+1];
448         quick[0] = '-';
449         System.arraycopy(coeff, first, quick, 1, precision);
450         }
451         if (precision <= MAX_COMPACT_DIGITS)
452         intCompact = Long.parseLong(new String JavaDoc(quick));
453         else
454         intVal = new BigInteger JavaDoc(quick);
455         // System.out.println(" new: " +intVal+" ["+scale+"] "+precision);
456
} catch (ArrayIndexOutOfBoundsException JavaDoc e) {
457             throw new NumberFormatException JavaDoc();
458         } catch (NegativeArraySizeException JavaDoc e) {
459             throw new NumberFormatException JavaDoc();
460         }
461     }
462
463     /**
464      * Translates a character array representation of a
465      * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
466      * same sequence of characters as the {@link #BigDecimal(String)}
467      * constructor, while allowing a sub-array to be specified and
468      * with rounding according to the context settings.
469      *
470      * <p>Note that if the sequence of characters is already available
471      * within a character array, using this constructor is faster than
472      * converting the <tt>char</tt> array to string and using the
473      * <tt>BigDecimal(String)</tt> constructor .
474      *
475      * @param in <tt>char</tt> array that is the source of characters.
476      * @param offset first character in the array to inspect.
477      * @param len number of characters to consider..
478      * @param mc the context to use.
479      * @throws ArithmeticException if the result is inexact but the
480      * rounding mode is <tt>UNNECESSARY</tt>.
481      * @throws NumberFormatException if <tt>in</tt> is not a valid
482      * representation of a <tt>BigDecimal</tt> or the defined subarray
483      * is not wholly within <tt>in</tt>.
484      * @since 1.5
485      */

486     public BigDecimal(char[] in, int offset, int len, MathContext JavaDoc mc) {
487         this(in, offset, len);
488         if (mc.precision > 0)
489             roundThis(mc);
490     }
491
492     /**
493      * Translates a character array representation of a
494      * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
495      * same sequence of characters as the {@link #BigDecimal(String)}
496      * constructor.
497      *
498      * <p>Note that if the sequence of characters is already available
499      * as a character array, using this constructor is faster than
500      * converting the <tt>char</tt> array to string and using the
501      * <tt>BigDecimal(String)</tt> constructor .
502      *
503      * @param in <tt>char</tt> array that is the source of characters.
504      * @throws NumberFormatException if <tt>in</tt> is not a valid
505      * representation of a <tt>BigDecimal</tt>.
506      * @since 1.5
507      */

508     public BigDecimal(char[] in) {
509         this(in, 0, in.length);
510     }
511
512     /**
513      * Translates a character array representation of a
514      * <tt>BigDecimal</tt> into a <tt>BigDecimal</tt>, accepting the
515      * same sequence of characters as the {@link #BigDecimal(String)}
516      * constructor and with rounding according to the context
517      * settings.
518      *
519      * <p>Note that if the sequence of characters is already available
520      * as a character array, using this constructor is faster than
521      * converting the <tt>char</tt> array to string and using the
522      * <tt>BigDecimal(String)</tt> constructor .
523      *
524      * @param in <tt>char</tt> array that is the source of characters.
525      * @param mc the context to use.
526      * @throws ArithmeticException if the result is inexact but the
527      * rounding mode is <tt>UNNECESSARY</tt>.
528      * @throws NumberFormatException if <tt>in</tt> is not a valid
529      * representation of a <tt>BigDecimal</tt>.
530      * @since 1.5
531      */

532     public BigDecimal(char[] in, MathContext JavaDoc mc) {
533         this(in, 0, in.length, mc);
534     }
535
536     /**
537      * Translates the string representation of a <tt>BigDecimal</tt>
538      * into a <tt>BigDecimal</tt>. The string representation consists
539      * of an optional sign, <tt>'+'</tt> (<tt>'&#92;u002B'</tt>) or
540      * <tt>'-'</tt> (<tt>'&#92;u002D'</tt>), followed by a sequence of
541      * zero or more decimal digits ("the integer"), optionally
542      * followed by a fraction, optionally followed by an exponent.
543      *
544      * <p>The fraction consists of a decimal point followed by zero
545      * or more decimal digits. The string must contain at least one
546      * digit in either the integer or the fraction. The number formed
547      * by the sign, the integer and the fraction is referred to as the
548      * <i>significand</i>.
549      *
550      * <p>The exponent consists of the character <tt>'e'</tt>
551      * (<tt>'&#92;u0075'</tt>) or <tt>'E'</tt> (<tt>'&#92;u0045'</tt>)
552      * followed by one or more decimal digits. The value of the
553      * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
554      * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
555      *
556      * <p>More formally, the strings this constructor accepts are
557      * described by the following grammar:
558      * <blockquote>
559      * <dl>
560      * <dt><i>BigDecimalString:</i>
561      * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
562      * <p>
563      * <dt><i>Sign:</i>
564      * <dd><tt>+</tt>
565      * <dd><tt>-</tt>
566      * <p>
567      * <dt><i>Significand:</i>
568      * <dd><i>IntegerPart</i> <tt>.</tt> <i>FractionPart<sub>opt</sub></i>
569      * <dd><tt>.</tt> <i>FractionPart</i>
570      * <dd><i>IntegerPart</i>
571      * <p>
572      * <dt><i>IntegerPart:
573      * <dd>Digits</i>
574      * <p>
575      * <dt><i>FractionPart:
576      * <dd>Digits</i>
577      * <p>
578      * <dt><i>Exponent:
579      * <dd>ExponentIndicator SignedInteger</i>
580      * <p>
581      * <dt><i>ExponentIndicator:</i>
582      * <dd><tt>e</tt>
583      * <dd><tt>E</tt>
584      * <p>
585      * <dt><i>SignedInteger:
586      * <dd>Sign<sub>opt</sub> Digits</i>
587      * <p>
588      * <dt><i>Digits:
589      * <dd>Digit
590      * <dd>Digits Digit</i>
591      * <p>
592      * <dt><i>Digit:</i>
593      * <dd>any character for which {@link Character#isDigit}
594      * returns <tt>true</tt>, including 0, 1, 2 ...
595      * </dl>
596      * </blockquote>
597      *
598      * <p>The scale of the returned <tt>BigDecimal</tt> will be the
599      * number of digits in the fraction, or zero if the string
600      * contains no decimal point, subject to adjustment for any
601      * exponent; if the string contains an exponent, the exponent is
602      * subtracted from the scale. The value of the resulting scale
603      * must lie between <tt>Integer.MIN_VALUE</tt> and
604      * <tt>Integer.MAX_VALUE</tt>, inclusive.
605      *
606      * <p>The character-to-digit mapping is provided by {@link
607      * java.lang.Character#digit} set to convert to radix 10. The
608      * String may not contain any extraneous characters (whitespace,
609      * for example).
610      *
611      * <p><b>Examples:</b><br>
612      * The value of the returned <tt>BigDecimal</tt> is equal to
613      * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
614      * For each string on the left, the resulting representation
615      * [<tt>BigInteger</tt>, <tt>scale</tt>] is shown on the right.
616      * <pre>
617      * "0" [0,0]
618      * "0.00" [0,2]
619      * "123" [123,0]
620      * "-123" [-123,0]
621      * "1.23E3" [123,-1]
622      * "1.23E+3" [123,-1]
623      * "12.3E+7" [123,-6]
624      * "12.0" [120,1]
625      * "12.3" [123,1]
626      * "0.00123" [123,5]
627      * "-1.23E-12" [-123,14]
628      * "1234.5E-4" [12345,5]
629      * "0E+7" [0,-7]
630      * "-0" [0,0]
631      * </pre>
632      *
633      * <p>Note: For values other than <tt>float</tt> and
634      * <tt>double</tt> NaN and &plusmn;Infinity, this constructor is
635      * compatible with the values returned by {@link Float#toString}
636      * and {@link Double#toString}. This is generally the preferred
637      * way to convert a <tt>float</tt> or <tt>double</tt> into a
638      * BigDecimal, as it doesn't suffer from the unpredictability of
639      * the {@link #BigDecimal(double)} constructor.
640      *
641      * @param val String representation of <tt>BigDecimal</tt>.
642      *
643      * @throws NumberFormatException if <tt>val</tt> is not a valid
644      * representation of a <tt>BigDecimal</tt>.
645      */

646     public BigDecimal(String JavaDoc val) {
647         this(val.toCharArray(), 0, val.length());
648     }
649
650     /**
651      * Translates the string representation of a <tt>BigDecimal</tt>
652      * into a <tt>BigDecimal</tt>, accepting the same strings as the
653      * {@link #BigDecimal(String)} constructor, with rounding
654      * according to the context settings.
655      *
656      * @param val string representation of a <tt>BigDecimal</tt>.
657      * @param mc the context to use.
658      * @throws ArithmeticException if the result is inexact but the
659      * rounding mode is <tt>UNNECESSARY</tt>.
660      * @throws NumberFormatException if <tt>val</tt> is not a valid
661      * representation of a BigDecimal.
662      * @since 1.5
663      */

664     public BigDecimal(String JavaDoc val, MathContext JavaDoc mc) {
665         this(val.toCharArray(), 0, val.length());
666         if (mc.precision > 0)
667             roundThis(mc);
668     }
669
670     /**
671      * Translates a <tt>double</tt> into a <tt>BigDecimal</tt> which
672      * is the exact decimal representation of the <tt>double</tt>'s
673      * binary floating-point value. The scale of the returned
674      * <tt>BigDecimal</tt> is the smallest value such that
675      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
676      * <p>
677      * <b>Notes:</b>
678      * <ol>
679      * <li>
680      * The results of this constructor can be somewhat unpredictable.
681      * One might assume that writing <tt>new BigDecimal(0.1)</tt> in
682      * Java creates a <tt>BigDecimal</tt> which is exactly equal to
683      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
684      * actually equal to
685      * 0.1000000000000000055511151231257827021181583404541015625.
686      * This is because 0.1 cannot be represented exactly as a
687      * <tt>double</tt> (or, for that matter, as a binary fraction of
688      * any finite length). Thus, the value that is being passed
689      * <i>in</i> to the constructor is not exactly equal to 0.1,
690      * appearances notwithstanding.
691      *
692      * <li>
693      * The <tt>String</tt> constructor, on the other hand, is
694      * perfectly predictable: writing <tt>new BigDecimal("0.1")</tt>
695      * creates a <tt>BigDecimal</tt> which is <i>exactly</i> equal to
696      * 0.1, as one would expect. Therefore, it is generally
697      * recommended that the {@linkplain #BigDecimal(String)
698      * <tt>String</tt> constructor} be used in preference to this one.
699      *
700      * <li>
701      * When a <tt>double</tt> must be used as a source for a
702      * <tt>BigDecimal</tt>, note that this constructor provides an
703      * exact conversion; it does not give the same result as
704      * converting the <tt>double</tt> to a <tt>String</tt> using the
705      * {@link Double#toString(double)} method and then using the
706      * {@link #BigDecimal(String)} constructor. To get that result,
707      * use the <tt>static</tt> {@link #valueOf(double)} method.
708      * </ol>
709      *
710      * @param val <tt>double</tt> value to be converted to
711      * <tt>BigDecimal</tt>.
712      * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
713      */

714     public BigDecimal(double val) {
715     if (Double.isInfinite(val) || Double.isNaN(val))
716         throw new NumberFormatException JavaDoc("Infinite or NaN");
717
718     // Translate the double into sign, exponent and significand, according
719
// to the formulae in JLS, Section 20.10.22.
720
long valBits = Double.doubleToLongBits(val);
721     int sign = ((valBits >> 63)==0 ? 1 : -1);
722     int exponent = (int) ((valBits >> 52) & 0x7ffL);
723     long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
724                 : (valBits & ((1L<<52) - 1)) | (1L<<52));
725     exponent -= 1075;
726     // At this point, val == sign * significand * 2**exponent.
727

728     /*
729      * Special case zero to supress nonterminating normalization
730      * and bogus scale calculation.
731      */

732     if (significand == 0) {
733         intVal = BigInteger.ZERO;
734         intCompact = 0;
735         precision = 1;
736         return;
737     }
738
739     // Normalize
740
while((significand & 1) == 0) { // i.e., significand is even
741
significand >>= 1;
742         exponent++;
743     }
744
745     // Calculate intVal and scale
746
intVal = BigInteger.valueOf(sign*significand);
747     if (exponent < 0) {
748         intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
749         scale = -exponent;
750     } else if (exponent > 0) {
751         intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
752     }
753     if (intVal.bitLength() <= MAX_BIGINT_BITS) {
754         intCompact = intVal.longValue();
755     }
756     }
757
758     /**
759      * Translates a <tt>double</tt> into a <tt>BigDecimal</tt>, with
760      * rounding according to the context settings. The scale of the
761      * <tt>BigDecimal</tt> is the smallest value such that
762      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
763      *
764      * <p>The results of this constructor can be somewhat unpredictable
765      * and its use is generally not recommended; see the notes under
766      * the {@link #BigDecimal(double)} constructor.
767      *
768      * @param val <tt>double</tt> value to be converted to
769      * <tt>BigDecimal</tt>.
770      * @param mc the context to use.
771      * @throws ArithmeticException if the result is inexact but the
772      * RoundingMode is UNNECESSARY.
773      * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
774      * @since 1.5
775      */

776     public BigDecimal(double val, MathContext JavaDoc mc) {
777         this(val);
778         if (mc.precision > 0)
779             roundThis(mc);
780     }
781
782     /**
783      * Translates a <tt>BigInteger</tt> into a <tt>BigDecimal</tt>.
784      * The scale of the <tt>BigDecimal</tt> is zero.
785      *
786      * @param val <tt>BigInteger</tt> value to be converted to
787      * <tt>BigDecimal</tt>.
788      */

789     public BigDecimal(BigInteger JavaDoc val) {
790         intVal = val;
791     if (val.bitLength() <= MAX_BIGINT_BITS) {
792         intCompact = val.longValue();
793     }
794     }
795
796     /**
797      * Translates a <tt>BigInteger</tt> into a <tt>BigDecimal</tt>
798      * rounding according to the context settings. The scale of the
799      * <tt>BigDecimal</tt> is zero.
800      *
801      * @param val <tt>BigInteger</tt> value to be converted to
802      * <tt>BigDecimal</tt>.
803      * @param mc the context to use.
804      * @throws ArithmeticException if the result is inexact but the
805      * rounding mode is <tt>UNNECESSARY</tt>.
806      * @since 1.5
807      */

808     public BigDecimal(BigInteger JavaDoc val, MathContext JavaDoc mc) {
809         intVal = val;
810         if (mc.precision > 0)
811             roundThis(mc);
812     }
813
814     /**
815      * Translates a <tt>BigInteger</tt> unscaled value and an
816      * <tt>int</tt> scale into a <tt>BigDecimal</tt>. The value of
817      * the <tt>BigDecimal</tt> is
818      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
819      *
820      * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
821      * @param scale scale of the <tt>BigDecimal</tt>.
822      */

823     public BigDecimal(BigInteger JavaDoc unscaledVal, int scale) {
824         // Negative scales are now allowed
825
intVal = unscaledVal;
826         this.scale = scale;
827     if (unscaledVal.bitLength() <= MAX_BIGINT_BITS) {
828         intCompact = unscaledVal.longValue();
829     }
830     }
831
832     /**
833      * Translates a <tt>BigInteger</tt> unscaled value and an
834      * <tt>int</tt> scale into a <tt>BigDecimal</tt>, with rounding
835      * according to the context settings. The value of the
836      * <tt>BigDecimal</tt> is <tt>(unscaledVal &times;
837      * 10<sup>-scale</sup>)</tt>, rounded according to the
838      * <tt>precision</tt> and rounding mode settings.
839      *
840      * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
841      * @param scale scale of the <tt>BigDecimal</tt>.
842      * @param mc the context to use.
843      * @throws ArithmeticException if the result is inexact but the
844      * rounding mode is <tt>UNNECESSARY</tt>.
845      * @since 1.5
846      */

847     public BigDecimal(BigInteger JavaDoc unscaledVal, int scale, MathContext JavaDoc mc) {
848         intVal = unscaledVal;
849         this.scale = scale;
850         if (mc.precision > 0)
851             roundThis(mc);
852     }
853
854     /**
855      * Translates an <tt>int</tt> into a <tt>BigDecimal</tt>. The
856      * scale of the <tt>BigDecimal</tt> is zero.
857      *
858      * @param val <tt>int</tt> value to be converted to
859      * <tt>BigDecimal</tt>.
860      * @since 1.5
861      */

862     public BigDecimal(int val) {
863     intCompact = val;
864     }
865
866     /**
867      * Translates an <tt>int</tt> into a <tt>BigDecimal</tt>, with
868      * rounding according to the context settings. The scale of the
869      * <tt>BigDecimal</tt>, before any rounding, is zero.
870      *
871      * @param val <tt>int</tt> value to be converted to <tt>BigDecimal</tt>.
872      * @param mc the context to use.
873      * @throws ArithmeticException if the result is inexact but the
874      * rounding mode is <tt>UNNECESSARY</tt>.
875      * @since 1.5
876      */

877     public BigDecimal(int val, MathContext JavaDoc mc) {
878     intCompact = val;
879         if (mc.precision > 0)
880             roundThis(mc);
881     }
882
883     /**
884      * Translates a <tt>long</tt> into a <tt>BigDecimal</tt>. The
885      * scale of the <tt>BigDecimal</tt> is zero.
886      *
887      * @param val <tt>long</tt> value to be converted to <tt>BigDecimal</tt>.
888      * @since 1.5
889      */

890     public BigDecimal(long val) {
891     if (compactLong(val))
892         intCompact = val;
893     else
894         intVal = BigInteger.valueOf(val);
895     }
896
897     /**
898      * Translates a <tt>long</tt> into a <tt>BigDecimal</tt>, with
899      * rounding according to the context settings. The scale of the
900      * <tt>BigDecimal</tt>, before any rounding, is zero.
901      *
902      * @param val <tt>long</tt> value to be converted to <tt>BigDecimal</tt>.
903      * @param mc the context to use.
904      * @throws ArithmeticException if the result is inexact but the
905      * rounding mode is <tt>UNNECESSARY</tt>.
906      * @since 1.5
907      */

908     public BigDecimal(long val, MathContext JavaDoc mc) {
909     if (compactLong(val))
910         intCompact = val;
911     else
912         intVal = BigInteger.valueOf(val);
913         if (mc.precision > 0)
914             roundThis(mc);
915     }
916
917     /**
918      * Trusted internal constructor
919      */

920     private BigDecimal(long val, int scale) {
921     this.intCompact = val;
922     this.scale = scale;
923     }
924
925     /**
926      * Trusted internal constructor
927      */

928     private BigDecimal(BigInteger JavaDoc intVal, long val, int scale) {
929     this.intVal = intVal;
930     this.intCompact = val;
931     this.scale = scale;
932     }
933
934     // Static Factory Methods
935

936     /**
937      * Translates a <tt>long</tt> unscaled value and an
938      * <tt>int</tt> scale into a <tt>BigDecimal</tt>. This
939      * &quot;static factory method&quot; is provided in preference to
940      * a (<tt>long</tt>, <tt>int</tt>) constructor because it
941      * allows for reuse of frequently used <tt>BigDecimal</tt> values..
942      *
943      * @param unscaledVal unscaled value of the <tt>BigDecimal</tt>.
944      * @param scale scale of the <tt>BigDecimal</tt>.
945      * @return a <tt>BigDecimal</tt> whose value is
946      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
947      */

948     public static BigDecimal JavaDoc valueOf(long unscaledVal, int scale) {
949         if (scale == 0 && unscaledVal >= 0 && unscaledVal <= 10) {
950         return zeroThroughTen[(int)unscaledVal];
951         }
952     if (compactLong(unscaledVal))
953         return new BigDecimal JavaDoc(unscaledVal, scale);
954         return new BigDecimal JavaDoc(BigInteger.valueOf(unscaledVal), scale);
955     }
956
957     /**
958      * Translates a <tt>long</tt> value into a <tt>BigDecimal</tt>
959      * with a scale of zero. This &quot;static factory method&quot;
960      * is provided in preference to a (<tt>long</tt>) constructor
961      * because it allows for reuse of frequently used
962      * <tt>BigDecimal</tt> values.
963      *
964      * @param val value of the <tt>BigDecimal</tt>.
965      * @return a <tt>BigDecimal</tt> whose value is <tt>val</tt>.
966      */

967     public static BigDecimal JavaDoc valueOf(long val) {
968     return valueOf(val, 0);
969     }
970
971     /**
972      * Translates a <tt>double</tt> into a <tt>BigDecimal</tt>, using
973      * the <tt>double</tt>'s canonical string representation provided
974      * by the {@link Double#toString(double)} method.
975      *
976      * <p><b>Note:</b> This is generally the preferred way to convert
977      * a <tt>double</tt> (or <tt>float</tt>) into a
978      * <tt>BigDecimal</tt>, as the value returned is equal to that
979      * resulting from constructing a <tt>BigDecimal</tt> from the
980      * result of using {@link Double#toString(double)}.
981      *
982      * @param val <tt>double</tt> to convert to a <tt>BigDecimal</tt>.
983      * @return a <tt>BigDecimal</tt> whose value is equal to or approximately
984      * equal to the value of <tt>val</tt>.
985      * @throws NumberFormatException if <tt>val</tt> is infinite or NaN.
986      * @since 1.5
987      */

988     public static BigDecimal JavaDoc valueOf(double val) {
989         // Reminder: a zero double returns '0.0', so we cannot fastpath
990
// to use the constant ZERO. This might be important enough to
991
// justify a factory approach, a cache, or a few private
992
// constants, later.
993
return new BigDecimal JavaDoc(Double.toString(val));
994     }
995
996     // Arithmetic Operations
997
/**
998      * Returns a <tt>BigDecimal</tt> whose value is <tt>(this +
999      * augend)</tt>, and whose scale is <tt>max(this.scale(),
1000     * augend.scale())</tt>.
1001     *
1002     * @param augend value to be added to this <tt>BigDecimal</tt>.
1003     * @return <tt>this + augend</tt>
1004     */

1005    public BigDecimal JavaDoc add(BigDecimal JavaDoc augend) {
1006        BigDecimal JavaDoc arg[] = {this, augend};
1007        matchScale(arg);
1008
1009    long x = arg[0].intCompact;
1010    long y = arg[1].intCompact;
1011
1012    // Might be able to do a more clever check incorporating the
1013
// inflated check into the overflow computation.
1014
if (x != INFLATED && y != INFLATED) {
1015        long sum = x + y;
1016        /*
1017         * If the sum is not an overflowed value, continue to use
1018         * the compact representation. if either of x or y is
1019         * INFLATED, the sum should also be regarded as an
1020         * overflow. See "Hacker's Delight" section 2-12 for
1021         * explanation of the overflow test.
1022         */

1023        if ( (((sum ^ x) & (sum ^ y)) >> 63) == 0L ) // not overflowed
1024
return BigDecimal.valueOf(sum, arg[0].scale);
1025    }
1026        return new BigDecimal JavaDoc(arg[0].inflate().intVal.add(arg[1].inflate().intVal), arg[0].scale);
1027    }
1028
1029    /**
1030     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this + augend)</tt>,
1031     * with rounding according to the context settings.
1032     *
1033     * If either number is zero and the precision setting is nonzero then
1034     * the other number, rounded if necessary, is used as the result.
1035     *
1036     * @param augend value to be added to this <tt>BigDecimal</tt>.
1037     * @param mc the context to use.
1038     * @return <tt>this + augend</tt>, rounded as necessary.
1039     * @throws ArithmeticException if the result is inexact but the
1040     * rounding mode is <tt>UNNECESSARY</tt>.
1041     * @since 1.5
1042     */

1043    public BigDecimal JavaDoc add(BigDecimal JavaDoc augend, MathContext JavaDoc mc) {
1044        if (mc.precision == 0)
1045            return add(augend);
1046        BigDecimal JavaDoc lhs = this;
1047
1048    // Could optimize if values are compact
1049
this.inflate();
1050    augend.inflate();
1051    
1052        // If either number is zero then the other number, rounded and
1053
// scaled if necessary, is used as the result.
1054
{
1055        boolean lhsIsZero = lhs.signum() == 0;
1056        boolean augendIsZero = augend.signum() == 0;
1057
1058        if (lhsIsZero || augendIsZero) {
1059        int preferredScale = Math.max(lhs.scale(), augend.scale());
1060        BigDecimal JavaDoc result;
1061
1062        // Could use a factory for zero instead of a new object
1063
if (lhsIsZero && augendIsZero)
1064            return new BigDecimal JavaDoc(BigInteger.ZERO, 0, preferredScale);
1065
1066
1067        result = lhsIsZero ? augend.doRound(mc) : lhs.doRound(mc);
1068
1069        if (result.scale() == preferredScale)
1070            return result;
1071        else if (result.scale() > preferredScale)
1072            return new BigDecimal JavaDoc(result.intVal, result.intCompact, result.scale).
1073            stripZerosToMatchScale(preferredScale);
1074        else { // result.scale < preferredScale
1075
int precisionDiff = mc.precision - result.precision();
1076            int scaleDiff = preferredScale - result.scale();
1077
1078            if (precisionDiff >= scaleDiff)
1079            return result.setScale(preferredScale); // can achieve target scale
1080
else
1081            return result.setScale(result.scale() + precisionDiff);
1082        }
1083        }
1084    }
1085
1086        long padding = (long)lhs.scale - augend.scale;
1087        if (padding != 0) { // scales differ; alignment needed
1088
BigDecimal JavaDoc arg[] = preAlign(lhs, augend, padding, mc);
1089            matchScale(arg);
1090            lhs = arg[0];
1091            augend = arg[1];
1092        }
1093    
1094    return new BigDecimal JavaDoc(lhs.inflate().intVal.add(augend.inflate().intVal),
1095                  lhs.scale).doRound(mc);
1096    }
1097
1098    /**
1099     * Returns an array of length two, the sum of whose entries is
1100     * equal to the rounded sum of the {@code BigDecimal} arguments.
1101     *
1102     * <p>If the digit positions of the arguments have a sufficient
1103     * gap between them, the value smaller in magnitude can be
1104     * condensed into a &quot;sticky bit&quot; and the end result will
1105     * round the same way <em>if</em> the precision of the final
1106     * result does not include the high order digit of the small
1107     * magnitude operand.
1108     *
1109     * <p>Note that while strictly speaking this is an optimization,
1110     * it makes a much wider range of additions practical.
1111     *
1112     * <p>This corresponds to a pre-shift operation in a fixed
1113     * precision floating-point adder; this method is complicated by
1114     * variable precision of the result as determined by the
1115     * MathContext. A more nuanced operation could implement a
1116     * &quot;right shift&quot; on the smaller magnitude operand so
1117     * that the number of digits of the smaller operand could be
1118     * reduced even though the significands partially overlapped.
1119     */

1120    private BigDecimal JavaDoc[] preAlign(BigDecimal JavaDoc lhs, BigDecimal JavaDoc augend,
1121                  long padding, MathContext JavaDoc mc) {
1122    assert padding != 0;
1123    BigDecimal JavaDoc big;
1124    BigDecimal JavaDoc small;
1125    
1126    if (padding < 0) { // lhs is big; augend is small
1127
big = lhs;
1128        small = augend;
1129    } else { // lhs is small; augend is big
1130
big = augend;
1131        small = lhs;
1132    }
1133
1134    /*
1135     * This is the estimated scale of an ulp of the result; it
1136     * assumes that the result doesn't have a carry-out on a true
1137     * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1138     * on borrowing (e.g. 100 - 1.2 => 98.8)
1139     */

1140    long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
1141
1142    /*
1143     * The low-order digit position of big is big.scale(). This
1144     * is true regardless of whether big has a positive or
1145     * negative scale. The high-order digit position of small is
1146     * small.scale - (small.precision() - 1). To do the full
1147     * condensation, the digit positions of big and small must be
1148     * disjoint *and* the digit positions of small should not be
1149     * directly visible in the result.
1150     */

1151    long smallHighDigitPos = (long)small.scale - small.precision() + 1;
1152    if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1153
smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1154
small = BigDecimal.valueOf(small.signum(),
1155                       this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1156    }
1157    
1158    // Since addition is symmetric, preserving input order in
1159
// returned operands doesn't matter
1160
BigDecimal JavaDoc[] result = {big, small};
1161    return result;
1162    }
1163
1164    /**
1165     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this -
1166     * subtrahend)</tt>, and whose scale is <tt>max(this.scale(),
1167     * subtrahend.scale())</tt>.
1168     *
1169     * @param subtrahend value to be subtracted from this <tt>BigDecimal</tt>.
1170     * @return <tt>this - subtrahend</tt>
1171     */

1172    public BigDecimal JavaDoc subtract(BigDecimal JavaDoc subtrahend) {
1173        BigDecimal JavaDoc arg[] = {this, subtrahend};
1174        matchScale(arg);
1175
1176    long x = arg[0].intCompact;
1177    long y = arg[1].intCompact;
1178
1179    // Might be able to do a more clever check incorporating the
1180
// inflated check into the overflow computation.
1181
if (x != INFLATED && y != INFLATED) {
1182        long difference = x - y;
1183        /*
1184         * If the difference is not an overflowed value, continue
1185         * to use the compact representation. if either of x or y
1186         * is INFLATED, the difference should also be regarded as
1187         * an overflow. See "Hacker's Delight" section 2-12 for
1188         * explanation of the overflow test.
1189         */

1190        if ( ((x ^ y) & (difference ^ x) ) >> 63 == 0L ) // not overflowed
1191
return BigDecimal.valueOf(difference, arg[0].scale);
1192    }
1193        return new BigDecimal JavaDoc(arg[0].inflate().intVal.subtract(arg[1].inflate().intVal),
1194                              arg[0].scale);
1195    }
1196
1197    /**
1198     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this - subtrahend)</tt>,
1199     * with rounding according to the context settings.
1200     *
1201     * If <tt>subtrahend</tt> is zero then this, rounded if necessary, is used as the
1202     * result. If this is zero then the result is <tt>subtrahend.negate(mc)</tt>.
1203     *
1204     * @param subtrahend value to be subtracted from this <tt>BigDecimal</tt>.
1205     * @param mc the context to use.
1206     * @return <tt>this - subtrahend</tt>, rounded as necessary.
1207     * @throws ArithmeticException if the result is inexact but the
1208     * rounding mode is <tt>UNNECESSARY</tt>.
1209     * @since 1.5
1210     */

1211    public BigDecimal JavaDoc subtract(BigDecimal JavaDoc subtrahend, MathContext JavaDoc mc) {
1212        if (mc.precision == 0)
1213            return subtract(subtrahend);
1214        // share the special rounding code in add()
1215
this.inflate();
1216    subtrahend.inflate();
1217        BigDecimal JavaDoc rhs = new BigDecimal JavaDoc(subtrahend.intVal.negate(), subtrahend.scale);
1218        rhs.precision = subtrahend.precision;
1219        return add(rhs, mc);
1220    }
1221
1222    /**
1223     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this &times;
1224     * multiplicand)</tt>, and whose scale is <tt>(this.scale() +
1225     * multiplicand.scale())</tt>.
1226     *
1227     * @param multiplicand value to be multiplied by this <tt>BigDecimal</tt>.
1228     * @return <tt>this * multiplicand</tt>
1229     */

1230    public BigDecimal JavaDoc multiply(BigDecimal JavaDoc multiplicand) {
1231    long x = this.intCompact;
1232    long y = multiplicand.intCompact;
1233    int productScale = checkScale((long)scale+multiplicand.scale);
1234
1235    // Might be able to do a more clever check incorporating the
1236
// inflated check into the overflow computation.
1237
if (x != INFLATED && y != INFLATED) {
1238        /*
1239         * If the product is not an overflowed value, continue
1240         * to use the compact representation. if either of x or y
1241         * is INFLATED, the product should also be regarded as
1242         * an overflow. See "Hacker's Delight" section 2-12 for
1243         * explanation of the overflow test.
1244         */

1245        long product = x * y;
1246        if ( !(y != 0L && product/y != x) ) // not overflowed
1247
return BigDecimal.valueOf(product, productScale);
1248    }
1249
1250        BigDecimal JavaDoc result = new BigDecimal JavaDoc(this.inflate().intVal.multiply(multiplicand.inflate().intVal), productScale);
1251        return result;
1252    }
1253
1254    /**
1255     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this &times;
1256     * multiplicand)</tt>, with rounding according to the context settings.
1257     *
1258     * @param multiplicand value to be multiplied by this <tt>BigDecimal</tt>.
1259     * @param mc the context to use.
1260     * @return <tt>this * multiplicand</tt>, rounded as necessary.
1261     * @throws ArithmeticException if the result is inexact but the
1262     * rounding mode is <tt>UNNECESSARY</tt>.
1263     * @since 1.5
1264     */

1265    public BigDecimal JavaDoc multiply(BigDecimal JavaDoc multiplicand, MathContext JavaDoc mc) {
1266        if (mc.precision == 0)
1267            return multiply(multiplicand);
1268        BigDecimal JavaDoc lhs = this;
1269        return lhs.inflate().multiply(multiplicand.inflate()).doRound(mc);
1270    }
1271
1272    /**
1273     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1274     * divisor)</tt>, and whose scale is as specified. If rounding must
1275     * be performed to generate a result with the specified scale, the
1276     * specified rounding mode is applied.
1277     *
1278     * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1279     * should be used in preference to this legacy method.
1280     *
1281     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1282     * @param scale scale of the <tt>BigDecimal</tt> quotient to be returned.
1283     * @param roundingMode rounding mode to apply.
1284     * @return <tt>this / divisor</tt>
1285     * @throws ArithmeticException if <tt>divisor</tt> is zero,
1286     * <tt>roundingMode==ROUND_UNNECESSARY</tt> and
1287     * the specified scale is insufficient to represent the result
1288     * of the division exactly.
1289     * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
1290     * represent a valid rounding mode.
1291     * @see #ROUND_UP
1292     * @see #ROUND_DOWN
1293     * @see #ROUND_CEILING
1294     * @see #ROUND_FLOOR
1295     * @see #ROUND_HALF_UP
1296     * @see #ROUND_HALF_DOWN
1297     * @see #ROUND_HALF_EVEN
1298     * @see #ROUND_UNNECESSARY
1299     */

1300    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor, int scale, int roundingMode) {
1301    /*
1302     * IMPLEMENTATION NOTE: This method *must* return a new object
1303     * since dropDigits uses divide to generate a value whose
1304     * scale is then modified.
1305     */

1306        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1307            throw new IllegalArgumentException JavaDoc("Invalid rounding mode");
1308        /*
1309         * Rescale dividend or divisor (whichever can be "upscaled" to
1310         * produce correctly scaled quotient).
1311         * Take care to detect out-of-range scales
1312         */

1313        BigDecimal JavaDoc dividend;
1314        if (checkScale((long)scale + divisor.scale) >= this.scale) {
1315            dividend = this.setScale(scale + divisor.scale);
1316        } else {
1317            dividend = this;
1318            divisor = divisor.setScale(checkScale((long)this.scale - scale));
1319        }
1320    
1321    boolean compact = dividend.intCompact != INFLATED && divisor.intCompact != INFLATED;
1322    long div = INFLATED;
1323    long rem = INFLATED;;
1324    BigInteger JavaDoc q=null, r=null;
1325
1326    if (compact) {
1327        div = dividend.intCompact / divisor.intCompact;
1328        rem = dividend.intCompact % divisor.intCompact;
1329    } else {
1330        // Do the division and return result if it's exact.
1331
BigInteger JavaDoc i[] = dividend.inflate().intVal.divideAndRemainder(divisor.inflate().intVal);
1332        q = i[0];
1333        r = i[1];
1334    }
1335
1336    // Check for exact result
1337
if (compact) {
1338        if (rem == 0)
1339        return new BigDecimal JavaDoc(div, scale);
1340    } else {
1341        if (r.signum() == 0)
1342        return new BigDecimal JavaDoc(q, scale);
1343    }
1344    
1345        if (roundingMode == ROUND_UNNECESSARY) // Rounding prohibited
1346
throw new ArithmeticException JavaDoc("Rounding necessary");
1347
1348        /* Round as appropriate */
1349        int signum = dividend.signum() * divisor.signum(); // Sign of result
1350
boolean increment;
1351        if (roundingMode == ROUND_UP) { // Away from zero
1352
increment = true;
1353        } else if (roundingMode == ROUND_DOWN) { // Towards zero
1354
increment = false;
1355        } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1356
increment = (signum > 0);
1357        } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
1358
increment = (signum < 0);
1359        } else { // Remaining modes based on nearest-neighbor determination
1360
int cmpFracHalf;
1361        if (compact) {
1362         cmpFracHalf = longCompareTo(Math.abs(2*rem), Math.abs(divisor.intCompact));
1363        } else {
1364        // add(r) here is faster than multiply(2) or shiftLeft(1)
1365
cmpFracHalf= r.add(r).abs().compareTo(divisor.intVal.abs());
1366        }
1367            if (cmpFracHalf < 0) { // We're closer to higher digit
1368
increment = false;
1369            } else if (cmpFracHalf > 0) { // We're closer to lower digit
1370
increment = true;
1371            } else { // We're dead-center
1372
if (roundingMode == ROUND_HALF_UP)
1373                    increment = true;
1374                else if (roundingMode == ROUND_HALF_DOWN)
1375                    increment = false;
1376                else { // roundingMode == ROUND_HALF_EVEN
1377
if (compact)
1378            increment = (div & 1L) != 0L;
1379            else
1380            increment = q.testBit(0); // true iff q is odd
1381
}
1382            }
1383    }
1384
1385    if (compact) {
1386        if (increment)
1387        div += signum; // guaranteed not to overflow
1388
return new BigDecimal JavaDoc(div, scale);
1389    } else {
1390        return (increment
1391            ? new BigDecimal JavaDoc(q.add(BigInteger.valueOf(signum)), scale)
1392            : new BigDecimal JavaDoc(q, scale));
1393    }
1394    }
1395
1396    /**
1397     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1398     * divisor)</tt>, and whose scale is as specified. If rounding must
1399     * be performed to generate a result with the specified scale, the
1400     * specified rounding mode is applied.
1401     *
1402     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1403     * @param scale scale of the <tt>BigDecimal</tt> quotient to be returned.
1404     * @param roundingMode rounding mode to apply.
1405     * @return <tt>this / divisor</tt>
1406     * @throws ArithmeticException if <tt>divisor</tt> is zero,
1407     * <tt>roundingMode==RoundingMode.UNNECESSARY</tt> and
1408     * the specified scale is insufficient to represent the result
1409     * of the division exactly.
1410     * @since 1.5
1411     */

1412    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor, int scale, RoundingMode JavaDoc roundingMode) {
1413    return divide(divisor, scale, roundingMode.oldMode);
1414    }
1415
1416    /**
1417     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1418     * divisor)</tt>, and whose scale is <tt>this.scale()</tt>. If
1419     * rounding must be performed to generate a result with the given
1420     * scale, the specified rounding mode is applied.
1421     *
1422     * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1423     * should be used in preference to this legacy method.
1424     *
1425     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1426     * @param roundingMode rounding mode to apply.
1427     * @return <tt>this / divisor</tt>
1428     * @throws ArithmeticException if <tt>divisor==0</tt>, or
1429     * <tt>roundingMode==ROUND_UNNECESSARY</tt> and
1430     * <tt>this.scale()</tt> is insufficient to represent the result
1431     * of the division exactly.
1432     * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
1433     * represent a valid rounding mode.
1434     * @see #ROUND_UP
1435     * @see #ROUND_DOWN
1436     * @see #ROUND_CEILING
1437     * @see #ROUND_FLOOR
1438     * @see #ROUND_HALF_UP
1439     * @see #ROUND_HALF_DOWN
1440     * @see #ROUND_HALF_EVEN
1441     * @see #ROUND_UNNECESSARY
1442     */

1443    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor, int roundingMode) {
1444            return this.divide(divisor, scale, roundingMode);
1445    }
1446
1447    /**
1448     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1449     * divisor)</tt>, and whose scale is <tt>this.scale()</tt>. If
1450     * rounding must be performed to generate a result with the given
1451     * scale, the specified rounding mode is applied.
1452     *
1453     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1454     * @param roundingMode rounding mode to apply.
1455     * @return <tt>this / divisor</tt>
1456     * @throws ArithmeticException if <tt>divisor==0</tt>, or
1457     * <tt>roundingMode==RoundingMode.UNNECESSARY</tt> and
1458     * <tt>this.scale()</tt> is insufficient to represent the result
1459     * of the division exactly.
1460     */

1461    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor, RoundingMode JavaDoc roundingMode) {
1462    return this.divide(divisor, scale, roundingMode.oldMode);
1463    }
1464
1465    /**
1466     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1467     * divisor)</tt>, and whose preferred scale is <tt>(this.scale() -
1468     * divisor.scale())</tt>; if the exact quotient cannot be
1469     * represented (because it has a non-terminating decimal
1470     * expansion) an <tt>ArithmeticException</tt> is thrown.
1471     *
1472     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1473     * @throws ArithmeticException if the exact quotient does not have a
1474     * terminating decimal expansion
1475     * @return <tt>this / divisor</tt>
1476     * @since 1.5
1477     * @author Joseph D. Darcy
1478     */

1479    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor) {
1480    /*
1481     * Handle zero cases first.
1482     */

1483        if (divisor.signum() == 0) { // x/0
1484
if (this.signum() == 0) // 0/0
1485
throw new ArithmeticException JavaDoc("Division undefined"); // NaN
1486
throw new ArithmeticException JavaDoc("Division by zero");
1487    }
1488
1489    // Calculate preferred scale
1490
int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
1491                            Integer.MAX_VALUE), Integer.MIN_VALUE);
1492        if (this.signum() == 0) // 0/y
1493
return new BigDecimal JavaDoc(0, preferredScale);
1494    else {
1495        this.inflate();
1496        divisor.inflate();
1497        /*
1498         * If the quotient this/divisor has a terminating decimal
1499         * expansion, the expansion can have no more than
1500         * (a.precision() + ceil(10*b.precision)/3) digits.
1501         * Therefore, create a MathContext object with this
1502         * precision and do a divide with the UNNECESSARY rounding
1503         * mode.
1504         */

1505        MathContext JavaDoc mc = new MathContext JavaDoc( (int)Math.min(this.precision() +
1506                                (long)Math.ceil(10.0*divisor.precision()/3.0),
1507                                Integer.MAX_VALUE),
1508                          RoundingMode.UNNECESSARY);
1509        BigDecimal JavaDoc quotient;
1510        try {
1511        quotient = this.divide(divisor, mc);
1512        } catch (ArithmeticException JavaDoc e) {
1513        throw new ArithmeticException JavaDoc("Non-terminating decimal expansion; " +
1514                          "no exact representable decimal result.");
1515        }
1516
1517        int quotientScale = quotient.scale();
1518
1519        // divide(BigDecimal, mc) tries to adjust the quotient to
1520
// the desired one by removing trailing zeros; since the
1521
// exact divide method does not have an explicit digit
1522
// limit, we can add zeros too.
1523

1524        if (preferredScale > quotientScale)
1525        return quotient.setScale(preferredScale);
1526
1527        return quotient;
1528    }
1529    }
1530
1531    /**
1532     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this /
1533     * divisor)</tt>, with rounding according to the context settings.
1534     *
1535     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1536     * @param mc the context to use.
1537     * @return <tt>this / divisor</tt>, rounded as necessary.
1538     * @throws ArithmeticException if the result is inexact but the
1539     * rounding mode is <tt>UNNECESSARY</tt> or
1540     * <tt>mc.precision == 0</tt> and the quotient has a
1541     * non-terminating decimal expansion.
1542     * @since 1.5
1543     */

1544    public BigDecimal JavaDoc divide(BigDecimal JavaDoc divisor, MathContext JavaDoc mc) {
1545        if (mc.precision == 0)
1546            return divide(divisor);
1547        BigDecimal JavaDoc lhs = this.inflate(); // left-hand-side
1548
BigDecimal JavaDoc rhs = divisor.inflate(); // right-hand-side
1549
BigDecimal JavaDoc result; // work
1550

1551    long preferredScale = (long)lhs.scale() - rhs.scale();
1552
1553        // Now calculate the answer. We use the existing
1554
// divide-and-round method, but as this rounds to scale we have
1555
// to normalize the values here to achieve the desired result.
1556
// For x/y we first handle y=0 and x=0, and then normalize x and
1557
// y to give x' and y' with the following constraints:
1558
// (a) 0.1 <= x' < 1
1559
// (b) x' <= y' < 10*x'
1560
// Dividing x'/y' with the required scale set to mc.precision then
1561
// will give a result in the range 0.1 to 1 rounded to exactly
1562
// the right number of digits (except in the case of a result of
1563
// 1.000... which can arise when x=y, or when rounding overflows
1564
// The 1.000... case will reduce properly to 1.
1565
if (rhs.signum() == 0) { // x/0
1566
if (lhs.signum() == 0) // 0/0
1567
throw new ArithmeticException JavaDoc("Division undefined"); // NaN
1568
throw new ArithmeticException JavaDoc("Division by zero");
1569    }
1570        if (lhs.signum() == 0) // 0/y
1571
return new BigDecimal JavaDoc(BigInteger.ZERO,
1572                  (int)Math.max(Math.min(preferredScale,
1573                             Integer.MAX_VALUE),
1574                        Integer.MIN_VALUE));
1575
1576        BigDecimal JavaDoc xprime = new BigDecimal JavaDoc(lhs.intVal.abs(), lhs.precision());
1577        BigDecimal JavaDoc yprime = new BigDecimal JavaDoc(rhs.intVal.abs(), rhs.precision());
1578        // xprime and yprime are now both in range 0.1 through 0.999...
1579
if (mc.roundingMode == RoundingMode.CEILING ||
1580        mc.roundingMode == RoundingMode.FLOOR) {
1581        // The floor (round toward negative infinity) and ceil
1582
// (round toward positive infinity) rounding modes are not
1583
// invariant under a sign flip. If xprime/yprime has a
1584
// different sign than lhs/rhs, the rounding mode must be
1585
// changed.
1586
if ((xprime.signum() != lhs.signum()) ^
1587        (yprime.signum() != rhs.signum())) {
1588        mc = new MathContext JavaDoc(mc.precision,
1589                     (mc.roundingMode==RoundingMode.CEILING)?
1590                     RoundingMode.FLOOR:RoundingMode.CEILING);
1591        }
1592    }
1593
1594        if (xprime.compareTo(yprime) > 0) // satisfy constraint (b)
1595
yprime.scale -= 1; // [that is, yprime *= 10]
1596
result = xprime.divide(yprime, mc.precision, mc.roundingMode.oldMode);
1597        // correct the scale of the result...
1598
result.scale = checkScale((long)yprime.scale - xprime.scale
1599            - (rhs.scale - lhs.scale) + mc.precision);
1600        // apply the sign
1601
if (lhs.signum() != rhs.signum())
1602            result = result.negate();
1603        // doRound, here, only affects 1000000000 case.
1604
result = result.doRound(mc);
1605        
1606    if (result.multiply(divisor).compareTo(this) == 0) {
1607        // Apply preferred scale rules for exact quotients
1608
return result.stripZerosToMatchScale(preferredScale);
1609    }
1610    else {
1611        return result;
1612    }
1613    }
1614
1615    /**
1616     * Returns a <tt>BigDecimal</tt> whose value is the integer part
1617     * of the quotient <tt>(this / divisor)</tt> rounded down. The
1618     * preferred scale of the result is <code>(this.scale() -
1619     * divisor.scale())</code>.
1620     *
1621     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1622     * @return The integer part of <tt>this / divisor</tt>.
1623     * @throws ArithmeticException if <tt>divisor==0</tt>
1624     * @since 1.5
1625     */

1626    public BigDecimal JavaDoc divideToIntegralValue(BigDecimal JavaDoc divisor) {
1627    // Calculate preferred scale
1628
int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
1629                            Integer.MAX_VALUE), Integer.MIN_VALUE);
1630    this.inflate();
1631    divisor.inflate();
1632        if (this.abs().compareTo(divisor.abs()) < 0) {
1633        // much faster when this << divisor
1634
return BigDecimal.valueOf(0, preferredScale);
1635        }
1636
1637    if(this.signum() == 0 && divisor.signum() != 0)
1638        return this.setScale(preferredScale);
1639
1640    // Perform a divide with enough digits to round to a correct
1641
// integer value; then remove any fractional digits
1642

1643    int maxDigits = (int)Math.min(this.precision() +
1644                      (long)Math.ceil(10.0*divisor.precision()/3.0) +
1645                      Math.abs((long)this.scale() - divisor.scale()) + 2,
1646                      Integer.MAX_VALUE);
1647
1648        BigDecimal JavaDoc quotient = this.divide(divisor, new MathContext JavaDoc(maxDigits,
1649                                   RoundingMode.DOWN));
1650    if (quotient.scale > 0) {
1651        quotient = quotient.setScale(0, RoundingMode.DOWN).
1652        stripZerosToMatchScale(preferredScale);
1653    }
1654    
1655    if (quotient.scale < preferredScale) {
1656        // pad with zeros if necessary
1657
quotient = quotient.setScale(preferredScale);
1658    }
1659
1660    return quotient;
1661    }
1662
1663    /**
1664     * Returns a <tt>BigDecimal</tt> whose value is the integer part
1665     * of <tt>(this / divisor)</tt>. Since the integer part of the
1666     * exact quotient does not depend on the rounding mode, the
1667     * rounding mode does not affect the values returned by this
1668     * method. The preferred scale of the result is
1669     * <code>(this.scale() - divisor.scale())</code>. An
1670     * <tt>ArithmeticException</tt> is thrown if the integer part of
1671     * the exact quotient needs more than <tt>mc.precision</tt>
1672     * digits.
1673     *
1674     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1675     * @param mc the context to use.
1676     * @return The integer part of <tt>this / divisor</tt>.
1677     * @throws ArithmeticException if <tt>divisor==0</tt>
1678     * @throws ArithmeticException if <tt>mc.precision</tt> &gt; 0 and the result
1679     * requires a precision of more than <tt>mc.precision</tt> digits.
1680     * @since 1.5
1681     * @author Joseph D. Darcy
1682     */

1683    public BigDecimal JavaDoc divideToIntegralValue(BigDecimal JavaDoc divisor, MathContext JavaDoc mc) {
1684        if (mc.precision == 0 || // exact result
1685
(this.abs().compareTo(divisor.abs()) < 0) ) // zero result
1686
return divideToIntegralValue(divisor);
1687    
1688    // Calculate preferred scale
1689
int preferredScale = (int)Math.max(Math.min((long)this.scale() - divisor.scale(),
1690                            Integer.MAX_VALUE), Integer.MIN_VALUE);
1691    
1692    /*
1693     * Perform a normal divide to mc.precision digits. If the
1694     * remainder has absolute value less than the divisor, the
1695     * integer portion of the quotient fits into mc.precision
1696     * digits. Next, remove any fractional digits from the
1697     * quotient and adjust the scale to the preferred value.
1698     */

1699    BigDecimal JavaDoc result = this.divide(divisor, new MathContext JavaDoc(mc.precision,
1700                                 RoundingMode.DOWN));
1701    int resultScale = result.scale();
1702    
1703    if (result.scale() < 0) {
1704        /*
1705         * Result is an integer. See if quotient represents the
1706         * full integer portion of the exact quotient; if it does,
1707         * the computed remainder will be less than the divisor.
1708         */

1709        BigDecimal JavaDoc product = result.multiply(divisor);
1710        // If the quotient is the full integer value,
1711
// |dividend-product| < |divisor|.
1712
if (this.subtract(product).abs().compareTo(divisor.abs()) >= 0) {
1713        throw new ArithmeticException JavaDoc("Division impossible");
1714        }
1715    } else if (result.scale() > 0) {
1716        /*
1717         * Integer portion of quotient will fit into precision
1718         * digits; recompute quotient to scale 0 to avoid double
1719         * rounding and then try to adjust, if necessary.
1720         */

1721        result = result.setScale(0, RoundingMode.DOWN);
1722    }
1723    // else result.scale() == 0;
1724

1725    int precisionDiff;
1726    if ((preferredScale > result.scale()) &&
1727        (precisionDiff = mc.precision - result.precision()) > 0 ) {
1728        return result.setScale(result.scale() +
1729                   Math.min(precisionDiff, preferredScale - result.scale) );
1730    } else
1731        return result.stripZerosToMatchScale(preferredScale);
1732    }
1733
1734    /**
1735     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this % divisor)</tt>.
1736     *
1737     * <p>The remainder is given by
1738     * <tt>this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))</tt>.
1739     * Note that this is not the modulo operation (the result can be
1740     * negative).
1741     *
1742     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1743     * @return <tt>this % divisor</tt>.
1744     * @throws ArithmeticException if <tt>divisor==0</tt>
1745     * @since 1.5
1746     */

1747    public BigDecimal JavaDoc remainder(BigDecimal JavaDoc divisor) {
1748        BigDecimal JavaDoc divrem[] = this.divideAndRemainder(divisor);
1749        return divrem[1];
1750    }
1751
1752
1753    /**
1754     * Returns a <tt>BigDecimal</tt> whose value is <tt>(this %
1755     * divisor)</tt>, with rounding according to the context settings.
1756     * The <tt>MathContext</tt> settings affect the implicit divide
1757     * used to compute the remainder. The remainder computation
1758     * itself is by definition exact. Therefore, the remainder may
1759     * contain more than <tt>mc.getPrecision()</tt> digits.
1760     *
1761     * <p>The remainder is given by
1762     * <tt>this.subtract(this.divideToIntegralValue(divisor,
1763     * mc).multiply(divisor))</tt>. Note that this is not the modulo
1764     * operation (the result can be negative).
1765     *
1766     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided.
1767     * @param mc the context to use.
1768     * @return <tt>this % divisor</tt>, rounded as necessary.
1769     * @throws ArithmeticException if <tt>divisor==0</tt>
1770     * @throws ArithmeticException if the result is inexact but the
1771     * rounding mode is <tt>UNNECESSARY</tt>, or <tt>mc.precision</tt>
1772     * &gt; 0 and the result of <tt>this.divideToIntgralValue(divisor)</tt> would
1773     * require a precision of more than <tt>mc.precision</tt> digits.
1774     * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1775     * @since 1.5
1776     */

1777    public BigDecimal JavaDoc remainder(BigDecimal JavaDoc divisor, MathContext JavaDoc mc) {
1778        BigDecimal JavaDoc divrem[] = this.divideAndRemainder(divisor, mc);
1779        return divrem[1];
1780    }
1781
1782    /**
1783     * Returns a two-element <tt>BigDecimal</tt> array containing the
1784     * result of <tt>divideToIntegralValue</tt> followed by the result of
1785     * <tt>remainder</tt> on the two operands.
1786     *
1787     * <p>Note that if both the integer quotient and remainder are
1788     * needed, this method is faster than using the
1789     * <tt>divideToIntegralValue</tt> and <tt>remainder</tt> methods
1790     * separately because the division need only be carried out once.
1791     *
1792     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided,
1793     * and the remainder computed.
1794     * @return a two element <tt>BigDecimal</tt> array: the quotient
1795     * (the result of <tt>divideToIntegralValue</tt>) is the initial element
1796     * and the remainder is the final element.
1797     * @throws ArithmeticException if <tt>divisor==0</tt>
1798     * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1799     * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1800     * @since 1.5
1801     */

1802    public BigDecimal JavaDoc[] divideAndRemainder(BigDecimal JavaDoc divisor) {
1803        // we use the identity x = i * y + r to determine r
1804
BigDecimal JavaDoc[] result = new BigDecimal JavaDoc[2];
1805
1806        result[0] = this.divideToIntegralValue(divisor);
1807    result[1] = this.subtract(result[0].multiply(divisor));
1808        return result;
1809    }
1810
1811    /**
1812     * Returns a two-element <tt>BigDecimal</tt> array containing the
1813     * result of <tt>divideToIntegralValue</tt> followed by the result of
1814     * <tt>remainder</tt> on the two operands calculated with rounding
1815     * according to the context settings.
1816     *
1817     * <p>Note that if both the integer quotient and remainder are
1818     * needed, this method is faster than using the
1819     * <tt>divideToIntegralValue</tt> and <tt>remainder</tt> methods
1820     * separately because the division need only be carried out once.
1821     *
1822     * @param divisor value by which this <tt>BigDecimal</tt> is to be divided,
1823     * and the remainder computed.
1824     * @param mc the context to use.
1825     * @return a two element <tt>BigDecimal</tt> array: the quotient
1826     * (the result of <tt>divideToIntegralValue</tt>) is the
1827     * initial element and the remainder is the final element.
1828     * @throws ArithmeticException if <tt>divisor==0</tt>
1829     * @throws ArithmeticException if the result is inexact but the
1830     * rounding mode is <tt>UNNECESSARY</tt>, or <tt>mc.precision</tt>
1831     * &gt; 0 and the result of <tt>this.divideToIntgralValue(divisor)</tt> would
1832     * require a precision of more than <tt>mc.precision</tt> digits.
1833     * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1834     * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1835     * @since 1.5
1836     */

1837    public BigDecimal JavaDoc[] divideAndRemainder(BigDecimal JavaDoc divisor, MathContext JavaDoc mc) {
1838        if (mc.precision == 0)
1839            return divideAndRemainder(divisor);
1840
1841        BigDecimal JavaDoc[] result = new BigDecimal JavaDoc[2];
1842        BigDecimal JavaDoc lhs = this;
1843
1844        result[0] = lhs.divideToIntegralValue(divisor, mc);
1845    result[1] = lhs.subtract(result[0].multiply(divisor));
1846        return result;
1847    }
1848
1849    /**
1850     * Returns a <tt>BigDecimal</tt> whose value is
1851     * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
1852     * unlimited precision.
1853     *
1854     * <p>The parameter <tt>n</tt> must be in the range 0 through
1855     * 999999999, inclusive. <tt>ZERO.pow(0)</tt> returns {@link
1856     * #ONE}.
1857     *
1858     * Note that future releases may expand the allowable exponent
1859     * range of this method.
1860     *
1861     * @param n power to raise this <tt>BigDecimal</tt> to.
1862     * @return <tt>this<sup>n</sup></tt>
1863     * @throws ArithmeticException if <tt>n</tt> is out of range.
1864     * @since 1.5
1865     */

1866    public BigDecimal JavaDoc pow(int n) {
1867        if (n < 0 || n > 999999999)
1868            throw new ArithmeticException JavaDoc("Invalid operation");
1869    // No need to calculate pow(n) if result will over/underflow.
1870
// Don't attempt to support "supernormal" numbers.
1871
int newScale = checkScale((long)scale * n);
1872    this.inflate();
1873        return new BigDecimal JavaDoc(intVal.pow(n), newScale);
1874    }
1875
1876
1877    /**
1878     * Returns a <tt>BigDecimal</tt> whose value is
1879     * <tt>(this<sup>n</sup>)</tt>. The current implementation uses
1880     * the core algorithm defined in ANSI standard X3.274-1996 with
1881     * rounding according to the context settings. In general, the
1882     * returned numerical value is within two ulps of the exact
1883     * numerical value for the chosen precision. Note that future
1884     * releases may use a different algorithm with a decreased
1885     * allowable error bound and increased allowable exponent range.
1886     *
1887     * <p>The X3.274-1996 algorithm is:
1888     *
1889     * <ul>
1890     * <li> An <tt>ArithmeticException</tt> exception is thrown if
1891     * <ul>
1892     * <li><tt>abs(n) &gt; 999999999</tt>
1893     * <li><tt>mc.precision == 0</tt> and <tt>n &lt; 0</tt>
1894     * <li><tt>mc.precision &gt; 0</tt> and <tt>n</tt> has more than
1895     * <tt>mc.precision</tt> decimal digits
1896     * </ul>
1897     *
1898     * <li> if <tt>n</tt> is zero, {@link #ONE} is returned even if
1899     * <tt>this</tt> is zero, otherwise
1900     * <ul>
1901     * <li> if <tt>n</tt> is positive, the result is calculated via
1902     * the repeated squaring technique into a single accumulator.
1903     * The individual multiplications with the accumulator use the
1904     * same math context settings as in <tt>mc</tt> except for a
1905     * precision increased to <tt>mc.precision + elength + 1</tt>
1906     * where <tt>elength</tt> is the number of decimal digits in
1907     * <tt>n</tt>.
1908     *
1909     * <li> if <tt>n</tt> is negative, the result is calculated as if
1910     * <tt>n</tt> were positive; this value is then divided into one
1911     * using the working precision specified above.
1912     *
1913     * <li> The final value from either the positive or negative case
1914     * is then rounded to the destination precision.
1915     * </ul>
1916     * </ul>
1917     *
1918     * @param n power to raise this <tt>BigDecimal</tt> to.
1919     * @param mc the context to use.
1920     * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
1921     * algorithm
1922     * @throws ArithmeticException if the result is inexact but the
1923     * rounding mode is <tt>UNNECESSARY</tt>, or <tt>n</tt> is out
1924     * of range.
1925     * @since 1.5
1926     */

1927    public BigDecimal JavaDoc pow(int n, MathContext JavaDoc mc) {
1928        if (mc.precision == 0)
1929            return pow(n);
1930        if (n < -999999999 || n > 999999999)
1931            throw new ArithmeticException JavaDoc("Invalid operation");
1932        if (n == 0)
1933            return ONE; // x**0 == 1 in X3.274
1934
this.inflate();
1935        BigDecimal JavaDoc lhs = this;
1936        MathContext JavaDoc workmc = mc; // working settings
1937
int mag = Math.abs(n); // magnitude of n
1938
if (mc.precision > 0) {
1939
1940            int elength = intLength(mag); // length of n in digits
1941
if (elength > mc.precision) // X3.274 rule
1942
throw new ArithmeticException JavaDoc("Invalid operation");
1943            workmc = new MathContext JavaDoc(mc.precision + elength + 1,
1944                      mc.roundingMode);
1945        }
1946        // ready to carry out power calculation...
1947
BigDecimal JavaDoc acc = ONE; // accumulator
1948
boolean seenbit = false; // set once we've seen a 1-bit
1949
for (int i=1;;i++) { // for each bit [top bit ignored]
1950
mag += mag; // shift left 1 bit
1951
if (mag < 0) { // top bit is set
1952
seenbit = true; // OK, we're off
1953
acc = acc.multiply(lhs, workmc); // acc=acc*x
1954
}
1955            if (i == 31)
1956                break; // that was the last bit
1957
if (seenbit)
1958                acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
1959
// else (!seenbit) no point in squaring ONE
1960
}
1961        // if negative n, calculate the reciprocal using working precision
1962
if (n<0) // [hence mc.precision>0]
1963
acc=ONE.divide(acc, workmc);
1964        // round to final precision and strip zeros
1965
return acc.doRound(mc);
1966    }
1967
1968    /**
1969     * Returns a <tt>BigDecimal</tt> whose value is the absolute value
1970     * of this <tt>BigDecimal</tt>, and whose scale is
1971     * <tt>this.scale()</tt>.
1972     *
1973     * @return <tt>abs(this)</tt>
1974     */

1975    public BigDecimal JavaDoc abs() {
1976        return (signum() < 0 ? negate() : this);
1977    }
1978
1979    /**
1980     * Returns a <tt>BigDecimal</tt> whose value is the absolute value
1981     * of this <tt>BigDecimal</tt>, with rounding according to the
1982     * context settings.
1983     *
1984     * @param mc the context to use.
1985     * @return <tt>abs(this)</tt>, rounded as necessary.
1986     * @throws ArithmeticException if the result is inexact but the
1987     * rounding mode is <tt>UNNECESSARY</tt>.
1988     */

1989    public BigDecimal JavaDoc abs(MathContext JavaDoc mc) {
1990        return (signum() < 0 ? negate(mc) : plus(mc));
1991    }
1992
1993    /**
1994     * Returns a <tt>BigDecimal</tt> whose value is <tt>(-this)</tt>,
1995     * and whose scale is <tt>this.scale()</tt>.
1996     *
1997     * @return <tt>-this</tt>.
1998     */

1999    public BigDecimal JavaDoc negate() {
2000    BigDecimal JavaDoc result;
2001    if (intCompact != INFLATED)
2002        result = BigDecimal.valueOf(-intCompact, scale);
2003    else {
2004        result = new BigDecimal JavaDoc(intVal.negate(), scale);
2005        result.precision = precision;
2006    }
2007        return result;
2008    }
2009
2010    /**
2011     * Returns a <tt>BigDecimal</tt> whose value is <tt>(-this)</tt>,
2012     * with rounding according to the context settings.
2013     *
2014     * @param mc the context to use.
2015     * @return <tt>-this</tt>, rounded as necessary.
2016     * @throws ArithmeticException if or the result is inexact but the
2017     * rounding mode is <tt>UNNECESSARY</tt>.
2018     * @since 1.5
2019     */

2020    public BigDecimal JavaDoc negate(MathContext JavaDoc mc) {
2021        return negate().plus(mc);
2022    }
2023
2024    /**
2025     * Returns a <tt>BigDecimal</tt> whose value is <tt>(+this)</tt>, and whose
2026     * scale is <tt>this.scale()</tt>.
2027     *
2028     * <p>This method, which simply returns this <tt>BigDecimal</tt>
2029     * is included for symmetry with the unary minus method {@link
2030     * #negate()}.
2031     *
2032     * @return <tt>this</tt>.
2033     * @see #negate()
2034     * @since 1.5
2035     */

2036    public BigDecimal JavaDoc plus() {
2037        return this;
2038    }
2039
2040    /**
2041     * Returns a <tt>BigDecimal</tt> whose value is <tt>(+this)</tt>,
2042     * with rounding according to the context settings.
2043     *
2044     * <p>The effect of this method is identical to that of the {@link
2045     * #round(MathContext)} method.
2046     *
2047     * @param mc the context to use.
2048     * @return <tt>this</tt>, rounded as necessary. A zero result will
2049     * have a scale of 0.
2050     * @throws ArithmeticException if the result is inexact but the
2051     * rounding mode is <tt>UNNECESSARY</tt>.
2052     * @see #round(MathContext)
2053     * @since 1.5
2054     */

2055    public BigDecimal JavaDoc plus(MathContext JavaDoc mc) {
2056        if (mc.precision == 0) // no rounding please
2057
return this;
2058        return this.doRound(mc);
2059    }
2060
2061    /**
2062     * Returns the signum function of this <tt>BigDecimal</tt>.
2063     *
2064     * @return -1, 0, or 1 as the value of this <tt>BigDecimal</tt>
2065     * is negative, zero, or positive.
2066     */

2067    public int signum() {
2068    return (intCompact != INFLATED)?
2069        Long.signum(intCompact):
2070        intVal.signum();
2071    }
2072
2073    /**
2074     * Returns the <i>scale</i> of this <tt>BigDecimal</tt>. If zero
2075     * or positive, the scale is the number of digits to the right of
2076     * the decimal point. If negative, the unscaled value of the
2077     * number is multiplied by ten to the power of the negation of the
2078     * scale. For example, a scale of <tt>-3</tt> means the unscaled
2079     * value is multiplied by 1000.
2080     *
2081     * @return the scale of this <tt>BigDecimal</tt>.
2082     */

2083    public int scale() {
2084        return scale;
2085    }
2086
2087    /**
2088     * Returns the <i>precision</i> of this <tt>BigDecimal</tt>. (The
2089     * precision is the number of digits in the unscaled value.)
2090     *
2091     * <p>The precision of a zero value is 1.
2092     *
2093     * @return the precision of this <tt>BigDecimal</tt>.
2094     * @since 1.5
2095     */

2096    public int precision() {
2097        int result = precision;
2098        if (result == 0) {
2099            result = digitLength();
2100            precision = result;
2101        }
2102        return result;
2103    }
2104
2105
2106    /**
2107     * Returns a <tt>BigInteger</tt> whose value is the <i>unscaled
2108     * value</i> of this <tt>BigDecimal</tt>. (Computes <tt>(this *
2109     * 10<sup>this.scale()</sup>)</tt>.)
2110     *
2111     * @return the unscaled value of this <tt>BigDecimal</tt>.
2112     * @since 1.2
2113     */

2114    public BigInteger JavaDoc unscaledValue() {
2115        return this.inflate().intVal;
2116    }
2117
2118    // Rounding Modes
2119

2120    /**
2121     * Rounding mode to round away from zero. Always increments the
2122     * digit prior to a nonzero discarded fraction. Note that this rounding
2123     * mode never decreases the magnitude of the calculated value.
2124     */

2125    public final static int ROUND_UP = 0;
2126
2127    /**
2128     * Rounding mode to round towards zero. Never increments the digit
2129     * prior to a discarded fraction (i.e., truncates). Note that this
2130     * rounding mode never increases the magnitude of the calculated value.
2131     */

2132    public final static int ROUND_DOWN = 1;
2133
2134    /**
2135     * Rounding mode to round towards positive infinity. If the
2136     * <tt>BigDecimal</tt> is positive, behaves as for
2137     * <tt>ROUND_UP</tt>; if negative, behaves as for
2138     * <tt>ROUND_DOWN</tt>. Note that this rounding mode never
2139     * decreases the calculated value.
2140     */

2141    public final static int ROUND_CEILING = 2;
2142
2143    /**
2144     * Rounding mode to round towards negative infinity. If the
2145     * <tt>BigDecimal</tt> is positive, behave as for
2146     * <tt>ROUND_DOWN</tt>; if negative, behave as for
2147     * <tt>ROUND_UP</tt>. Note that this rounding mode never
2148     * increases the calculated value.
2149     */

2150    public final static int ROUND_FLOOR = 3;
2151
2152    /**
2153     * Rounding mode to round towards &quot;nearest neighbor&quot;
2154     * unless both neighbors are equidistant, in which case round up.
2155     * Behaves as for <tt>ROUND_UP</tt> if the discarded fraction is
2156     * &gt;= 0.5; otherwise, behaves as for <tt>ROUND_DOWN</tt>. Note
2157     * that this is the rounding mode that most of us were taught in
2158     * grade school.
2159     */

2160    public final static int ROUND_HALF_UP = 4;
2161
2162    /**
2163     * Rounding mode to round towards &quot;nearest neighbor&quot;
2164     * unless both neighbors are equidistant, in which case round
2165     * down. Behaves as for <tt>ROUND_UP</tt> if the discarded
2166     * fraction is &gt; 0.5; otherwise, behaves as for
2167     * <tt>ROUND_DOWN</tt>.
2168     */

2169    public final static int ROUND_HALF_DOWN = 5;
2170
2171    /**
2172     * Rounding mode to round towards the &quot;nearest neighbor&quot;
2173     * unless both neighbors are equidistant, in which case, round
2174     * towards the even neighbor. Behaves as for
2175     * <tt>ROUND_HALF_UP</tt> if the digit to the left of the
2176     * discarded fraction is odd; behaves as for
2177     * <tt>ROUND_HALF_DOWN</tt> if it's even. Note that this is the
2178     * rounding mode that minimizes cumulative error when applied
2179     * repeatedly over a sequence of calculations.
2180     */

2181    public final static int ROUND_HALF_EVEN = 6;
2182
2183    /**
2184     * Rounding mode to assert that the requested operation has an exact
2185     * result, hence no rounding is necessary. If this rounding mode is
2186     * specified on an operation that yields an inexact result, an
2187     * <tt>ArithmeticException</tt> is thrown.
2188     */

2189    public final static int ROUND_UNNECESSARY = 7;
2190
2191
2192    // Scaling/Rounding Operations
2193

2194    /**
2195     * Returns a <tt>BigDecimal</tt> rounded according to the
2196     * <tt>MathContext</tt> settings. If the precision setting is 0 then
2197     * no rounding takes place.
2198     *
2199     * <p>The effect of this method is identical to that of the
2200     * {@link #plus(MathContext)} method.
2201     *
2202     * @param mc the context to use.
2203     * @return a <tt>BigDecimal</tt> rounded according to the
2204     * <tt>MathContext</tt> settings.
2205     * @throws ArithmeticException if the rounding mode is
2206     * <tt>UNNECESSARY</tt> and the
2207     * <tt>BigDecimal</tt> operation would require rounding.
2208     * @see #plus(MathContext)
2209     * @since 1.5
2210     */

2211    public BigDecimal JavaDoc round(MathContext JavaDoc mc) {
2212        return plus(mc);
2213    }
2214
2215    /**
2216     * Returns a <tt>BigDecimal</tt> whose scale is the specified
2217     * value, and whose unscaled value is determined by multiplying or
2218     * dividing this <tt>BigDecimal</tt>'s unscaled value by the
2219     * appropriate power of ten to maintain its overall value. If the
2220     * scale is reduced by the operation, the unscaled value must be
2221     * divided (rather than multiplied), and the value may be changed;
2222     * in this case, the specified rounding mode is applied to the
2223     * division.
2224     *
2225     * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
2226     * @param roundingMode The rounding mode to apply.
2227     * @return a <tt>BigDecimal</tt> whose scale is the specified value,
2228     * and whose unscaled value is determined by multiplying or
2229     * dividing this <tt>BigDecimal</tt>'s unscaled value by the
2230     * appropriate power of ten to maintain its overall value.
2231     * @throws ArithmeticException if <tt>roundingMode==UNNECESSARY</tt>
2232     * and the specified scaling operation would require
2233     * rounding.
2234     * @see RoundingMode
2235     * @since 1.5
2236     */

2237    public BigDecimal JavaDoc setScale(int newScale, RoundingMode JavaDoc roundingMode) {
2238        return setScale(newScale, roundingMode.oldMode);
2239    }
2240
2241    /**
2242     * Returns a <tt>BigDecimal</tt> whose scale is the specified
2243     * value, and whose unscaled value is determined by multiplying or
2244     * dividing this <tt>BigDecimal</tt>'s unscaled value by the
2245     * appropriate power of ten to maintain its overall value. If the
2246     * scale is reduced by the operation, the unscaled value must be
2247     * divided (rather than multiplied), and the value may be changed;
2248     * in this case, the specified rounding mode is applied to the
2249     * division.
2250     *
2251     * <p>Note that since BigDecimal objects are immutable, calls of
2252     * this method do <i>not</i> result in the original object being
2253     * modified, contrary to the usual convention of having methods
2254     * named <tt>set<i>X</i></tt> mutate field <tt><i>X</i></tt>.
2255     * Instead, <tt>setScale</tt> returns an object with the proper
2256     * scale; the returned object may or may not be newly allocated.
2257     *
2258     * <p>The new {@link #setScale(int, RoundingMode)} method should
2259     * be used in preference to this legacy method.
2260     *
2261     * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
2262     * @param roundingMode The rounding mode to apply.
2263     * @return a <tt>BigDecimal</tt> whose scale is the specified value,
2264     * and whose unscaled value is determined by multiplying or
2265     * dividing this <tt>BigDecimal</tt>'s unscaled value by the
2266     * appropriate power of ten to maintain its overall value.
2267     * @throws ArithmeticException if <tt>roundingMode==ROUND_UNNECESSARY</tt>
2268     * and the specified scaling operation would require
2269     * rounding.
2270     * @throws IllegalArgumentException if <tt>roundingMode</tt> does not
2271     * represent a valid rounding mode.
2272     * @see #ROUND_UP
2273     * @see #ROUND_DOWN
2274     * @see #ROUND_CEILING
2275     * @see #ROUND_FLOOR
2276     * @see #ROUND_HALF_UP
2277     * @see #ROUND_HALF_DOWN
2278     * @see #ROUND_HALF_EVEN
2279     * @see #ROUND_UNNECESSARY
2280     */

2281    public BigDecimal JavaDoc setScale(int newScale, int roundingMode) {
2282        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2283            throw new IllegalArgumentException JavaDoc("Invalid rounding mode");
2284
2285        if (newScale == this.scale) // easy case
2286
return this;
2287    if (this.signum() == 0) // zero can have any scale
2288
return BigDecimal.valueOf(0, newScale);
2289        if (newScale > this.scale) {
2290            // [we can use checkScale to assure multiplier is valid]
2291
int raise = checkScale((long)newScale - this.scale);
2292
2293        if (intCompact != INFLATED) {
2294        long scaledResult = longTenToThe(intCompact, raise);
2295        if (scaledResult != INFLATED)
2296            return BigDecimal.valueOf(scaledResult, newScale);
2297        this.inflate();
2298        }
2299
2300            BigDecimal JavaDoc result = new BigDecimal JavaDoc(intVal.multiply(tenToThe(raise)),
2301                           newScale);
2302            if (this.precision > 0)
2303                result.precision = this.precision + newScale - this.scale;
2304            return result;
2305        }
2306        // scale < this.scale
2307
// we cannot perfectly predict the precision after rounding
2308
return divide(ONE, newScale, roundingMode);
2309    }
2310
2311    /**
2312     * Returns a <tt>BigDecimal</tt> whose scale is the specified
2313     * value, and whose value is numerically equal to this
2314     * <tt>BigDecimal</tt>'s. Throws an <tt>ArithmeticException</tt>
2315     * if this is not possible.
2316     *
2317     * <p>This call is typically used to increase the scale, in which
2318     * case it is guaranteed that there exists a <tt>BigDecimal</tt>
2319     * of the specified scale and the correct value. The call can
2320     * also be used to reduce the scale if the caller knows that the
2321     * <tt>BigDecimal</tt> has sufficiently many zeros at the end of
2322     * its fractional part (i.e., factors of ten in its integer value)
2323     * to allow for the rescaling without changing its value.
2324     *
2325     * <p>This method returns the same result as the two-argument
2326     * versions of <tt>setScale</tt>, but saves the caller the trouble
2327     * of specifying a rounding mode in cases where it is irrelevant.
2328     *
2329     * <p>Note that since <tt>BigDecimal</tt> objects are immutable,
2330     * calls of this method do <i>not</i> result in the original
2331     * object being modified, contrary to the usual convention of
2332     * having methods named <tt>set<i>X</i></tt> mutate field
2333     * <tt><i>X</i></tt>. Instead, <tt>setScale</tt> returns an
2334     * object with the proper scale; the returned object may or may
2335     * not be newly allocated.
2336     *
2337     * @param newScale scale of the <tt>BigDecimal</tt> value to be returned.
2338     * @return a <tt>BigDecimal</tt> whose scale is the specified value, and
2339     * whose unscaled value is determined by multiplying or dividing
2340     * this <tt>BigDecimal</tt>'s unscaled value by the appropriate
2341     * power of ten to maintain its overall value.
2342     * @throws ArithmeticException if the specified scaling operation would
2343     * require rounding.
2344     * @see #setScale(int, int)
2345     * @see #setScale(int, RoundingMode)
2346     */

2347    public BigDecimal JavaDoc setScale(int newScale) {
2348        return setScale(newScale, ROUND_UNNECESSARY);
2349    }
2350
2351    // Decimal Point Motion Operations
2352

2353    /**
2354     * Returns a <tt>BigDecimal</tt> which is equivalent to this one
2355     * with the decimal point moved <tt>n</tt> places to the left. If
2356     * <tt>n</tt> is non-negative, the call merely adds <tt>n</tt> to
2357     * the scale. If <tt>n</tt> is negative, the call is equivalent
2358     * to <tt>movePointRight(-n)</tt>. The <tt>BigDecimal</tt>
2359     * returned by this call has value <tt>(this &times;
2360     * 10<sup>-n</sup>)</tt> and scale <tt>max(this.scale()+n,
2361     * 0)</tt>.
2362     *
2363     * @param n number of places to move the decimal point to the left.
2364     * @return a <tt>BigDecimal</tt> which is equivalent to this one with the
2365     * decimal point moved <tt>n</tt> places to the left.
2366     * @throws ArithmeticException if scale overflows.
2367     */

2368    public BigDecimal JavaDoc movePointLeft(int n) {
2369        // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2370
int newScale = checkScale((long)scale + n);
2371    BigDecimal JavaDoc num;
2372    if (intCompact != INFLATED)
2373        num = BigDecimal.valueOf(intCompact, newScale);
2374    else
2375        num = new BigDecimal JavaDoc(intVal, newScale);
2376        return (num.scale<0 ? num.setScale(0) : num);
2377    }
2378
2379    /**
2380     * Returns a <tt>BigDecimal</tt> which is equivalent to this one
2381     * with the decimal point moved <tt>n</tt> places to the right.
2382     * If <tt>n</tt> is non-negative, the call merely subtracts
2383     * <tt>n</tt> from the scale. If <tt>n</tt> is negative, the call
2384     * is equivalent to <tt>movePointLeft(-n)</tt>. The
2385     * <tt>BigDecimal</tt> returned by this call has value <tt>(this
2386     * &times; 10<sup>n</sup>)</tt> and scale <tt>max(this.scale()-n,
2387     * 0)</tt>.
2388     *
2389     * @param n number of places to move the decimal point to the right.
2390     * @return a <tt>BigDecimal</tt> which is equivalent to this one
2391     * with the decimal point moved <tt>n</tt> places to the right.
2392     * @throws ArithmeticException if scale overflows.
2393     */

2394    public BigDecimal JavaDoc movePointRight(int n) {
2395        // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2396
int newScale = checkScale((long)scale - n);
2397    BigDecimal JavaDoc num;
2398    if (intCompact != INFLATED)
2399        num = BigDecimal.valueOf(intCompact, newScale);
2400    else
2401        num = new BigDecimal JavaDoc(intVal, newScale);
2402        return (num.scale<0 ? num.setScale(0) : num);
2403    }
2404
2405    /**
2406     * Returns a BigDecimal whose numerical value is equal to
2407     * (<tt>this</tt> * 10<sup>n</sup>). The scale of
2408     * the result is <tt>(this.scale() - n)</tt>.
2409     *
2410     * @throws ArithmeticException if the scale would be
2411     * outside the range of a 32-bit integer.
2412     *
2413     * @since 1.5
2414     */

2415    public BigDecimal JavaDoc scaleByPowerOfTen(int n) {
2416    this.inflate();
2417        BigDecimal JavaDoc num = new BigDecimal JavaDoc(intVal, checkScale((long)scale - n));
2418        num.precision = precision;
2419        return num;
2420    }
2421
2422    /**
2423     * Returns a <tt>BigDecimal</tt> which is numerically equal to
2424     * this one but with any trailing zeros removed from the
2425     * representation. For example, stripping the trailing zeros from
2426     * the <tt>BigDecimal</tt> value <tt>600.0</tt>, which has
2427     * [<tt>BigInteger</tt>, <tt>scale</tt>] components equals to
2428     * [6000, 1], yields <tt>6E2</tt> with [<tt>BigInteger</tt>,
2429     * <tt>scale</tt>] components equals to [6, -2]
2430     *
2431     * @return a numerically equal <tt>BigDecimal</tt> with any
2432     * trailing zeros removed.
2433     */

2434    public BigDecimal JavaDoc stripTrailingZeros() {
2435    this.inflate();
2436    return (new BigDecimal JavaDoc(intVal, scale)).stripZerosToMatchScale(Long.MIN_VALUE);
2437    }
2438
2439    // Comparison Operations
2440

2441    /**
2442     * Compares this <tt>BigDecimal</tt> with the specified
2443     * <tt>BigDecimal</tt>. Two <tt>BigDecimal</tt> objects that are
2444     * equal in value but have a different scale (like 2.0 and 2.00)
2445     * are considered equal by this method. This method is provided
2446     * in preference to individual methods for each of the six boolean
2447     * comparison operators (&lt;, ==, &gt;, &gt;=, !=, &lt;=). The
2448     * suggested idiom for performing these comparisons is:
2449     * <tt>(x.compareTo(y)</tt> &lt;<i>op</i>&gt; <tt>0)</tt>, where
2450     * &lt;<i>op</i>&gt; is one of the six comparison operators.
2451     *
2452     * @param val <tt>BigDecimal</tt> to which this <tt>BigDecimal</tt> is
2453     * to be compared.
2454     * @return -1, 0, or 1 as this <tt>BigDecimal</tt> is numerically
2455     * less than, equal to, or greater than <tt>val</tt>.
2456     */

2457    public int compareTo(BigDecimal JavaDoc val) {
2458    // Optimization: would run fine without the next three lines
2459
int sigDiff = signum() - val.signum();
2460    if (sigDiff != 0)
2461        return (sigDiff > 0 ? 1 : -1);
2462
2463    // If the (adjusted) exponents are different we do not need to
2464
// expensively match scales and compare the significands
2465
int aethis = this.precision() - this.scale; // [-1]
2466
int aeval = val.precision() - val.scale; // [-1]
2467
if (aethis < aeval)
2468        return -this.signum();
2469    else if (aethis > aeval)
2470        return this.signum();
2471
2472    // Scale and compare intVals
2473
BigDecimal JavaDoc arg[] = {this, val};
2474    matchScale(arg);
2475    if (arg[0].intCompact != INFLATED && arg[1].intCompact != INFLATED)
2476        return longCompareTo(arg[0].intCompact, arg[1].intCompact);
2477    return arg[0].inflate().intVal.compareTo(arg[1].inflate().intVal);
2478    }
2479
2480    /**
2481     * Compares this <tt>BigDecimal</tt> with the specified
2482     * <tt>Object</tt> for equality. Unlike {@link
2483     * #compareTo(BigDecimal) compareTo}, this method considers two
2484     * <tt>BigDecimal</tt> objects equal only if they are equal in
2485     * value and scale (thus 2.0 is not equal to 2.00 when compared by
2486     * this method).
2487     *
2488     * @param x <tt>Object</tt> to which this <tt>BigDecimal</tt> is
2489     * to be compared.
2490     * @return <tt>true</tt> if and only if the specified <tt>Object</tt> is a
2491     * <tt>BigDecimal</tt> whose value and scale are equal to this
2492     * <tt>BigDecimal</tt>'s.
2493     * @see #compareTo(java.math.BigDecimal)
2494     * @see #hashCode
2495     */

2496    public boolean equals(Object JavaDoc x) {
2497        if (!(x instanceof BigDecimal JavaDoc))
2498            return false;
2499        BigDecimal JavaDoc xDec = (BigDecimal JavaDoc) x;
2500    if (scale != xDec.scale)
2501        return false;
2502    if (this.intCompact != INFLATED && xDec.intCompact != INFLATED)
2503        return this.intCompact == xDec.intCompact;
2504        return this.inflate().intVal.equals(xDec.inflate().intVal);
2505    }
2506
2507    /**
2508     * Returns the minimum of this <tt>BigDecimal</tt> and
2509     * <tt>val</tt>.
2510     *
2511     * @param val value with which the minimum is to be computed.
2512     * @return the <tt>BigDecimal</tt> whose value is the lesser of this
2513     * <tt>BigDecimal</tt> and <tt>val</tt>. If they are equal,
2514     * as defined by the {@link #compareTo(BigDecimal) compareTo}
2515     * method, <tt>this</tt> is returned.
2516     * @see #compareTo(java.math.BigDecimal)
2517     */

2518    public BigDecimal JavaDoc min(BigDecimal JavaDoc val) {
2519        return (compareTo(val) <= 0 ? this : val);
2520    }
2521
2522    /**
2523     * Returns the maximum of this <tt>BigDecimal</tt> and <tt>val</tt>.
2524     *
2525     * @param val value with which the maximum is to be computed.
2526     * @return the <tt>BigDecimal</tt> whose value is the greater of this
2527     * <tt>BigDecimal</tt> and <tt>val</tt>. If they are equal,
2528     * as defined by the {@link #compareTo(BigDecimal) compareTo}
2529     * method, <tt>this</tt> is returned.
2530     * @see #compareTo(java.math.BigDecimal)
2531     */

2532    public BigDecimal JavaDoc max(BigDecimal JavaDoc val) {
2533        return (compareTo(val) >= 0 ? this : val);
2534    }
2535
2536    // Hash Function
2537

2538    /**
2539     * Returns the hash code for this <tt>BigDecimal</tt>. Note that
2540     * two <tt>BigDecimal</tt> objects that are numerically equal but
2541     * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2542     * have the same hash code.
2543     *
2544     * @return hash code for this <tt>BigDecimal</tt>.
2545     * @see #equals(Object)
2546     */

2547    public int hashCode() {
2548    if (intCompact != INFLATED) {
2549        long val2 = (intCompact < 0)?-intCompact:intCompact;
2550        int temp = (int)( ((int)(val2 >>> 32)) * 31 +
2551                  (val2 & 0xffffffffL));
2552        return 31*((intCompact < 0) ?-temp:temp) + scale;
2553    } else
2554        return 31*intVal.hashCode() + scale;
2555    }
2556
2557    // Format Converters
2558

2559    /**
2560     * Returns the string representation of this <tt>BigDecimal</tt>,
2561     * using scientific notation if an exponent is needed.
2562     *
2563     * <p>A standard canonical string form of the <tt>BigDecimal</tt>
2564     * is created as though by the following steps: first, the
2565     * absolute value of the unscaled value of the <tt>BigDecimal</tt>
2566     * is converted to a string in base ten using the characters
2567     * <tt>'0'</tt> through <tt>'9'</tt> with no leading zeros (except
2568     * if its value is zero, in which case a single <tt>'0'</tt>
2569     * character is used).
2570     *
2571     * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2572     * negated scale, plus the number of characters in the converted
2573     * unscaled value, less one. That is,
2574     * <tt>-scale+(ulength-1)</tt>, where <tt>ulength</tt> is the
2575     * length of the absolute value of the unscaled value in decimal
2576     * digits (its <i>precision</i>).
2577     *
2578     * <p>If the scale is greater than or equal to zero and the
2579     * adjusted exponent is greater than or equal to <tt>-6</tt>, the
2580     * number will be converted to a character form without using
2581     * exponential notation. In this case, if the scale is zero then
2582     * no decimal point is added and if the scale is positive a
2583     * decimal point will be inserted with the scale specifying the
2584     * number of characters to the right of the decimal point.
2585     * <tt>'0'</tt> characters are added to the left of the converted
2586     * unscaled value as necessary. If no character precedes the
2587     * decimal point after this insertion then a conventional
2588     * <tt>'0'</tt> character is prefixed.
2589     *
2590     * <p>Otherwise (that is, if the scale is negative, or the
2591     * adjusted exponent is less than <tt>-6</tt>), the number will be
2592     * converted to a character form using exponential notation. In
2593     * this case, if the converted <tt>BigInteger</tt> has more than
2594     * one digit a decimal point is inserted after the first digit.
2595     * An exponent in character form is then suffixed to the converted
2596     * unscaled value (perhaps with inserted decimal point); this
2597     * comprises the letter <tt>'E'</tt> followed immediately by the
2598     * adjusted exponent converted to a character form. The latter is
2599     * in base ten, using the characters <tt>'0'</tt> through
2600     * <tt>'9'</tt> with no leading zeros, and is always prefixed by a
2601     * sign character <tt>'-'</tt> (<tt>'&#92;u002D'</tt>) if the
2602     * adjusted exponent is negative, <tt>'+'</tt>
2603     * (<tt>'&#92;u002B'</tt>) otherwise).
2604     *
2605     * <p>Finally, the entire string is prefixed by a minus sign
2606     * character <tt>'-'</tt> (<tt>'&#92;u002D'</tt>) if the unscaled
2607     * value is less than zero. No sign character is prefixed if the
2608     * unscaled value is zero or positive.
2609     *
2610     * <p><b>Examples:</b>
2611     * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2612     * on the left, the resulting string is shown on the right.
2613     * <pre>
2614     * [123,0] &quot;123&quot;
2615     * [-123,0] &quot;-123&quot;
2616     * [123,-1] &quot;1.23E+3&quot;
2617     * [123,-3] &quot;1.23E+5&quot;
2618     * [123,1] &quot;12.3&quot;
2619     * [123,5] &quot;0.00123&quot;
2620     * [123,10] &quot;1.23E-8&quot;
2621     * [-123,12] &quot;-1.23E-10&quot;
2622     * </pre>
2623     *
2624     * <b>Notes:</b>
2625     * <ol>
2626     *
2627     * <li>There is a one-to-one mapping between the distinguishable
2628     * <tt>BigDecimal</tt> values and the result of this conversion.
2629     * That is, every distinguishable <tt>BigDecimal</tt> value
2630     * (unscaled value and scale) has a unique string representation
2631     * as a result of using <tt>toString</tt>. If that string
2632     * representation is converted back to a <tt>BigDecimal</tt> using
2633     * the {@link #BigDecimal(String)} constructor, then the original
2634     * value will be recovered.
2635     *
2636     * <li>The string produced for a given number is always the same;
2637     * it is not affected by locale. This means that it can be used
2638     * as a canonical string representation for exchanging decimal
2639     * data, or as a key for a Hashtable, etc. Locale-sensitive
2640     * number formatting and parsing is handled by the {@link
2641     * java.text.NumberFormat} class and its subclasses.
2642     *
2643     * <li>The {@link #toEngineeringString} method may be used for
2644     * presenting numbers with exponents in engineering notation, and the
2645     * {@link #setScale(int,RoundingMode) setScale} method may be used for
2646     * rounding a <tt>BigDecimal</tt> so it has a known number of digits after
2647     * the decimal point.
2648     *
2649     * <li>The digit-to-character mapping provided by
2650     * <tt>Character.forDigit</tt> is used.
2651     *
2652     * </ol>
2653     *
2654     * @return string representation of this <tt>BigDecimal</tt>.
2655     * @see Character#forDigit
2656     * @see #BigDecimal(java.lang.String)
2657     */

2658    public String JavaDoc toString() {
2659    if (stringCache == null)
2660        stringCache = layoutChars(true);
2661    return stringCache;
2662    }
2663
2664    /**
2665     * Returns a string representation of this <tt>BigDecimal</tt>,
2666     * using engineering notation if an exponent is needed.
2667     *
2668     * <p>Returns a string that represents the <tt>BigDecimal</tt> as
2669     * described in the {@link #toString()} method, except that if
2670     * exponential notation is used, the power of ten is adjusted to
2671     * be a multiple of three (engineering notation) such that the
2672     * integer part of nonzero values will be in the range 1 through
2673     * 999. If exponential notation is used for zero values, a
2674     * decimal point and one or two fractional zero digits are used so
2675     * that the scale of the zero value is preserved. Note that
2676     * unlike the output of {@link #toString()}, the output of this
2677     * method is <em>not</em> guaranteed to recover the same [integer,
2678     * scale] pair of this <tt>BigDecimal</tt> if the output string is
2679     * converting back to a <tt>BigDecimal</tt> using the {@linkplain
2680     * #BigDecimal(String) string constructor}. The result of this method meets
2681     * the weaker constraint of always producing a numerically equal
2682     * result from applying the string constructor to the method's output.
2683     *
2684     * @return string representation of this <tt>BigDecimal</tt>, using
2685     * engineering notation if an exponent is needed.
2686     * @since 1.5
2687     */

2688    public String JavaDoc toEngineeringString() {
2689        return layoutChars(false);
2690    }
2691
2692    /**
2693     * Returns a string representation of this <tt>BigDecimal</tt>
2694     * without an exponent field. For values with a positive scale,
2695     * the number of digits to the right of the decimal point is used
2696     * to indicate scale. For values with a zero or negative scale,
2697     * the resulting string is generated as if the value were
2698     * converted to a numerically equal value with zero scale and as
2699     * if all the trailing zeros of the zero scale value were present
2700     * in the result.
2701     *
2702     * The entire string is prefixed by a minus sign character '-'
2703     * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
2704     * zero. No sign character is prefixed if the unscaled value is
2705     * zero or positive.
2706     *
2707     * Note that if the result of this method is passed to the
2708     * {@linkplain #BigDecimal(String) string constructor}, only the
2709     * numerical value of this <tt>BigDecimal</tt> will necessarily be
2710     * recovered; the representation of the new <tt>BigDecimal</tt>
2711     * may have a different scale. In particular, if this
2712     * <tt>BigDecimal</tt> has a positive scale, the string resulting
2713     * from this method will have a scale of zero when processed by
2714     * the string constructor.
2715     *
2716     * (This method behaves analogously to the <tt>toString</tt>
2717     * method in 1.4 and earlier releases.)
2718     *
2719     * @return a string representation of this <tt>BigDecimal</tt>
2720     * without an exponent field.
2721     * @since 1.5
2722     * @see #toString()
2723     * @see #toEngineeringString()
2724     */

2725    public String JavaDoc toPlainString() {
2726    BigDecimal JavaDoc bd = this;
2727    if (bd.scale < 0)
2728        bd = bd.setScale(0);
2729    bd.inflate();
2730    if (bd.scale == 0) // No decimal point
2731
return bd.intVal.toString();
2732        return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
2733    }
2734
2735    /* Returns a digit.digit string */
2736    private String JavaDoc getValueString(int signum, String JavaDoc intString, int scale) {
2737    /* Insert decimal point */
2738    StringBuilder JavaDoc buf;
2739    int insertionPoint = intString.length() - scale;
2740    if (insertionPoint == 0) { /* Point goes right before intVal */
2741        return (signum<0 ? "-0." : "0.") + intString;
2742    } else if (insertionPoint > 0) { /* Point goes inside intVal */
2743        buf = new StringBuilder JavaDoc(intString);
2744        buf.insert(insertionPoint, '.');
2745        if (signum < 0)
2746        buf.insert(0, '-');
2747    } else { /* We must insert zeros between point and intVal */
2748        buf = new StringBuilder JavaDoc(3-insertionPoint + intString.length());
2749        buf.append(signum<0 ? "-0." : "0.");
2750        for (int i=0; i<-insertionPoint; i++)
2751        buf.append('0');
2752        buf.append(intString);
2753    }
2754    return buf.toString();
2755    }
2756
2757    /**
2758     * Converts this <tt>BigDecimal</tt> to a <tt>BigInteger</tt>.
2759     * This conversion is analogous to a <a
2760     * HREF="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2761     * primitive conversion</i></a> from <tt>double</tt> to
2762     * <tt>long</tt> as defined in the <a
2763     * HREF="http://java.sun.com/docs/books/jls/html/">Java Language
2764     * Specification</a>: any fractional part of this
2765     * <tt>BigDecimal</tt> will be discarded. Note that this
2766     * conversion can lose information about the precision of the
2767     * <tt>BigDecimal</tt> value.
2768     * <p>
2769     * To have an exception thrown if the conversion is inexact (in
2770     * other words if a nonzero fractional part is discarded), use the
2771     * {@link #toBigIntegerExact()} method.
2772     *
2773     * @return this <tt>BigDecimal</tt> converted to a <tt>BigInteger</tt>.
2774     */

2775    public BigInteger JavaDoc toBigInteger() {
2776        // force to an integer, quietly
2777
return this.setScale(0, ROUND_DOWN).inflate().intVal;
2778    }
2779
2780    /**
2781     * Converts this <tt>BigDecimal</tt> to a <tt>BigInteger</tt>,
2782     * checking for lost information. An exception is thrown if this
2783     * <tt>BigDecimal</tt> has a nonzero fractional part.
2784     *
2785     * @return this <tt>BigDecimal</tt> converted to a <tt>BigInteger</tt>.
2786     * @throws ArithmeticException if <tt>this</tt> has a nonzero
2787     * fractional part.
2788     * @since 1.5
2789     */

2790    public BigInteger JavaDoc toBigIntegerExact() {
2791        // round to an integer, with Exception if decimal part non-0
2792
return this.setScale(0, ROUND_UNNECESSARY).inflate().intVal;
2793    }
2794
2795    /**
2796     * Converts this <tt>BigDecimal</tt> to a <tt>long</tt>. This
2797     * conversion is analogous to a <a
2798     * HREF="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2799     * primitive conversion</i></a> from <tt>double</tt> to
2800     * <tt>short</tt> as defined in the <a
2801     * HREF="http://java.sun.com/docs/books/jls/html/">Java Language
2802     * Specification</a>: any fractional part of this
2803     * <tt>BigDecimal</tt> will be discarded, and if the resulting
2804     * &quot;<tt>BigInteger</tt>&quot; is too big to fit in a
2805     * <tt>long</tt>, only the low-order 64 bits are returned.
2806     * Note that this conversion can lose information about the
2807     * overall magnitude and precision of this <tt>BigDecimal</tt> value as well
2808     * as return a result with the opposite sign.
2809     *
2810     * @return this <tt>BigDecimal</tt> converted to a <tt>long</tt>.
2811     */

2812    public long longValue(){
2813    return (intCompact != INFLATED && scale == 0) ?
2814        intCompact:
2815        toBigInteger().longValue();
2816    }
2817
2818    /**
2819     * Converts this <tt>BigDecimal</tt> to a <tt>long</tt>, checking
2820     * for lost information. If this <tt>BigDecimal</tt> has a
2821     * nonzero fractional part or is out of the possible range for a
2822     * <tt>long</tt> result then an <tt>ArithmeticException</tt> is
2823     * thrown.
2824     *
2825     * @return this <tt>BigDecimal</tt> converted to a <tt>long</tt>.
2826     * @throws ArithmeticException if <tt>this</tt> has a nonzero
2827     * fractional part, or will not fit in a <tt>long</tt>.
2828     * @since 1.5
2829     */

2830    public long longValueExact() {
2831    if (intCompact != INFLATED && scale == 0)
2832        return intCompact;
2833        // If more than 19 digits in integer part it cannot possibly fit
2834
if ((precision() - scale) > 19) // [OK for negative scale too]
2835
throw new java.lang.ArithmeticException JavaDoc("Overflow");
2836        // Fastpath zero and < 1.0 numbers (the latter can be very slow
2837
// to round if very small)
2838
if (this.signum() == 0)
2839            return 0;
2840        if ((this.precision() - this.scale) <= 0)
2841            throw new ArithmeticException JavaDoc("Rounding necessary");
2842        // round to an integer, with Exception if decimal part non-0
2843
BigDecimal JavaDoc num = this.setScale(0, ROUND_UNNECESSARY).inflate();
2844        if (num.precision() >= 19) { // need to check carefully
2845
if (LONGMIN == null) { // initialize constants
2846
LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
2847                LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
2848            }
2849            if ((num.intVal.compareTo(LONGMIN) < 0) ||
2850                (num.intVal.compareTo(LONGMAX) > 0))
2851                throw new java.lang.ArithmeticException JavaDoc("Overflow");
2852        }
2853        return num.intVal.longValue();
2854    }
2855    // These constants are only initialized if needed
2856
/** BigInteger equal to Long.MIN_VALUE. */
2857    private static BigInteger JavaDoc LONGMIN = null;
2858    /** BigInteger equal to Long.MAX_VALUE. */
2859    private static BigInteger JavaDoc LONGMAX = null;
2860
2861    /**
2862     * Converts this <tt>BigDecimal</tt> to an <tt>int</tt>. This
2863     * conversion is analogous to a <a
2864     * HREF="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2865     * primitive conversion</i></a> from <tt>double</tt> to
2866     * <tt>short</tt> as defined in the <a
2867     * HREF="http://java.sun.com/docs/books/jls/html/">Java Language
2868     * Specification</a>: any fractional part of this
2869     * <tt>BigDecimal</tt> will be discarded, and if the resulting
2870     * &quot;<tt>BigInteger</tt>&quot; is too big to fit in an
2871     * <tt>int</tt>, only the low-order 32 bits are returned.
2872     * Note that this conversion can lose information about the
2873     * overall magnitude and precision of this <tt>BigDecimal</tt>
2874     * value as well as return a result with the opposite sign.
2875     *
2876     * @return this <tt>BigDecimal</tt> converted to an <tt>int</tt>.
2877     */

2878    public int intValue() {
2879    return (intCompact != INFLATED && scale == 0) ?
2880        (int)intCompact :
2881        toBigInteger().intValue();
2882    }
2883
2884    /**
2885     * Converts this <tt>BigDecimal</tt> to an <tt>int</tt>, checking
2886     * for lost information. If this <tt>BigDecimal</tt> has a
2887     * nonzero fractional part or is out of the possible range for an
2888     * <tt>int</tt> result then an <tt>ArithmeticException</tt> is
2889     * thrown.
2890     *
2891     * @return this <tt>BigDecimal</tt> converted to an <tt>int</tt>.
2892     * @throws ArithmeticException if <tt>this</tt> has a nonzero
2893     * fractional part, or will not fit in an <tt>int</tt>.
2894     * @since 1.5
2895     */

2896    public int intValueExact() {
2897       long num;
2898       num = this.longValueExact(); // will check decimal part
2899
if ((int)num != num)
2900           throw new java.lang.ArithmeticException JavaDoc("Overflow");
2901       return (int)num;
2902    }
2903
2904    /**
2905     * Converts this <tt>BigDecimal</tt> to a <tt>short</tt>, checking
2906     * for lost information. If this <tt>BigDecimal</tt> has a
2907     * nonzero fractional part or is out of the possible range for a
2908     * <tt>short</tt> result then an <tt>ArithmeticException</tt> is
2909     * thrown.
2910     *
2911     * @return this <tt>BigDecimal</tt> converted to a <tt>short</tt>.
2912     * @throws ArithmeticException if <tt>this</tt> has a nonzero
2913     * fractional part, or will not fit in a <tt>short</tt>.
2914     * @since 1.5
2915     */

2916    public short shortValueExact() {
2917       long num;
2918       num = this.longValueExact(); // will check decimal part
2919
if ((short)num != num)
2920           throw new java.lang.ArithmeticException JavaDoc("Overflow");
2921       return (short)num;
2922    }
2923
2924    /**
2925     * Converts this <tt>BigDecimal</tt> to a <tt>byte</tt>, checking
2926     * for lost information. If this <tt>BigDecimal</tt> has a
2927     * nonzero fractional part or is out of the possible range for a
2928     * <tt>byte</tt> result then an <tt>ArithmeticException</tt> is
2929     * thrown.
2930     *
2931     * @return this <tt>BigDecimal</tt> converted to a <tt>byte</tt>.
2932     * @throws ArithmeticException if <tt>this</tt> has a nonzero
2933     * fractional part, or will not fit in a <tt>byte</tt>.
2934     * @since 1.5
2935     */

2936    public byte byteValueExact() {
2937       long num;
2938       num = this.longValueExact(); // will check decimal part
2939
if ((byte)num != num)
2940           throw new java.lang.ArithmeticException JavaDoc("Overflow");
2941       return (byte)num;
2942    }
2943
2944    /**
2945     * Converts this <tt>BigDecimal</tt> to a <tt>float</tt>.
2946     * This conversion is similar to the <a
2947     * HREF="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2948     * primitive conversion</i></a> from <tt>double</tt> to
2949     * <tt>float</tt> defined in the <a
2950     * HREF="http://java.sun.com/docs/books/jls/html/">Java Language
2951     * Specification</a>: if this <tt>BigDecimal</tt> has too great a
2952     * magnitude to represent as a <tt>float</tt>, it will be
2953     * converted to {@link Float#NEGATIVE_INFINITY} or {@link
2954     * Float#POSITIVE_INFINITY} as appropriate. Note that even when
2955     * the return value is finite, this conversion can lose
2956     * information about the precision of the <tt>BigDecimal</tt>
2957     * value.
2958     *
2959     * @return this <tt>BigDecimal</tt> converted to a <tt>float</tt>.
2960     */

2961    public float floatValue(){
2962    if (scale == 0 && intCompact != INFLATED)
2963        return (float)intCompact;
2964    // Somewhat inefficient, but guaranteed to work.
2965
return Float.parseFloat(this.toString());
2966    }
2967
2968    /**
2969     * Converts this <tt>BigDecimal</tt> to a <tt>double</tt>.
2970     * This conversion is similar to the <a
2971     * HREF="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2972     * primitive conversion</i></a> from <tt>double</tt> to
2973     * <tt>float</tt> as defined in the <a
2974     * HREF="http://java.sun.com/docs/books/jls/html/">Java Language
2975     * Specification</a>: if this <tt>BigDecimal</tt> has too great a
2976     * magnitude represent as a <tt>double</tt>, it will be
2977     * converted to {@link Double#NEGATIVE_INFINITY} or {@link
2978     * Double#POSITIVE_INFINITY} as appropriate. Note that even when
2979     * the return value is finite, this conversion can lose
2980     * information about the precision of the <tt>BigDecimal</tt>
2981     * value.
2982     *
2983     * @return this <tt>BigDecimal</tt> converted to a <tt>double</tt>.
2984     */

2985    public double doubleValue(){
2986    if (scale == 0 && intCompact != INFLATED)
2987        return (double)intCompact;
2988    // Somewhat inefficient, but guaranteed to work.
2989
return Double.parseDouble(this.toString());
2990    }
2991
2992    /**
2993     * Returns the size of an ulp, a unit in the last place, of this
2994     * <tt>BigDecimal</tt>. An ulp of a nonzero <tt>BigDecimal</tt>
2995     * value is the positive distance between this value and the
2996     * <tt>BigDecimal</tt> value next larger in magnitude with the
2997     * same number of digits. An ulp of a zero value is numerically
2998     * equal to 1 with the scale of <tt>this</tt>. The result is
2999     * stored with the same scale as <code>this</code> so the result
3000     * for zero and nonzero values is equal to <code>[1,
3001     * this.scale()]</code>.
3002     *
3003     * @return the size of an ulp of <tt>this</tt>
3004     * @since 1.5
3005     */

3006    public BigDecimal JavaDoc ulp() {
3007    return BigDecimal.valueOf(1, this.scale());
3008    }
3009
3010    // Private "Helper" Methods
3011

3012    /**
3013     * Lay out this <tt>BigDecimal</tt> into a <tt>char[]</tt> array.
3014     * The Java 1.2 equivalent to this was called <tt>getValueString</tt>.
3015     *
3016     * @param sci <tt>true</tt> for Scientific exponential notation;
3017     * <tt>false</tt> for Engineering
3018     * @return string with canonical string representation of this
3019     * <tt>BigDecimal</tt>
3020     */

3021    private String JavaDoc layoutChars(boolean sci) {
3022        if (scale == 0) // zero scale is trivial
3023
return (intCompact != INFLATED) ?
3024        Long.toString(intCompact):
3025        intVal.toString();
3026
3027        // Get the significand as an absolute value
3028
char coeff[];
3029    if (intCompact != INFLATED)
3030        coeff = Long.toString(Math.abs(intCompact)).toCharArray();
3031    else
3032        coeff = intVal.abs().toString().toCharArray();
3033
3034        // Construct a buffer, with sufficient capacity for all cases.
3035
// If E-notation is needed, length will be: +1 if negative, +1
3036
// if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3037
// Otherwise it could have +1 if negative, plus leading "0.00000"
3038
StringBuilder JavaDoc buf=new StringBuilder JavaDoc(coeff.length+14);
3039        if (signum() < 0) // prefix '-' if negative
3040
buf.append('-');
3041        long adjusted = -(long)scale + (coeff.length-1);
3042        if ((scale >= 0) && (adjusted >= -6)) { // plain number
3043
int pad = scale - coeff.length; // count of padding zeros
3044
if (pad >= 0) { // 0.xxx form
3045
buf.append('0');
3046                buf.append('.');
3047                for (; pad>0; pad--) {
3048                    buf.append('0');
3049                }
3050                buf.append(coeff);
3051            } else { // xx.xx form
3052
buf.append(coeff, 0, -pad);
3053                buf.append('.');
3054                buf.append(coeff, -pad, scale);
3055            }
3056        } else { // E-notation is needed
3057
if (sci) { // Scientific notation
3058
buf.append(coeff[0]); // first character
3059
if (coeff.length > 1) { // more to come
3060
buf.append('.');
3061                    buf.append(coeff, 1, coeff.length-1);
3062                }
3063            } else { // Engineering notation
3064
int sig = (int)(adjusted % 3);
3065                if (sig < 0)
3066                    sig += 3; // [adjusted was negative]
3067
adjusted -= sig; // now a multiple of 3
3068
sig++;
3069        if (signum() == 0) {
3070            switch (sig) {
3071            case 1:
3072            buf.append('0'); // exponent is a multiple of three
3073
break;
3074            case 2:
3075            buf.append("0.00");
3076            adjusted += 3;
3077            break;
3078            case 3:
3079            buf.append("0.0");
3080            adjusted += 3;
3081            break;
3082            default:
3083            throw new AssertionError JavaDoc("Unexpected sig value " + sig);
3084            }
3085        } else if (sig >= coeff.length) { // significand all in integer
3086
buf.append(coeff, 0, coeff.length);
3087                    // may need some zeros, too
3088
for (int i = sig - coeff.length; i > 0; i--)
3089                        buf.append('0');
3090                } else { // xx.xxE form
3091
buf.append(coeff, 0, sig);
3092                    buf.append('.');
3093                    buf.append(coeff, sig, coeff.length-sig);
3094                }
3095            }
3096            if (adjusted != 0) { // [!sci could have made 0]
3097
buf.append('E');
3098                if (adjusted > 0) // force sign for positive
3099
buf.append('+');
3100                buf.append(adjusted);
3101            }
3102        }
3103        return buf.toString();
3104    }
3105
3106    /**
3107     * Return 10 to the power n, as a <tt>BigInteger</tt>.
3108     *
3109     * @param n the power of ten to be returned (>=0)
3110     * @return a <tt>BigInteger</tt> with the value (10<sup>n</sup>)
3111     */

3112    private static BigInteger JavaDoc tenToThe(int n) {
3113        if (n < TENPOWERS.length) // use value from constant array
3114
return TENPOWERS[n];
3115        // BigInteger.pow is slow, so make 10**n by constructing a
3116
// BigInteger from a character string (still not very fast)
3117
char tenpow[] = new char[n + 1];
3118        tenpow[0] = '1';
3119        for (int i = 1; i <= n; i++)
3120        tenpow[i] = '0';
3121        return new BigInteger JavaDoc(tenpow);
3122    }
3123    private static BigInteger JavaDoc TENPOWERS[] = {BigInteger.ONE,
3124        BigInteger.valueOf(10), BigInteger.valueOf(100),
3125        BigInteger.valueOf(1000), BigInteger.valueOf(10000),
3126        BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
3127        BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
3128        BigInteger.valueOf(1000000000)};
3129
3130    /**
3131     * Compute val * 10 ^ n; return this product if it is
3132     * representable as a long, INFLATED otherwise.
3133     */

3134    private static long longTenToThe(long val, int n) {
3135    // System.err.print("\tval " + val + "\t power " + n + "\tresult ");
3136
if (n >= 0 && n < thresholds.length) {
3137        if (Math.abs(val) <= thresholds[n][0] ) {
3138        // System.err.println(val * thresholds[n][1]);
3139
return val * thresholds[n][1];
3140        }
3141    }
3142    // System.err.println(INFLATED);
3143
return INFLATED;
3144    }
3145
3146    private static long thresholds[][] = {
3147    {Long.MAX_VALUE, 1L}, // 0
3148
{Long.MAX_VALUE/10L, 10L}, // 1
3149
{Long.MAX_VALUE/100L, 100L}, // 2
3150
{Long.MAX_VALUE/1000L, 1000L}, // 3
3151
{Long.MAX_VALUE/10000L, 10000L}, // 4
3152
{Long.MAX_VALUE/100000L, 100000L}, // 5
3153
{Long.MAX_VALUE/1000000L, 1000000L}, // 6
3154
{Long.MAX_VALUE/10000000L, 10000000L}, // 7
3155
{Long.MAX_VALUE/100000000L, 100000000L}, // 8
3156
{Long.MAX_VALUE/1000000000L, 1000000000L}, // 9
3157
{Long.MAX_VALUE/10000000000L, 10000000000L}, // 10
3158
{Long.MAX_VALUE/100000000000L, 100000000000L}, // 11
3159
{Long.MAX_VALUE/1000000000000L, 1000000000000L},// 12
3160
{Long.MAX_VALUE/100000000000000L, 10000000000000L},// 13
3161
};
3162
3163    private static boolean compactLong(long val) {
3164    return (val != Long.MIN_VALUE);
3165    }
3166
3167    /**
3168     * Assign appropriate BigInteger to intVal field if intVal is
3169     * null, i.e. the compact representation is in use.
3170     */

3171    private BigDecimal JavaDoc inflate() {
3172    if (intVal == null)
3173        intVal = BigInteger.valueOf(intCompact);
3174    return this;
3175    }
3176
3177    /**
3178     * Match the scales of two <tt>BigDecimal<tt>s to align their
3179     * least significant digits.
3180     *
3181     * <p>If the scales of val[0] and val[1] differ, rescale
3182     * (non-destructively) the lower-scaled <tt>BigDecimal</tt> so
3183     * they match. That is, the lower-scaled reference will be
3184     * replaced by a reference to a new object with the same scale as
3185     * the other <tt>BigDecimal</tt>.
3186     *
3187     * @param val array of two elements referring to the two
3188     * <tt>BigDecimal</tt>s to be aligned.
3189     */

3190    private static void matchScale(BigDecimal JavaDoc[] val) {
3191        if (val[0].scale < val[1].scale)
3192            val[0] = val[0].setScale(val[1].scale);
3193        else if (val[1].scale < val[0].scale)
3194            val[1] = val[1].setScale(val[0].scale);
3195    }
3196
3197    /**
3198     * Reconstitute the <tt>BigDecimal</tt> instance from a stream (that is,
3199     * deserialize it).
3200     *
3201     * @param s the stream being read.
3202     */

3203    private synchronized void readObject(java.io.ObjectInputStream JavaDoc s)
3204        throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
3205        // Read in all fields
3206
s.defaultReadObject();
3207        // validate possibly bad fields
3208
if (intVal == null) {
3209            String JavaDoc message = "BigDecimal: null intVal in stream";
3210            throw new java.io.StreamCorruptedException JavaDoc(message);
3211        // [all values of scale are now allowed]
3212
}
3213    // Set intCompact to uninitialized value; could also see if the
3214
// intVal was small enough to fit as a compact value.
3215
intCompact = INFLATED;
3216    }
3217
3218   /**
3219    * Serialize this <tt>BigDecimal</tt> to the stream in question
3220    *
3221    * @param s the stream to serialize to.
3222    */

3223   private void writeObject(java.io.ObjectOutputStream JavaDoc s)
3224       throws java.io.IOException JavaDoc {
3225       // Must inflate to maintain compatible serial form.
3226
this.inflate();
3227
3228       // Write proper fields
3229
s.defaultWriteObject();
3230   }
3231
3232    /**
3233     * Returns the length of this <tt>BigDecimal</tt>, in decimal digits.
3234     *
3235     * Notes:
3236     *<ul>
3237     * <li> This is performance-critical; most operations where a
3238     * context is supplied will need at least one call to this
3239     * method.
3240     *
3241     * <li> This should be a method on BigInteger; the call to this
3242     * method in precision() can then be replaced with the
3243     * term: intVal.digitLength(). It could also be called
3244     * precision() in BigInteger.
3245     *
3246     * Better still -- the precision lookaside could be moved to
3247     * BigInteger, too.
3248     *
3249     * <li> This could/should use MutableBigIntegers directly for the
3250     * reduction loop.
3251     *<ul>
3252     * @return the length of the unscaled value, in decimal digits
3253     */

3254    private int digitLength() {
3255    if (intCompact != INFLATED && Math.abs(intCompact) <= Integer.MAX_VALUE)
3256        return intLength(Math.abs((int)intCompact));
3257        if (signum() == 0) // 0 is one decimal digit
3258
return 1;
3259    this.inflate();
3260        // we have a nonzero magnitude
3261
BigInteger JavaDoc work = intVal;
3262        int digits = 0; // counter
3263
for (;work.mag.length>1;) {
3264            // here when more than one integer in the magnitude; divide
3265
// by a billion (reduce by 9 digits) and try again
3266
work = work.divide(TENPOWERS[9]);
3267            digits += 9;
3268            if (work.signum() == 0) // the division was exact
3269
return digits; // (a power of a billion)
3270
}
3271        // down to a simple nonzero integer
3272
digits += intLength(work.mag[0]);
3273        // System.out.println("digitLength... "+this+" -> "+digits);
3274
return digits;
3275    }
3276
3277    private static int[] ilogTable = {
3278    0,
3279    9,
3280    99,
3281    999,
3282    9999,
3283    99999,
3284    999999,
3285    9999999,
3286    99999999,
3287    999999999,
3288    Integer.MAX_VALUE};
3289
3290    /**
3291     * Returns the length of an unsigned <tt>int</tt>, in decimal digits.
3292     * @param i the <tt>int</tt> (treated as unsigned)
3293     * @return the length of the unscaled value, in decimal digits
3294     */

3295    private int intLength(int x) {
3296        int digits;
3297        if (x < 0) { // 'negative' is 10 digits unsigned
3298
return 10;
3299        } else { // positive integer
3300
if (x <= 9)
3301        return 1;
3302        // "Hacker's Delight" section 11-4
3303
for(int i = -1; ; i++) {
3304        if (x <= ilogTable[i+1])
3305            return i +1;
3306        }
3307        }
3308    }
3309
3310    /**
3311     * Remove insignificant trailing zeros from this
3312     * <tt>BigDecimal</tt> until the preferred scale is reached or no
3313     * more zeros can be removed. If the preferred scale is less than
3314     * Integer.MIN_VALUE, all the trailing zeros will be removed.
3315     *
3316     * <tt>BigInteger</tt> assistance could help, here?
3317     *
3318     * <p>WARNING: This method should only be called on new objects as
3319     * it mutates the value fields.
3320     *
3321     * @return this <tt>BigDecimal</tt> with a scale possibly reduced
3322     * to be closed to the preferred scale.
3323     */

3324    private BigDecimal JavaDoc stripZerosToMatchScale(long preferredScale) {
3325    boolean compact = (intCompact != INFLATED);
3326    this.inflate();
3327        BigInteger JavaDoc qr[]; // quotient-remainder pair
3328
while ( intVal.abs().compareTo(BigInteger.TEN) >= 0 &&
3329        scale > preferredScale) {
3330            if (intVal.testBit(0))
3331                break; // odd number cannot end in 0
3332
qr = intVal.divideAndRemainder(BigInteger.TEN);
3333            if (qr[1].signum() != 0)
3334                break; // non-0 remainder
3335
intVal=qr[0];
3336            scale = checkScale((long)scale-1); // could Overflow
3337
if (precision > 0) // adjust precision if known
3338
precision--;
3339        }
3340    if (compact)
3341        intCompact = intVal.longValue();
3342        return this;
3343    }
3344
3345    /**
3346     * Check a scale for Underflow or Overflow. If this BigDecimal is
3347     * uninitialized or initialized and nonzero, throw an exception if
3348     * the scale is out of range. If this is zero, saturate the scale
3349     * to the extreme value of the right sign if the scale is out of
3350     * range.
3351     *
3352     * @param val The new scale.
3353     * @throws ArithmeticException (overflow or underflow) if the new
3354     * scale is out of range.
3355     * @return validated scale as an int.
3356     */

3357    private int checkScale(long val) {
3358        if ((int)val != val) {
3359        if ((this.intCompact != INFLATED && this.intCompact != 0) ||
3360        (this.intVal != null && this.signum() != 0) ||
3361        (this.intVal == null && this.intCompact == INFLATED) ) {
3362        if (val > Integer.MAX_VALUE)
3363            throw new ArithmeticException JavaDoc("Underflow");
3364        if (val < Integer.MIN_VALUE)
3365            throw new ArithmeticException JavaDoc("Overflow");
3366        } else {
3367        return (val > Integer.MAX_VALUE)?Integer.MAX_VALUE:Integer.MIN_VALUE;
3368        }
3369        }
3370        return (int)val;
3371    }
3372
3373    /**
3374     * Round an operand; used only if digits &gt; 0. Does not change
3375     * <tt>this</tt>; if rounding is needed a new <tt>BigDecimal</tt>
3376     * is created and returned.
3377     *
3378     * @param mc the context to use.
3379     * @throws ArithmeticException if the result is inexact but the
3380     * rounding mode is <tt>UNNECESSARY</tt>.
3381     */

3382    private BigDecimal JavaDoc roundOp(MathContext JavaDoc mc) {
3383        BigDecimal JavaDoc rounded = doRound(mc);
3384        return rounded;
3385    }
3386
3387    /** Round this BigDecimal according to the MathContext settings;
3388     * used only if precision &gt; 0.
3389     *
3390     * <p>WARNING: This method should only be called on new objects as
3391     * it mutates the value fields.
3392     *
3393     * @param mc the context to use.
3394     * @throws ArithmeticException if the rounding mode is
3395     * <tt>RoundingMode.UNNECESSARY</tt> and the
3396     * <tt>BigDecimal</tt> operation would require rounding.
3397     */

3398    private void roundThis(MathContext JavaDoc mc) {
3399        BigDecimal JavaDoc rounded = doRound(mc);
3400        if (rounded == this) // wasn't rounded
3401
return;
3402        this.intVal = rounded.intVal;
3403        this.intCompact = rounded.intCompact;
3404        this.scale = rounded.scale;
3405        this.precision = rounded.precision;
3406    }
3407
3408    /**
3409     * Returns a <tt>BigDecimal</tt> rounded according to the
3410     * MathContext settings; used only if <tt>mc.precision&gt;0</tt>.
3411     * Does not change <tt>this</tt>; if rounding is needed a new
3412     * <tt>BigDecimal</tt> is created and returned.
3413     *
3414     * @param mc the context to use.
3415     * @return a <tt>BigDecimal</tt> rounded according to the MathContext
3416     * settings. May return this, if no rounding needed.
3417     * @throws ArithmeticException if the rounding mode is
3418     * <tt>RoundingMode.UNNECESSARY</tt> and the
3419     * result is inexact.
3420     */

3421    private BigDecimal JavaDoc doRound(MathContext JavaDoc mc) {
3422    this.inflate();
3423        if (precision == 0) {
3424            if (mc.roundingMax != null
3425                && intVal.compareTo(mc.roundingMax) < 0
3426                && intVal.compareTo(mc.roundingMin) > 0)
3427                return this; // no rounding needed
3428
precision(); // find it
3429
}
3430        int drop = precision - mc.precision; // digits to discard
3431
if (drop <= 0) // we fit
3432
return this;
3433        BigDecimal JavaDoc rounded = dropDigits(mc, drop);
3434        // we need to double-check, in case of the 999=>1000 case
3435
return rounded.doRound(mc);
3436    }
3437
3438    /**
3439     * Removes digits from the significand of a <tt>BigDecimal</tt>,
3440     * rounding according to the MathContext settings. Does not
3441     * change <tt>this</tt>; a new <tt>BigDecimal</tt> is always
3442     * created and returned.
3443     *
3444     * <p>Actual rounding is carried out, as before, by the divide
3445     * method, as this minimized code changes. It might be more
3446     * efficient in most cases to move rounding to here, so we can do
3447     * a round-to-length rather than round-to-scale.
3448     *
3449     * @param mc the context to use.
3450     * @param drop the number of digits to drop, must be &gt; 0
3451     * @return a <tt>BigDecimal</tt> rounded according to the MathContext
3452     * settings. May return <tt>this</tt>, if no rounding needed.
3453     * @throws ArithmeticException if the rounding mode is
3454     * <tt>RoundingMode.UNNECESSARY</tt> and the
3455     * result is inexact.
3456     */

3457    private BigDecimal JavaDoc dropDigits(MathContext JavaDoc mc, int drop) {
3458        // here if we need to round; make the divisor = 10**drop)
3459
// [calculating the BigInteger here saves setScale later]
3460
BigDecimal JavaDoc divisor = new BigDecimal JavaDoc(tenToThe(drop), 0);
3461
3462        // divide to same scale to force round to length
3463
BigDecimal JavaDoc rounded = this.divide(divisor, scale,
3464                     mc.roundingMode.oldMode);
3465        rounded.scale = checkScale((long)rounded.scale - drop ); // adjust the scale
3466
return rounded;
3467    }
3468
3469    private static int longCompareTo(long x, long y) {
3470    return (x < y) ? -1 : (x == y) ? 0 : 1;
3471    }
3472
3473    /*
3474     * Internal printing routine
3475     */

3476    private static void print(String JavaDoc name, BigDecimal JavaDoc bd) {
3477    System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
3478              name,
3479              bd.intCompact,
3480              bd.intVal,
3481              bd.scale,
3482              bd.precision);
3483    }
3484
3485    /**
3486     * Check internal invariants of this BigDecimal. These invariants
3487     * include:
3488     *
3489     * <ul>
3490     *
3491     * <li>The object must be initialized; either intCompact must not be
3492     * INFLATED or intVal is non-null. Both of these conditions may
3493     * be true.
3494     *
3495     * <li>If both intCompact and intVal and set, their values must be
3496     * consistent.
3497     *
3498     * <li>If precision is nonzero, it must have the right value.
3499     * </ul>
3500     */

3501    private BigDecimal JavaDoc audit() {
3502    // Check precision
3503
if (precision > 0) {
3504        if (precision != digitLength()) {
3505        print("audit", this);
3506        throw new AssertionError JavaDoc("precision mismatch");
3507        }
3508    }
3509
3510    if (intCompact == INFLATED) {
3511        if (intVal == null) {
3512        print("audit", this);
3513        throw new AssertionError JavaDoc("null intVal");
3514        }
3515    } else {
3516        if (intVal != null) {
3517        long val = intVal.longValue();
3518        if (val != intCompact) {
3519            print("audit", this);
3520            throw new AssertionError JavaDoc("Inconsistent state, intCompact=" +
3521                         intCompact + "\t intVal=" + val);
3522        }
3523        }
3524    }
3525    return this;
3526    }
3527}
3528
Popular Tags