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>.