1 /*
   2  * Portions Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 /*
  27  * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
  28  */
  29 
  30 package java.math;
  31 
  32 import java.util.Arrays;
  33 import static java.math.BigInteger.LONG_MASK;
  34 
  35 /**
  36  * Immutable, arbitrary-precision signed decimal numbers.  A
  37  * {@code BigDecimal} consists of an arbitrary precision integer
  38  * <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  If zero
  39  * or positive, the scale is the number of digits to the right of the
  40  * decimal point.  If negative, the unscaled value of the number is
  41  * multiplied by ten to the power of the negation of the scale.  The
  42  * value of the number represented by the {@code BigDecimal} is
  43  * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
  44  *
  45  * <p>The {@code BigDecimal} class provides operations for
  46  * arithmetic, scale manipulation, rounding, comparison, hashing, and
  47  * format conversion.  The {@link #toString} method provides a
  48  * canonical representation of a {@code BigDecimal}.
  49  *
  50  * <p>The {@code BigDecimal} class gives its user complete control
  51  * over rounding behavior.  If no rounding mode is specified and the
  52  * exact result cannot be represented, an exception is thrown;
  53  * otherwise, calculations can be carried out to a chosen precision
  54  * and rounding mode by supplying an appropriate {@link MathContext}
  55  * object to the operation.  In either case, eight <em>rounding
  56  * modes</em> are provided for the control of rounding.  Using the
  57  * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
  58  * represent rounding mode is largely obsolete; the enumeration values
  59  * of the {@code RoundingMode} {@code enum}, (such as {@link
  60  * RoundingMode#HALF_UP}) should be used instead.
  61  *
  62  * <p>When a {@code MathContext} object is supplied with a precision
  63  * setting of 0 (for example, {@link MathContext#UNLIMITED}),
  64  * arithmetic operations are exact, as are the arithmetic methods
  65  * which take no {@code MathContext} object.  (This is the only
  66  * behavior that was supported in releases prior to 5.)  As a
  67  * corollary of computing the exact result, the rounding mode setting
  68  * of a {@code MathContext} object with a precision setting of 0 is
  69  * not used and thus irrelevant.  In the case of divide, the exact
  70  * quotient could have an infinitely long decimal expansion; for
  71  * example, 1 divided by 3.  If the quotient has a nonterminating
  72  * decimal expansion and the operation is specified to return an exact
  73  * result, an {@code ArithmeticException} is thrown.  Otherwise, the
  74  * exact result of the division is returned, as done for other
  75  * operations.
  76  *
  77  * <p>When the precision setting is not 0, the rules of
  78  * {@code BigDecimal} arithmetic are broadly compatible with selected
  79  * modes of operation of the arithmetic defined in ANSI X3.274-1996
  80  * and ANSI X3.274-1996/AM 1-2000 (section 7.4).  Unlike those
  81  * standards, {@code BigDecimal} includes many rounding modes, which
  82  * were mandatory for division in {@code BigDecimal} releases prior
  83  * to 5.  Any conflicts between these ANSI standards and the
  84  * {@code BigDecimal} specification are resolved in favor of
  85  * {@code BigDecimal}.
  86  *
  87  * <p>Since the same numerical value can have different
  88  * representations (with different scales), the rules of arithmetic
  89  * and rounding must specify both the numerical result and the scale
  90  * used in the result's representation.
  91  *
  92  *
  93  * <p>In general the rounding modes and precision setting determine
  94  * how operations return results with a limited number of digits when
  95  * the exact result has more digits (perhaps infinitely many in the
  96  * case of division) than the number of digits returned.
  97  *
  98  * First, the
  99  * total number of digits to return is specified by the
 100  * {@code MathContext}'s {@code precision} setting; this determines
 101  * the result's <i>precision</i>.  The digit count starts from the
 102  * leftmost nonzero digit of the exact result.  The rounding mode
 103  * determines how any discarded trailing digits affect the returned
 104  * result.
 105  *
 106  * <p>For all arithmetic operators , the operation is carried out as
 107  * though an exact intermediate result were first calculated and then
 108  * rounded to the number of digits specified by the precision setting
 109  * (if necessary), using the selected rounding mode.  If the exact
 110  * result is not returned, some digit positions of the exact result
 111  * are discarded.  When rounding increases the magnitude of the
 112  * returned result, it is possible for a new digit position to be
 113  * created by a carry propagating to a leading {@literal "9"} digit.
 114  * For example, rounding the value 999.9 to three digits rounding up
 115  * would be numerically equal to one thousand, represented as
 116  * 100&times;10<sup>1</sup>.  In such cases, the new {@literal "1"} is
 117  * the leading digit position of the returned result.
 118  *
 119  * <p>Besides a logical exact result, each arithmetic operation has a
 120  * preferred scale for representing a result.  The preferred
 121  * scale for each operation is listed in the table below.
 122  *
 123  * <table border>
 124  * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
 125  * </h3></caption>
 126  * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
 127  * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
 128  * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
 129  * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
 130  * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
 131  * </table>
 132  *
 133  * These scales are the ones used by the methods which return exact
 134  * arithmetic results; except that an exact divide may have to use a
 135  * larger scale since the exact result may have more digits.  For
 136  * example, {@code 1/32} is {@code 0.03125}.
 137  *
 138  * <p>Before rounding, the scale of the logical exact intermediate
 139  * result is the preferred scale for that operation.  If the exact
 140  * numerical result cannot be represented in {@code precision}
 141  * digits, rounding selects the set of digits to return and the scale
 142  * of the result is reduced from the scale of the intermediate result
 143  * to the least scale which can represent the {@code precision}
 144  * digits actually returned.  If the exact result can be represented
 145  * with at most {@code precision} digits, the representation
 146  * of the result with the scale closest to the preferred scale is
 147  * returned.  In particular, an exactly representable quotient may be
 148  * represented in fewer than {@code precision} digits by removing
 149  * trailing zeros and decreasing the scale.  For example, rounding to
 150  * three digits using the {@linkplain RoundingMode#FLOOR floor}
 151  * rounding mode, <br>
 152  *
 153  * {@code 19/100 = 0.19   // integer=19,  scale=2} <br>
 154  *
 155  * but<br>
 156  *
 157  * {@code 21/110 = 0.190  // integer=190, scale=3} <br>
 158  *
 159  * <p>Note that for add, subtract, and multiply, the reduction in
 160  * scale will equal the number of digit positions of the exact result
 161  * which are discarded. If the rounding causes a carry propagation to
 162  * create a new high-order digit position, an additional digit of the
 163  * result is discarded than when no new digit position is created.
 164  *
 165  * <p>Other methods may have slightly different rounding semantics.
 166  * For example, the result of the {@code pow} method using the
 167  * {@linkplain #pow(int, MathContext) specified algorithm} can
 168  * occasionally differ from the rounded mathematical result by more
 169  * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
 170  *
 171  * <p>Two types of operations are provided for manipulating the scale
 172  * of a {@code BigDecimal}: scaling/rounding operations and decimal
 173  * point motion operations.  Scaling/rounding operations ({@link
 174  * #setScale setScale} and {@link #round round}) return a
 175  * {@code BigDecimal} whose value is approximately (or exactly) equal
 176  * to that of the operand, but whose scale or precision is the
 177  * specified value; that is, they increase or decrease the precision
 178  * of the stored number with minimal effect on its value.  Decimal
 179  * point motion operations ({@link #movePointLeft movePointLeft} and
 180  * {@link #movePointRight movePointRight}) return a
 181  * {@code BigDecimal} created from the operand by moving the decimal
 182  * point a specified distance in the specified direction.
 183  *
 184  * <p>For the sake of brevity and clarity, pseudo-code is used
 185  * throughout the descriptions of {@code BigDecimal} methods.  The
 186  * pseudo-code expression {@code (i + j)} is shorthand for "a
 187  * {@code BigDecimal} whose value is that of the {@code BigDecimal}
 188  * {@code i} added to that of the {@code BigDecimal}
 189  * {@code j}." The pseudo-code expression {@code (i == j)} is
 190  * shorthand for "{@code true} if and only if the
 191  * {@code BigDecimal} {@code i} represents the same value as the
 192  * {@code BigDecimal} {@code j}." Other pseudo-code expressions
 193  * are interpreted similarly.  Square brackets are used to represent
 194  * the particular {@code BigInteger} and scale pair defining a
 195  * {@code BigDecimal} value; for example [19, 2] is the
 196  * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
 197  *
 198  * <p>Note: care should be exercised if {@code BigDecimal} objects
 199  * are used as keys in a {@link java.util.SortedMap SortedMap} or
 200  * elements in a {@link java.util.SortedSet SortedSet} since
 201  * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
 202  * with equals</i>.  See {@link Comparable}, {@link
 203  * java.util.SortedMap} or {@link java.util.SortedSet} for more
 204  * information.
 205  *
 206  * <p>All methods and constructors for this class throw
 207  * {@code NullPointerException} when passed a {@code null} object
 208  * reference for any input parameter.
 209  *
 210  * @see     BigInteger
 211  * @see     MathContext
 212  * @see     RoundingMode
 213  * @see     java.util.SortedMap
 214  * @see     java.util.SortedSet
 215  * @author  Josh Bloch
 216  * @author  Mike Cowlishaw
 217  * @author  Joseph D. Darcy
 218  */
 219 public class BigDecimal extends Number implements Comparable<BigDecimal> {
 220     /**
 221      * The unscaled value of this BigDecimal, as returned by {@link
 222      * #unscaledValue}.
 223      *
 224      * @serial
 225      * @see #unscaledValue
 226      */
 227     private volatile BigInteger intVal;
 228 
 229     /**
 230      * The scale of this BigDecimal, as returned by {@link #scale}.
 231      *
 232      * @serial
 233      * @see #scale
 234      */
 235     private int scale;  // Note: this may have any value, so
 236                         // calculations must be done in longs
 237     /**
 238      * The number of decimal digits in this BigDecimal, or 0 if the
 239      * number of digits are not known (lookaside information).  If
 240      * nonzero, the value is guaranteed correct.  Use the precision()
 241      * method to obtain and set the value if it might be 0.  This
 242      * field is mutable until set nonzero.
 243      *
 244      * @since  1.5
 245      */
 246     private transient int precision;
 247 
 248     /**
 249      * Used to store the canonical string representation, if computed.
 250      */
 251     private transient String stringCache;
 252 
 253     /**
 254      * Sentinel value for {@link #intCompact} indicating the
 255      * significand information is only available from {@code intVal}.
 256      */
 257     static final long INFLATED = Long.MIN_VALUE;
 258 
 259     /**
 260      * If the absolute value of the significand of this BigDecimal is
 261      * less than or equal to {@code Long.MAX_VALUE}, the value can be
 262      * compactly stored in this field and used in computations.
 263      */
 264     private transient long intCompact;
 265 
 266     // All 18-digit base ten strings fit into a long; not all 19-digit
 267     // strings will
 268     private static final int MAX_COMPACT_DIGITS = 18;
 269 
 270     private static final int MAX_BIGINT_BITS = 62;
 271 
 272     /* Appease the serialization gods */
 273     private static final long serialVersionUID = 6108874887143696463L;
 274 
 275     private static final ThreadLocal<StringBuilderHelper> 
 276         threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
 277         @Override
 278         protected StringBuilderHelper initialValue() {
 279             return new StringBuilderHelper();
 280         }
 281     };
 282     
 283     // Cache of common small BigDecimal values.
 284     private static final BigDecimal zeroThroughTen[] = { 
 285         new BigDecimal(BigInteger.ZERO,         0,  0, 1),
 286         new BigDecimal(BigInteger.ONE,          1,  0, 1),
 287         new BigDecimal(BigInteger.valueOf(2),   2,  0, 1),
 288         new BigDecimal(BigInteger.valueOf(3),   3,  0, 1),
 289         new BigDecimal(BigInteger.valueOf(4),   4,  0, 1),
 290         new BigDecimal(BigInteger.valueOf(5),   5,  0, 1),
 291         new BigDecimal(BigInteger.valueOf(6),   6,  0, 1),
 292         new BigDecimal(BigInteger.valueOf(7),   7,  0, 1),
 293         new BigDecimal(BigInteger.valueOf(8),   8,  0, 1),
 294         new BigDecimal(BigInteger.valueOf(9),   9,  0, 1),
 295         new BigDecimal(BigInteger.TEN,          10, 0, 2),
 296     };
 297 
 298     // Cache of zero scaled by 0 - 15
 299     private static final BigDecimal[] ZERO_SCALED_BY = {
 300         zeroThroughTen[0],
 301         new BigDecimal(BigInteger.ZERO, 0, 1, 1),
 302         new BigDecimal(BigInteger.ZERO, 0, 2, 1),
 303         new BigDecimal(BigInteger.ZERO, 0, 3, 1),
 304         new BigDecimal(BigInteger.ZERO, 0, 4, 1),
 305         new BigDecimal(BigInteger.ZERO, 0, 5, 1),
 306         new BigDecimal(BigInteger.ZERO, 0, 6, 1),
 307         new BigDecimal(BigInteger.ZERO, 0, 7, 1),
 308         new BigDecimal(BigInteger.ZERO, 0, 8, 1),
 309         new BigDecimal(BigInteger.ZERO, 0, 9, 1),
 310         new BigDecimal(BigInteger.ZERO, 0, 10, 1),
 311         new BigDecimal(BigInteger.ZERO, 0, 11, 1),
 312         new BigDecimal(BigInteger.ZERO, 0, 12, 1),
 313         new BigDecimal(BigInteger.ZERO, 0, 13, 1),
 314         new BigDecimal(BigInteger.ZERO, 0, 14, 1),
 315         new BigDecimal(BigInteger.ZERO, 0, 15, 1),
 316     };
 317     
 318     // Constants
 319     /**
 320      * The value 0, with a scale of 0.
 321      *
 322      * @since  1.5
 323      */
 324     public static final BigDecimal ZERO =
 325         zeroThroughTen[0];
 326 
 327     /**
 328      * The value 1, with a scale of 0.
 329      *
 330      * @since  1.5
 331      */
 332     public static final BigDecimal ONE =
 333         zeroThroughTen[1];
 334 
 335     /**
 336      * The value 10, with a scale of 0.
 337      *
 338      * @since  1.5
 339      */
 340     public static final BigDecimal TEN =
 341         zeroThroughTen[10];
 342 
 343     // Constructors
 344 
 345     /**
 346      * Trusted package private constructor.
 347      * Trusted simply means if val is INFLATED, intVal could not be null and
 348      * if intVal is null, val could not be INFLATED.
 349      */
 350     BigDecimal(BigInteger intVal, long val, int scale, int prec) {
 351         this.scale = scale;
 352         this.precision = prec;
 353         this.intCompact = val;
 354         this.intVal = intVal;
 355     }
 356     
 357     /**
 358      * Translates a character array representation of a
 359      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 360      * same sequence of characters as the {@link #BigDecimal(String)}
 361      * constructor, while allowing a sub-array to be specified.
 362      * 
 363      * <p>Note that if the sequence of characters is already available
 364      * within a character array, using this constructor is faster than
 365      * converting the {@code char} array to string and using the
 366      * {@code BigDecimal(String)} constructor .
 367      *
 368      * @param  in {@code char} array that is the source of characters.
 369      * @param  offset first character in the array to inspect.
 370      * @param  len number of characters to consider.
 371      * @throws NumberFormatException if {@code in} is not a valid
 372      *         representation of a {@code BigDecimal} or the defined subarray
 373      *         is not wholly within {@code in}.
 374      * @since  1.5
 375      */
 376     public BigDecimal(char[] in, int offset, int len) {
 377         // protect against huge length.
 378         if (offset+len > in.length || offset < 0)
 379             throw new NumberFormatException();
 380         // This is the primary string to BigDecimal constructor; all
 381         // incoming strings end up here; it uses explicit (inline)
 382         // parsing for speed and generates at most one intermediate
 383         // (temporary) object (a char[] array) for non-compact case.
 384 
 385         // Use locals for all fields values until completion
 386         int prec = 0;                 // record precision value
 387         int scl = 0;                  // record scale value
 388         long rs = 0;                  // the compact value in long
 389         BigInteger rb = null;         // the inflated value in BigInteger
 390         
 391         // use array bounds checking to handle too-long, len == 0,
 392         // bad offset, etc.
 393         try {
 394             // handle the sign
 395             boolean isneg = false;          // assume positive
 396             if (in[offset] == '-') {
 397                 isneg = true;               // leading minus means negative
 398                 offset++;
 399                 len--;
 400             } else if (in[offset] == '+') { // leading + allowed
 401                 offset++;
 402                 len--;
 403             }
 404 
 405             // should now be at numeric part of the significand
 406             boolean dot = false;             // true when there is a '.'
 407             int cfirst = offset;             // record start of integer
 408             long exp = 0;                    // exponent
 409             char c;                          // current character
 410     
 411             boolean isCompact = (len <= MAX_COMPACT_DIGITS);
 412             // integer significand array & idx is the index to it. The array
 413             // is ONLY used when we can't use a compact representation.
 414             char coeff[] = isCompact ? null : new char[len];             
 415             int idx = 0;                     
 416 
 417             for (; len > 0; offset++, len--) {
 418                 c = in[offset];
 419                 // have digit
 420                 if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
 421                     // First compact case, we need not to preserve the character
 422                     // and we can just compute the value in place.
 423                     if (isCompact) {
 424                         int digit = Character.digit(c, 10);
 425                         if (digit == 0) {
 426                             if (prec == 0)
 427                                 prec = 1;
 428                             else if (rs != 0) {
 429                                 rs *= 10;
 430                                 ++prec;
 431                             } // else digit is a redundant leading zero
 432                         } else {
 433                             if (prec != 1 || rs != 0)
 434                                 ++prec; // prec unchanged if preceded by 0s
 435                             rs = rs * 10 + digit;
 436                         }
 437                     } else { // the unscaled value is likely a BigInteger object.
 438                         if (c == '0' || Character.digit(c, 10) == 0) {
 439                             if (prec == 0) {
 440                                 coeff[idx] = c;
 441                                 prec = 1;
 442                             } else if (idx != 0) {
 443                                 coeff[idx++] = c;
 444                                 ++prec;
 445                             } // else c must be a redundant leading zero
 446                         } else {
 447                             if (prec != 1 || idx != 0)
 448                                 ++prec; // prec unchanged if preceded by 0s
 449                             coeff[idx++] = c;
 450                         }
 451                     }
 452                     if (dot)
 453                         ++scl;
 454                     continue;
 455                 }
 456                 // have dot
 457                 if (c == '.') {
 458                     // have dot
 459                     if (dot)         // two dots
 460                         throw new NumberFormatException();
 461                     dot = true;
 462                     continue;
 463                 }
 464                 // exponent expected
 465                 if ((c != 'e') && (c != 'E'))
 466                     throw new NumberFormatException();
 467                 offset++;
 468                 c = in[offset];
 469                 len--;
 470                 boolean negexp = (c == '-');
 471                 // optional sign
 472                 if (negexp || c == '+') {
 473                     offset++;
 474                     c = in[offset];
 475                     len--;
 476                 }
 477                 if (len <= 0)    // no exponent digits
 478                     throw new NumberFormatException();
 479                 // skip leading zeros in the exponent 
 480                 while (len > 10 && Character.digit(c, 10) == 0) {
 481                     offset++;
 482                     c = in[offset];
 483                     len--;
 484                 }
 485                 if (len > 10)  // too many nonzero exponent digits
 486                     throw new NumberFormatException();
 487                 // c now holds first digit of exponent
 488                 for (;; len--) {
 489                     int v;
 490                     if (c >= '0' && c <= '9') {
 491                         v = c - '0';
 492                     } else {
 493                         v = Character.digit(c, 10);
 494                         if (v < 0)            // not a digit
 495                             throw new NumberFormatException();
 496                     }
 497                     exp = exp * 10 + v;
 498                     if (len == 1)
 499                         break;               // that was final character
 500                     offset++;
 501                     c = in[offset];
 502                 }
 503                 if (negexp)                  // apply sign
 504                     exp = -exp;
 505                 // Next test is required for backwards compatibility
 506                 if ((int)exp != exp)         // overflow
 507                     throw new NumberFormatException();
 508                 break;                       // [saves a test]
 509             }
 510             // here when no characters left
 511             if (prec == 0)              // no digits found
 512                 throw new NumberFormatException();
 513 
 514             // Adjust scale if exp is not zero.
 515             if (exp != 0) {                  // had significant exponent
 516                 // Can't call checkScale which relies on proper fields value
 517                 long adjustedScale = scl - exp;
 518                 if (adjustedScale > Integer.MAX_VALUE ||
 519                     adjustedScale < Integer.MIN_VALUE)
 520                     throw new NumberFormatException("Scale out of range.");
 521                 scl = (int)adjustedScale;
 522             }
 523 
 524             // Remove leading zeros from precision (digits count)
 525             if (isCompact) {
 526                 rs = isneg ? -rs : rs;
 527             } else {
 528                 char quick[];
 529                 if (!isneg) {
 530                     quick = (coeff.length != prec) ?
 531                         Arrays.copyOf(coeff, prec) : coeff;
 532                 } else {
 533                     quick = new char[prec + 1];
 534                     quick[0] = '-';
 535                     System.arraycopy(coeff, 0, quick, 1, prec);
 536                 }                
 537                 rb = new BigInteger(quick);
 538                 rs = compactValFor(rb);
 539             }
 540         } catch (ArrayIndexOutOfBoundsException e) {
 541             throw new NumberFormatException();
 542         } catch (NegativeArraySizeException e) {
 543             throw new NumberFormatException();
 544         }
 545         this.scale = scl;
 546         this.precision = prec;
 547         this.intCompact = rs;
 548         this.intVal = rb;
 549     }
 550 
 551     /**
 552      * Translates a character array representation of a
 553      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 554      * same sequence of characters as the {@link #BigDecimal(String)}
 555      * constructor, while allowing a sub-array to be specified and
 556      * with rounding according to the context settings.
 557      *
 558      * <p>Note that if the sequence of characters is already available
 559      * within a character array, using this constructor is faster than
 560      * converting the {@code char} array to string and using the
 561      * {@code BigDecimal(String)} constructor .
 562      *
 563      * @param  in {@code char} array that is the source of characters.
 564      * @param  offset first character in the array to inspect.
 565      * @param  len number of characters to consider..
 566      * @param  mc the context to use.
 567      * @throws ArithmeticException if the result is inexact but the
 568      *         rounding mode is {@code UNNECESSARY}.
 569      * @throws NumberFormatException if {@code in} is not a valid
 570      *         representation of a {@code BigDecimal} or the defined subarray
 571      *         is not wholly within {@code in}.
 572      * @since  1.5
 573      */
 574     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
 575         this(in, offset, len);
 576         if (mc.precision > 0)
 577             roundThis(mc);
 578     }
 579 
 580     /**
 581      * Translates a character array representation of a
 582      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 583      * same sequence of characters as the {@link #BigDecimal(String)}
 584      * constructor.
 585      *
 586      * <p>Note that if the sequence of characters is already available
 587      * as a character array, using this constructor is faster than
 588      * converting the {@code char} array to string and using the
 589      * {@code BigDecimal(String)} constructor .
 590      *
 591      * @param in {@code char} array that is the source of characters.
 592      * @throws NumberFormatException if {@code in} is not a valid
 593      *         representation of a {@code BigDecimal}.
 594      * @since  1.5
 595      */
 596     public BigDecimal(char[] in) {
 597         this(in, 0, in.length);
 598     }
 599 
 600     /**
 601      * Translates a character array representation of a
 602      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 603      * same sequence of characters as the {@link #BigDecimal(String)}
 604      * constructor and with rounding according to the context
 605      * settings.
 606      *
 607      * <p>Note that if the sequence of characters is already available
 608      * as a character array, using this constructor is faster than
 609      * converting the {@code char} array to string and using the
 610      * {@code BigDecimal(String)} constructor .
 611      *
 612      * @param  in {@code char} array that is the source of characters.
 613      * @param  mc the context to use.
 614      * @throws ArithmeticException if the result is inexact but the
 615      *         rounding mode is {@code UNNECESSARY}.
 616      * @throws NumberFormatException if {@code in} is not a valid
 617      *         representation of a {@code BigDecimal}.
 618      * @since  1.5
 619      */
 620     public BigDecimal(char[] in, MathContext mc) {
 621         this(in, 0, in.length, mc);
 622     }
 623 
 624     /**
 625      * Translates the string representation of a {@code BigDecimal}
 626      * into a {@code BigDecimal}.  The string representation consists
 627      * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
 628      * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
 629      * zero or more decimal digits ("the integer"), optionally
 630      * followed by a fraction, optionally followed by an exponent.
 631      *
 632      * <p>The fraction consists of a decimal point followed by zero
 633      * or more decimal digits.  The string must contain at least one
 634      * digit in either the integer or the fraction.  The number formed
 635      * by the sign, the integer and the fraction is referred to as the
 636      * <i>significand</i>.
 637      *
 638      * <p>The exponent consists of the character {@code 'e'}
 639      * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
 640      * followed by one or more decimal digits.  The value of the
 641      * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
 642      * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
 643      *
 644      * <p>More formally, the strings this constructor accepts are
 645      * described by the following grammar:
 646      * <blockquote>
 647      * <dl>
 648      * <dt><i>BigDecimalString:</i>
 649      * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
 650      * <p>
 651      * <dt><i>Sign:</i>
 652      * <dd>{@code +}
 653      * <dd>{@code -}
 654      * <p>
 655      * <dt><i>Significand:</i>
 656      * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
 657      * <dd>{@code .} <i>FractionPart</i>
 658      * <dd><i>IntegerPart</i>
 659      * <p>
 660      * <dt><i>IntegerPart:
 661      * <dd>Digits</i>
 662      * <p>
 663      * <dt><i>FractionPart:
 664      * <dd>Digits</i>
 665      * <p>
 666      * <dt><i>Exponent:
 667      * <dd>ExponentIndicator SignedInteger</i>
 668      * <p>
 669      * <dt><i>ExponentIndicator:</i>
 670      * <dd>{@code e}
 671      * <dd>{@code E}
 672      * <p>
 673      * <dt><i>SignedInteger:
 674      * <dd>Sign<sub>opt</sub> Digits</i>
 675      * <p>
 676      * <dt><i>Digits:
 677      * <dd>Digit
 678      * <dd>Digits Digit</i>
 679      * <p>
 680      * <dt><i>Digit:</i>
 681      * <dd>any character for which {@link Character#isDigit}
 682      * returns {@code true}, including 0, 1, 2 ...
 683      * </dl>
 684      * </blockquote>
 685      *
 686      * <p>The scale of the returned {@code BigDecimal} will be the
 687      * number of digits in the fraction, or zero if the string
 688      * contains no decimal point, subject to adjustment for any
 689      * exponent; if the string contains an exponent, the exponent is
 690      * subtracted from the scale.  The value of the resulting scale
 691      * must lie between {@code Integer.MIN_VALUE} and
 692      * {@code Integer.MAX_VALUE}, inclusive.
 693      *
 694      * <p>The character-to-digit mapping is provided by {@link
 695      * java.lang.Character#digit} set to convert to radix 10.  The
 696      * String may not contain any extraneous characters (whitespace,
 697      * for example).
 698      *
 699      * <p><b>Examples:</b><br>
 700      * The value of the returned {@code BigDecimal} is equal to
 701      * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
 702      * For each string on the left, the resulting representation
 703      * [{@code BigInteger}, {@code scale}] is shown on the right.
 704      * <pre>
 705      * "0"            [0,0]
 706      * "0.00"         [0,2]
 707      * "123"          [123,0]
 708      * "-123"         [-123,0]
 709      * "1.23E3"       [123,-1]
 710      * "1.23E+3"      [123,-1]
 711      * "12.3E+7"      [123,-6]
 712      * "12.0"         [120,1]
 713      * "12.3"         [123,1]
 714      * "0.00123"      [123,5]
 715      * "-1.23E-12"    [-123,14]
 716      * "1234.5E-4"    [12345,5]
 717      * "0E+7"         [0,-7]
 718      * "-0"           [0,0]
 719      * </pre>
 720      *
 721      * <p>Note: For values other than {@code float} and
 722      * {@code double} NaN and &plusmn;Infinity, this constructor is
 723      * compatible with the values returned by {@link Float#toString}
 724      * and {@link Double#toString}.  This is generally the preferred
 725      * way to convert a {@code float} or {@code double} into a
 726      * BigDecimal, as it doesn't suffer from the unpredictability of
 727      * the {@link #BigDecimal(double)} constructor.
 728      *
 729      * @param val String representation of {@code BigDecimal}.
 730      *
 731      * @throws NumberFormatException if {@code val} is not a valid
 732      *         representation of a {@code BigDecimal}.
 733      */
 734     public BigDecimal(String val) {
 735         this(val.toCharArray(), 0, val.length());
 736     }
 737 
 738     /**
 739      * Translates the string representation of a {@code BigDecimal}
 740      * into a {@code BigDecimal}, accepting the same strings as the
 741      * {@link #BigDecimal(String)} constructor, with rounding
 742      * according to the context settings.
 743      *
 744      * @param  val string representation of a {@code BigDecimal}.
 745      * @param  mc the context to use.
 746      * @throws ArithmeticException if the result is inexact but the
 747      *         rounding mode is {@code UNNECESSARY}.
 748      * @throws NumberFormatException if {@code val} is not a valid
 749      *         representation of a BigDecimal.
 750      * @since  1.5
 751      */
 752     public BigDecimal(String val, MathContext mc) {
 753         this(val.toCharArray(), 0, val.length());
 754         if (mc.precision > 0)
 755             roundThis(mc);
 756     }
 757 
 758     /**
 759      * Translates a {@code double} into a {@code BigDecimal} which
 760      * is the exact decimal representation of the {@code double}'s
 761      * binary floating-point value.  The scale of the returned
 762      * {@code BigDecimal} is the smallest value such that
 763      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 764      * <p>
 765      * <b>Notes:</b>
 766      * <ol>
 767      * <li>
 768      * The results of this constructor can be somewhat unpredictable.
 769      * One might assume that writing {@code new BigDecimal(0.1)} in
 770      * Java creates a {@code BigDecimal} which is exactly equal to
 771      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
 772      * actually equal to
 773      * 0.1000000000000000055511151231257827021181583404541015625.
 774      * This is because 0.1 cannot be represented exactly as a
 775      * {@code double} (or, for that matter, as a binary fraction of
 776      * any finite length).  Thus, the value that is being passed
 777      * <i>in</i> to the constructor is not exactly equal to 0.1,
 778      * appearances notwithstanding.
 779      *
 780      * <li>
 781      * The {@code String} constructor, on the other hand, is
 782      * perfectly predictable: writing {@code new BigDecimal("0.1")}
 783      * creates a {@code BigDecimal} which is <i>exactly</i> equal to
 784      * 0.1, as one would expect.  Therefore, it is generally
 785      * recommended that the {@linkplain #BigDecimal(String)
 786      * <tt>String</tt> constructor} be used in preference to this one.
 787      *
 788      * <li>
 789      * When a {@code double} must be used as a source for a
 790      * {@code BigDecimal}, note that this constructor provides an
 791      * exact conversion; it does not give the same result as
 792      * converting the {@code double} to a {@code String} using the
 793      * {@link Double#toString(double)} method and then using the
 794      * {@link #BigDecimal(String)} constructor.  To get that result,
 795      * use the {@code static} {@link #valueOf(double)} method.
 796      * </ol>
 797      *
 798      * @param val {@code double} value to be converted to
 799      *        {@code BigDecimal}.
 800      * @throws NumberFormatException if {@code val} is infinite or NaN.
 801      */
 802     public BigDecimal(double val) {
 803         if (Double.isInfinite(val) || Double.isNaN(val))
 804             throw new NumberFormatException("Infinite or NaN");
 805 
 806         // Translate the double into sign, exponent and significand, according
 807         // to the formulae in JLS, Section 20.10.22.
 808         long valBits = Double.doubleToLongBits(val);
 809         int sign = ((valBits >> 63)==0 ? 1 : -1);
 810         int exponent = (int) ((valBits >> 52) & 0x7ffL);
 811         long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
 812                             : (valBits & ((1L<<52) - 1)) | (1L<<52));
 813         exponent -= 1075;
 814         // At this point, val == sign * significand * 2**exponent.
 815 
 816         /*
 817          * Special case zero to supress nonterminating normalization
 818          * and bogus scale calculation.
 819          */
 820         if (significand == 0) {
 821             intVal = BigInteger.ZERO;
 822             intCompact = 0;
 823             precision = 1;
 824             return;
 825         }
 826 
 827         // Normalize
 828         while((significand & 1) == 0) {    //  i.e., significand is even
 829             significand >>= 1;
 830             exponent++;
 831         }
 832 
 833         // Calculate intVal and scale
 834         intVal = BigInteger.valueOf(sign*significand);
 835         if (exponent < 0) {
 836             intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
 837             scale = -exponent;
 838         } else if (exponent > 0) {
 839             intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
 840         }
 841         intCompact = compactValFor(intVal);
 842     }
 843 
 844     /**
 845      * Translates a {@code double} into a {@code BigDecimal}, with
 846      * rounding according to the context settings.  The scale of the
 847      * {@code BigDecimal} is the smallest value such that
 848      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 849      *
 850      * <p>The results of this constructor can be somewhat unpredictable
 851      * and its use is generally not recommended; see the notes under
 852      * the {@link #BigDecimal(double)} constructor.
 853      *
 854      * @param  val {@code double} value to be converted to
 855      *         {@code BigDecimal}.
 856      * @param  mc the context to use.
 857      * @throws ArithmeticException if the result is inexact but the
 858      *         RoundingMode is UNNECESSARY.
 859      * @throws NumberFormatException if {@code val} is infinite or NaN.
 860      * @since  1.5
 861      */
 862     public BigDecimal(double val, MathContext mc) {
 863         this(val);
 864         if (mc.precision > 0)
 865             roundThis(mc);
 866     }
 867 
 868     /**
 869      * Translates a {@code BigInteger} into a {@code BigDecimal}.
 870      * The scale of the {@code BigDecimal} is zero.
 871      *
 872      * @param val {@code BigInteger} value to be converted to
 873      *            {@code BigDecimal}.
 874      */
 875     public BigDecimal(BigInteger val) {
 876         intVal = val;
 877         intCompact = compactValFor(val);
 878     }
 879 
 880     /**
 881      * Translates a {@code BigInteger} into a {@code BigDecimal}
 882      * rounding according to the context settings.  The scale of the
 883      * {@code BigDecimal} is zero.
 884      *
 885      * @param val {@code BigInteger} value to be converted to
 886      *            {@code BigDecimal}.
 887      * @param  mc the context to use.
 888      * @throws ArithmeticException if the result is inexact but the
 889      *         rounding mode is {@code UNNECESSARY}.
 890      * @since  1.5
 891      */
 892     public BigDecimal(BigInteger val, MathContext mc) {
 893         this(val);
 894         if (mc.precision > 0)
 895             roundThis(mc);
 896     }
 897 
 898     /**
 899      * Translates a {@code BigInteger} unscaled value and an
 900      * {@code int} scale into a {@code BigDecimal}.  The value of
 901      * the {@code BigDecimal} is
 902      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
 903      *
 904      * @param unscaledVal unscaled value of the {@code BigDecimal}.
 905      * @param scale scale of the {@code BigDecimal}.
 906      */
 907     public BigDecimal(BigInteger unscaledVal, int scale) {
 908         // Negative scales are now allowed
 909         this(unscaledVal);
 910         this.scale = scale;
 911     }
 912 
 913     /**
 914      * Translates a {@code BigInteger} unscaled value and an
 915      * {@code int} scale into a {@code BigDecimal}, with rounding
 916      * according to the context settings.  The value of the
 917      * {@code BigDecimal} is <tt>(unscaledVal &times;
 918      * 10<sup>-scale</sup>)</tt>, rounded according to the
 919      * {@code precision} and rounding mode settings.
 920      *
 921      * @param  unscaledVal unscaled value of the {@code BigDecimal}.
 922      * @param  scale scale of the {@code BigDecimal}.
 923      * @param  mc the context to use.
 924      * @throws ArithmeticException if the result is inexact but the
 925      *         rounding mode is {@code UNNECESSARY}.
 926      * @since  1.5
 927      */
 928     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
 929         this(unscaledVal);
 930         this.scale = scale;
 931         if (mc.precision > 0)
 932             roundThis(mc);
 933     }
 934 
 935     /**
 936      * Translates an {@code int} into a {@code BigDecimal}.  The
 937      * scale of the {@code BigDecimal} is zero.
 938      *
 939      * @param val {@code int} value to be converted to
 940      *            {@code BigDecimal}.
 941      * @since  1.5
 942      */
 943     public BigDecimal(int val) {
 944         intCompact = val;
 945     }
 946 
 947     /**
 948      * Translates an {@code int} into a {@code BigDecimal}, with
 949      * rounding according to the context settings.  The scale of the
 950      * {@code BigDecimal}, before any rounding, is zero.
 951      *
 952      * @param  val {@code int} value to be converted to {@code BigDecimal}.
 953      * @param  mc the context to use.
 954      * @throws ArithmeticException if the result is inexact but the
 955      *         rounding mode is {@code UNNECESSARY}.
 956      * @since  1.5
 957      */
 958     public BigDecimal(int val, MathContext mc) {
 959         intCompact = val;
 960         if (mc.precision > 0)
 961             roundThis(mc);
 962     }
 963 
 964     /**
 965      * Translates a {@code long} into a {@code BigDecimal}.  The
 966      * scale of the {@code BigDecimal} is zero.
 967      *
 968      * @param val {@code long} value to be converted to {@code BigDecimal}.
 969      * @since  1.5
 970      */
 971     public BigDecimal(long val) {
 972         this.intCompact = val;
 973         this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
 974     }
 975 
 976     /**
 977      * Translates a {@code long} into a {@code BigDecimal}, with
 978      * rounding according to the context settings.  The scale of the
 979      * {@code BigDecimal}, before any rounding, is zero.
 980      *
 981      * @param  val {@code long} value to be converted to {@code BigDecimal}.
 982      * @param  mc the context to use.
 983      * @throws ArithmeticException if the result is inexact but the
 984      *         rounding mode is {@code UNNECESSARY}.
 985      * @since  1.5
 986      */
 987     public BigDecimal(long val, MathContext mc) {
 988         this(val);
 989         if (mc.precision > 0)
 990             roundThis(mc);
 991     }
 992     
 993     // Static Factory Methods
 994 
 995     /**
 996      * Translates a {@code long} unscaled value and an
 997      * {@code int} scale into a {@code BigDecimal}.  This
 998      * {@literal "static factory method"} is provided in preference to
 999      * a ({@code long}, {@code int}) constructor because it
1000      * allows for reuse of frequently used {@code BigDecimal} values..
1001      *
1002      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1003      * @param scale scale of the {@code BigDecimal}.
1004      * @return a {@code BigDecimal} whose value is
1005      *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1006      */
1007     public static BigDecimal valueOf(long unscaledVal, int scale) {
1008         if (scale == 0)
1009             return valueOf(unscaledVal);
1010         else if (unscaledVal == 0) {
1011             if (scale > 0 && scale < ZERO_SCALED_BY.length)
1012                 return ZERO_SCALED_BY[scale];
1013             else
1014                 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1015         }
1016         return new BigDecimal(unscaledVal == INFLATED ?
1017                               BigInteger.valueOf(unscaledVal) : null, 
1018                               unscaledVal, scale, 0);
1019     }
1020 
1021     /**
1022      * Translates a {@code long} value into a {@code BigDecimal}
1023      * with a scale of zero.  This {@literal "static factory method"}
1024      * is provided in preference to a ({@code long}) constructor
1025      * because it allows for reuse of frequently used
1026      * {@code BigDecimal} values.
1027      *
1028      * @param val value of the {@code BigDecimal}.
1029      * @return a {@code BigDecimal} whose value is {@code val}.
1030      */
1031     public static BigDecimal valueOf(long val) {
1032         if (val >= 0 && val < zeroThroughTen.length)
1033             return zeroThroughTen[(int)val];
1034         else if (val != INFLATED)
1035             return new BigDecimal(null, val, 0, 0);
1036         return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
1037     }
1038 
1039     /**
1040      * Translates a {@code double} into a {@code BigDecimal}, using
1041      * the {@code double}'s canonical string representation provided
1042      * by the {@link Double#toString(double)} method.
1043      *
1044      * <p><b>Note:</b> This is generally the preferred way to convert
1045      * a {@code double} (or {@code float}) into a
1046      * {@code BigDecimal}, as the value returned is equal to that
1047      * resulting from constructing a {@code BigDecimal} from the
1048      * result of using {@link Double#toString(double)}.
1049      *
1050      * @param  val {@code double} to convert to a {@code BigDecimal}.
1051      * @return a {@code BigDecimal} whose value is equal to or approximately
1052      *         equal to the value of {@code val}.
1053      * @throws NumberFormatException if {@code val} is infinite or NaN.
1054      * @since  1.5
1055      */
1056     public static BigDecimal valueOf(double val) {
1057         // Reminder: a zero double returns '0.0', so we cannot fastpath
1058         // to use the constant ZERO.  This might be important enough to
1059         // justify a factory approach, a cache, or a few private
1060         // constants, later.
1061         return new BigDecimal(Double.toString(val));
1062     }
1063 
1064     // Arithmetic Operations
1065     /**
1066      * Returns a {@code BigDecimal} whose value is {@code (this +
1067      * augend)}, and whose scale is {@code max(this.scale(),
1068      * augend.scale())}.
1069      *
1070      * @param  augend value to be added to this {@code BigDecimal}.
1071      * @return {@code this + augend}
1072      */
1073     public BigDecimal add(BigDecimal augend) {
1074         long xs = this.intCompact;
1075         long ys = augend.intCompact;
1076         BigInteger fst = this.intVal;
1077         BigInteger snd = augend.intVal;
1078         int rscale = this.scale;
1079         
1080         long sdiff = (long)rscale - augend.scale;
1081         if (sdiff != 0) {
1082             if (sdiff < 0) {
1083                 int raise = checkScale(-sdiff);
1084                 rscale = augend.scale;
1085                 if (xs == INFLATED ||
1086                     (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
1087                     fst = bigMultiplyPowerTen(raise);
1088             } else {
1089                 int raise = augend.checkScale(sdiff);
1090                 if (ys == INFLATED ||
1091                     (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
1092                     snd = augend.bigMultiplyPowerTen(raise);
1093             }
1094         }
1095         if (xs != INFLATED && ys != INFLATED) {
1096             long sum = xs + ys;
1097             // See "Hacker's Delight" section 2-12 for explanation of
1098             // the overflow test.
1099             if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
1100                 return new BigDecimal(null, sum, rscale, 0);
1101         }
1102         if (fst == null)
1103             fst = BigInteger.valueOf(xs);
1104         if (snd == null)
1105             snd = BigInteger.valueOf(ys);
1106         BigInteger sum = fst.add(snd);
1107         return (fst.signum == snd.signum) ? 
1108             new BigDecimal(sum, INFLATED, rscale, 0) :
1109             new BigDecimal(sum, compactValFor(sum), rscale, 0);
1110     }
1111 
1112     /**
1113      * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1114      * with rounding according to the context settings.
1115      *
1116      * If either number is zero and the precision setting is nonzero then
1117      * the other number, rounded if necessary, is used as the result.
1118      *
1119      * @param  augend value to be added to this {@code BigDecimal}.
1120      * @param  mc the context to use.
1121      * @return {@code this + augend}, rounded as necessary.
1122      * @throws ArithmeticException if the result is inexact but the
1123      *         rounding mode is {@code UNNECESSARY}.
1124      * @since  1.5
1125      */
1126     public BigDecimal add(BigDecimal augend, MathContext mc) {
1127         if (mc.precision == 0)
1128             return add(augend);
1129         BigDecimal lhs = this;
1130 
1131         // Could optimize if values are compact
1132         this.inflate();
1133         augend.inflate();
1134 
1135         // If either number is zero then the other number, rounded and
1136         // scaled if necessary, is used as the result.
1137         {
1138             boolean lhsIsZero = lhs.signum() == 0;
1139             boolean augendIsZero = augend.signum() == 0;
1140 
1141             if (lhsIsZero || augendIsZero) {
1142                 int preferredScale = Math.max(lhs.scale(), augend.scale());
1143                 BigDecimal result;
1144 
1145                 // Could use a factory for zero instead of a new object
1146                 if (lhsIsZero && augendIsZero)
1147                     return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
1148 
1149                 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1150 
1151                 if (result.scale() == preferredScale)
1152                     return result;
1153                 else if (result.scale() > preferredScale) {
1154                     BigDecimal scaledResult =
1155                         new BigDecimal(result.intVal, result.intCompact,
1156                                        result.scale, 0);
1157                     scaledResult.stripZerosToMatchScale(preferredScale);
1158                     return scaledResult;
1159                 } else { // result.scale < preferredScale
1160                     int precisionDiff = mc.precision - result.precision();
1161                     int scaleDiff     = preferredScale - result.scale();
1162 
1163                     if (precisionDiff >= scaleDiff)
1164                         return result.setScale(preferredScale); // can achieve target scale
1165                     else
1166                         return result.setScale(result.scale() + precisionDiff);
1167                 }
1168             }
1169         }
1170 
1171         long padding = (long)lhs.scale - augend.scale;
1172         if (padding != 0) {        // scales differ; alignment needed
1173             BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1174             matchScale(arg);
1175             lhs    = arg[0];
1176             augend = arg[1];
1177         }
1178 
1179         BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
1180                                       lhs.scale);
1181         return doRound(d, mc);
1182     }
1183 
1184     /**
1185      * Returns an array of length two, the sum of whose entries is
1186      * equal to the rounded sum of the {@code BigDecimal} arguments.
1187      *
1188      * <p>If the digit positions of the arguments have a sufficient
1189      * gap between them, the value smaller in magnitude can be
1190      * condensed into a {@literal "sticky bit"} and the end result will
1191      * round the same way <em>if</em> the precision of the final
1192      * result does not include the high order digit of the small
1193      * magnitude operand.
1194      *
1195      * <p>Note that while strictly speaking this is an optimization,
1196      * it makes a much wider range of additions practical.
1197      *
1198      * <p>This corresponds to a pre-shift operation in a fixed
1199      * precision floating-point adder; this method is complicated by
1200      * variable precision of the result as determined by the
1201      * MathContext.  A more nuanced operation could implement a
1202      * {@literal "right shift"} on the smaller magnitude operand so
1203      * that the number of digits of the smaller operand could be
1204      * reduced even though the significands partially overlapped.
1205      */
1206     private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
1207                                   long padding, MathContext mc) {
1208         assert padding != 0;
1209         BigDecimal big;
1210         BigDecimal small;
1211 
1212         if (padding < 0) {     // lhs is big;   augend is small
1213             big   = lhs;
1214             small = augend;
1215         } else {               // lhs is small; augend is big
1216             big   = augend;
1217             small = lhs;
1218         }
1219 
1220         /*
1221          * This is the estimated scale of an ulp of the result; it
1222          * assumes that the result doesn't have a carry-out on a true
1223          * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1224          * on borrowing (e.g. 100 - 1.2 => 98.8)
1225          */
1226         long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
1227 
1228         /*
1229          * The low-order digit position of big is big.scale().  This
1230          * is true regardless of whether big has a positive or
1231          * negative scale.  The high-order digit position of small is
1232          * small.scale - (small.precision() - 1).  To do the full
1233          * condensation, the digit positions of big and small must be
1234          * disjoint *and* the digit positions of small should not be
1235          * directly visible in the result.
1236          */
1237         long smallHighDigitPos = (long)small.scale - small.precision() + 1;
1238         if (smallHighDigitPos > big.scale + 2 &&         // big and small disjoint
1239             smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1240             small = BigDecimal.valueOf(small.signum(),
1241                                        this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1242         }
1243 
1244         // Since addition is symmetric, preserving input order in
1245         // returned operands doesn't matter
1246         BigDecimal[] result = {big, small};
1247         return result;
1248     }
1249 
1250     /**
1251      * Returns a {@code BigDecimal} whose value is {@code (this -
1252      * subtrahend)}, and whose scale is {@code max(this.scale(),
1253      * subtrahend.scale())}.
1254      *
1255      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1256      * @return {@code this - subtrahend}
1257      */
1258     public BigDecimal subtract(BigDecimal subtrahend) {
1259         return add(subtrahend.negate());
1260     }
1261 
1262     /**
1263      * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1264      * with rounding according to the context settings.
1265      *
1266      * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1267      * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1268      *
1269      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1270      * @param  mc the context to use.
1271      * @return {@code this - subtrahend}, rounded as necessary.
1272      * @throws ArithmeticException if the result is inexact but the
1273      *         rounding mode is {@code UNNECESSARY}.
1274      * @since  1.5
1275      */
1276     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1277         BigDecimal nsubtrahend = subtrahend.negate();
1278         if (mc.precision == 0)
1279             return add(nsubtrahend);
1280         // share the special rounding code in add()
1281         return add(nsubtrahend, mc);
1282     }
1283 
1284     /**
1285      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1286      * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1287      * multiplicand.scale())}.
1288      *
1289      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1290      * @return {@code this * multiplicand}
1291      */
1292     public BigDecimal multiply(BigDecimal multiplicand) {
1293         long x = this.intCompact;
1294         long y = multiplicand.intCompact;
1295         int productScale = checkScale((long)scale + multiplicand.scale);
1296 
1297         // Might be able to do a more clever check incorporating the
1298         // inflated check into the overflow computation.
1299         if (x != INFLATED && y != INFLATED) {
1300             /*
1301              * If the product is not an overflowed value, continue
1302              * to use the compact representation.  if either of x or y
1303              * is INFLATED, the product should also be regarded as
1304              * an overflow. Before using the overflow test suggested in
1305              * "Hacker's Delight" section 2-12, we perform quick checks
1306              * using the precision information to see whether the overflow
1307              * would occur since division is expensive on most CPUs.
1308              */
1309             long product = x * y;
1310             int prec = this.precision() + multiplicand.precision();
1311             if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
1312                 return new BigDecimal(null, product, productScale, 0);
1313             return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
1314                                   productScale, 0);  
1315         }
1316         BigInteger rb;
1317         if (x == INFLATED && y == INFLATED)
1318             rb = this.intVal.multiply(multiplicand.intVal);
1319         else if (x != INFLATED)
1320             rb = multiplicand.intVal.multiply(x);
1321         else
1322             rb = this.intVal.multiply(y);
1323         return new BigDecimal(rb, INFLATED, productScale, 0);
1324     }
1325 
1326     /**
1327      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1328      * multiplicand)</tt>, with rounding according to the context settings.
1329      *
1330      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1331      * @param  mc the context to use.
1332      * @return {@code this * multiplicand}, rounded as necessary.
1333      * @throws ArithmeticException if the result is inexact but the
1334      *         rounding mode is {@code UNNECESSARY}.
1335      * @since  1.5
1336      */
1337     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1338         if (mc.precision == 0)
1339             return multiply(multiplicand);
1340         return doRound(this.multiply(multiplicand), mc);
1341     }
1342 
1343     /**
1344      * Returns a {@code BigDecimal} whose value is {@code (this /
1345      * divisor)}, and whose scale is as specified.  If rounding must
1346      * be performed to generate a result with the specified scale, the
1347      * specified rounding mode is applied.
1348      *
1349      * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1350      * should be used in preference to this legacy method.
1351      *
1352      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1353      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1354      * @param  roundingMode rounding mode to apply.
1355      * @return {@code this / divisor}
1356      * @throws ArithmeticException if {@code divisor} is zero,
1357      *         {@code roundingMode==ROUND_UNNECESSARY} and
1358      *         the specified scale is insufficient to represent the result
1359      *         of the division exactly.
1360      * @throws IllegalArgumentException if {@code roundingMode} does not
1361      *         represent a valid rounding mode.
1362      * @see    #ROUND_UP
1363      * @see    #ROUND_DOWN
1364      * @see    #ROUND_CEILING
1365      * @see    #ROUND_FLOOR
1366      * @see    #ROUND_HALF_UP
1367      * @see    #ROUND_HALF_DOWN
1368      * @see    #ROUND_HALF_EVEN
1369      * @see    #ROUND_UNNECESSARY
1370      */
1371     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1372         /*
1373          * IMPLEMENTATION NOTE: This method *must* return a new object
1374          * since divideAndRound uses divide to generate a value whose
1375          * scale is then modified.
1376          */
1377         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1378             throw new IllegalArgumentException("Invalid rounding mode");
1379         /*
1380          * Rescale dividend or divisor (whichever can be "upscaled" to
1381          * produce correctly scaled quotient).
1382          * Take care to detect out-of-range scales
1383          */
1384         BigDecimal dividend = this;
1385         if (checkScale((long)scale + divisor.scale) > this.scale)
1386             dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
1387         else
1388             divisor = divisor.setScale(checkScale((long)this.scale - scale),
1389                                        ROUND_UNNECESSARY);
1390         return divideAndRound(dividend.intCompact, dividend.intVal,
1391                               divisor.intCompact, divisor.intVal,
1392                               scale, roundingMode, scale);
1393     }
1394 
1395     /**
1396      * Internally used for division operation. The dividend and divisor are
1397      * passed both in {@code long} format and {@code BigInteger} format. The
1398      * returned {@code BigDecimal} object is the quotient whose scale is set to
1399      * the passed in scale. If the remainder is not zero, it will be rounded
1400      * based on the passed in roundingMode. Also, if the remainder is zero and
1401      * the last parameter, i.e. preferredScale is NOT equal to scale, the
1402      * trailing zeros of the result is stripped to match the preferredScale.
1403      */
1404     private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend, 
1405                                              long ldivisor,  BigInteger bdivisor,
1406                                              int scale, int roundingMode,
1407                                              int preferredScale) {
1408         boolean isRemainderZero;       // record remainder is zero or not
1409         int qsign;                     // quotient sign
1410         long q = 0, r = 0;             // store quotient & remainder in long
1411         MutableBigInteger mq = null;   // store quotient
1412         MutableBigInteger mr = null;   // store remainder
1413         MutableBigInteger mdivisor = null;
1414         boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
1415         if (isLongDivision) {
1416             q = ldividend / ldivisor;
1417             if (roundingMode == ROUND_DOWN && scale == preferredScale)
1418                 return new BigDecimal(null, q, scale, 0);
1419             r = ldividend % ldivisor;
1420             isRemainderZero = (r == 0);
1421             qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
1422         } else {
1423             if (bdividend == null)
1424                 bdividend = BigInteger.valueOf(ldividend);
1425             // Descend into mutables for faster remainder checks
1426             MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
1427             mq = new MutableBigInteger();
1428             if (ldivisor != INFLATED) {
1429                 r = mdividend.divide(ldivisor, mq);
1430                 isRemainderZero = (r == 0);
1431                 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
1432             } else {
1433                 mdivisor = new MutableBigInteger(bdivisor.mag);
1434                 mr = mdividend.divide(mdivisor, mq);
1435                 isRemainderZero = mr.isZero();
1436                 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
1437             }
1438         }
1439         boolean increment = false;
1440         if (!isRemainderZero) {
1441             int cmpFracHalf;
1442             /* Round as appropriate */
1443             if (roundingMode == ROUND_UNNECESSARY) {  // Rounding prohibited
1444                 throw new ArithmeticException("Rounding necessary");
1445             } else if (roundingMode == ROUND_UP) {      // Away from zero
1446                 increment = true;
1447             } else if (roundingMode == ROUND_DOWN) {    // Towards zero
1448                 increment = false;
1449             } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1450                 increment = (qsign > 0);
1451             } else if (roundingMode == ROUND_FLOOR) {   // Towards -infinity
1452                 increment = (qsign < 0);
1453             } else {
1454                 if (isLongDivision || ldivisor != INFLATED)
1455                     cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
1456                 else
1457                     cmpFracHalf = mr.compareHalf(mdivisor);
1458                 if (cmpFracHalf < 0)
1459                     increment = false;     // We're closer to higher digit
1460                 else if (cmpFracHalf > 0)  // We're closer to lower digit
1461                     increment = true;
1462                 else if (roundingMode == ROUND_HALF_UP)
1463                     increment = true;
1464                 else if (roundingMode == ROUND_HALF_DOWN)
1465                     increment = false;
1466                 else  // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
1467                     increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
1468             }
1469         }
1470         BigDecimal res;
1471         if (isLongDivision)
1472             res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
1473         else {
1474             if (increment)
1475                 mq.add(MutableBigInteger.ONE);
1476             res = mq.toBigDecimal(qsign, scale);
1477         }
1478         if (isRemainderZero && preferredScale != scale)
1479             res.stripZerosToMatchScale(preferredScale);
1480         return res;
1481     }
1482 
1483     /**
1484      * Returns a {@code BigDecimal} whose value is {@code (this /
1485      * divisor)}, and whose scale is as specified.  If rounding must
1486      * be performed to generate a result with the specified scale, the
1487      * specified rounding mode is applied.
1488      *
1489      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1490      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1491      * @param  roundingMode rounding mode to apply.
1492      * @return {@code this / divisor}
1493      * @throws ArithmeticException if {@code divisor} is zero,
1494      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1495      *         the specified scale is insufficient to represent the result
1496      *         of the division exactly.
1497      * @since 1.5
1498      */
1499     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1500         return divide(divisor, scale, roundingMode.oldMode);
1501     }
1502 
1503     /**
1504      * Returns a {@code BigDecimal} whose value is {@code (this /
1505      * divisor)}, and whose scale is {@code this.scale()}.  If
1506      * rounding must be performed to generate a result with the given
1507      * scale, the specified rounding mode is applied.
1508      *
1509      * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1510      * should be used in preference to this legacy method.
1511      *
1512      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1513      * @param  roundingMode rounding mode to apply.
1514      * @return {@code this / divisor}
1515      * @throws ArithmeticException if {@code divisor==0}, or
1516      *         {@code roundingMode==ROUND_UNNECESSARY} and
1517      *         {@code this.scale()} is insufficient to represent the result
1518      *         of the division exactly.
1519      * @throws IllegalArgumentException if {@code roundingMode} does not
1520      *         represent a valid rounding mode.
1521      * @see    #ROUND_UP
1522      * @see    #ROUND_DOWN
1523      * @see    #ROUND_CEILING
1524      * @see    #ROUND_FLOOR
1525      * @see    #ROUND_HALF_UP
1526      * @see    #ROUND_HALF_DOWN
1527      * @see    #ROUND_HALF_EVEN
1528      * @see    #ROUND_UNNECESSARY
1529      */
1530     public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1531             return this.divide(divisor, scale, roundingMode);
1532     }
1533 
1534     /**
1535      * Returns a {@code BigDecimal} whose value is {@code (this /
1536      * divisor)}, and whose scale is {@code this.scale()}.  If
1537      * rounding must be performed to generate a result with the given
1538      * scale, the specified rounding mode is applied.
1539      *
1540      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1541      * @param  roundingMode rounding mode to apply.
1542      * @return {@code this / divisor}
1543      * @throws ArithmeticException if {@code divisor==0}, or
1544      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1545      *         {@code this.scale()} is insufficient to represent the result
1546      *         of the division exactly.
1547      * @since 1.5
1548      */
1549     public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1550         return this.divide(divisor, scale, roundingMode.oldMode);
1551     }
1552 
1553     /**
1554      * Returns a {@code BigDecimal} whose value is {@code (this /
1555      * divisor)}, and whose preferred scale is {@code (this.scale() -
1556      * divisor.scale())}; if the exact quotient cannot be
1557      * represented (because it has a non-terminating decimal
1558      * expansion) an {@code ArithmeticException} is thrown.
1559      *
1560      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1561      * @throws ArithmeticException if the exact quotient does not have a
1562      *         terminating decimal expansion
1563      * @return {@code this / divisor}
1564      * @since 1.5
1565      * @author Joseph D. Darcy
1566      */
1567     public BigDecimal divide(BigDecimal divisor) {
1568         /*
1569          * Handle zero cases first.
1570          */
1571         if (divisor.signum() == 0) {   // x/0
1572             if (this.signum() == 0)    // 0/0
1573                 throw new ArithmeticException("Division undefined");  // NaN
1574             throw new ArithmeticException("Division by zero");
1575         }
1576 
1577         // Calculate preferred scale
1578         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1579         if (this.signum() == 0)        // 0/y
1580             return (preferredScale >= 0 && 
1581                     preferredScale < ZERO_SCALED_BY.length) ? 
1582                 ZERO_SCALED_BY[preferredScale] : 
1583                 new BigDecimal(null, 0, preferredScale, 1);
1584         else {
1585             this.inflate();
1586             divisor.inflate();
1587             /*
1588              * If the quotient this/divisor has a terminating decimal
1589              * expansion, the expansion can have no more than
1590              * (a.precision() + ceil(10*b.precision)/3) digits.
1591              * Therefore, create a MathContext object with this
1592              * precision and do a divide with the UNNECESSARY rounding
1593              * mode.
1594              */
1595             MathContext mc = new MathContext( (int)Math.min(this.precision() +
1596                                                             (long)Math.ceil(10.0*divisor.precision()/3.0),
1597                                                             Integer.MAX_VALUE),
1598                                               RoundingMode.UNNECESSARY);
1599             BigDecimal quotient;
1600             try {
1601                 quotient = this.divide(divisor, mc);
1602             } catch (ArithmeticException e) {
1603                 throw new ArithmeticException("Non-terminating decimal expansion; " +
1604                                               "no exact representable decimal result.");
1605             }
1606 
1607             int quotientScale = quotient.scale();
1608 
1609             // divide(BigDecimal, mc) tries to adjust the quotient to
1610             // the desired one by removing trailing zeros; since the
1611             // exact divide method does not have an explicit digit
1612             // limit, we can add zeros too.
1613 
1614             if (preferredScale > quotientScale)
1615                 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1616 
1617             return quotient;
1618         }
1619     }
1620 
1621     /**
1622      * Returns a {@code BigDecimal} whose value is {@code (this /
1623      * divisor)}, with rounding according to the context settings.
1624      *
1625      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1626      * @param  mc the context to use.
1627      * @return {@code this / divisor}, rounded as necessary.
1628      * @throws ArithmeticException if the result is inexact but the
1629      *         rounding mode is {@code UNNECESSARY} or
1630      *         {@code mc.precision == 0} and the quotient has a
1631      *         non-terminating decimal expansion.
1632      * @since  1.5
1633      */
1634     public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1635         int mcp = mc.precision;
1636         if (mcp == 0)
1637             return divide(divisor);
1638 
1639         BigDecimal dividend = this;
1640         long preferredScale = (long)dividend.scale - divisor.scale;        
1641         // Now calculate the answer.  We use the existing
1642         // divide-and-round method, but as this rounds to scale we have
1643         // to normalize the values here to achieve the desired result.
1644         // For x/y we first handle y=0 and x=0, and then normalize x and
1645         // y to give x' and y' with the following constraints:
1646         //   (a) 0.1 <= x' < 1
1647         //   (b)  x' <= y' < 10*x'
1648         // Dividing x'/y' with the required scale set to mc.precision then
1649         // will give a result in the range 0.1 to 1 rounded to exactly
1650         // the right number of digits (except in the case of a result of
1651         // 1.000... which can arise when x=y, or when rounding overflows
1652         // The 1.000... case will reduce properly to 1.
1653         if (divisor.signum() == 0) {      // x/0
1654             if (dividend.signum() == 0)    // 0/0
1655                 throw new ArithmeticException("Division undefined");  // NaN
1656             throw new ArithmeticException("Division by zero");
1657         }
1658         if (dividend.signum() == 0)        // 0/y
1659             return new BigDecimal(BigInteger.ZERO, 0, 
1660                                   saturateLong(preferredScale), 1);
1661         
1662         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
1663         int xscale = dividend.precision();
1664         int yscale = divisor.precision();
1665         dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
1666                                   xscale, xscale);
1667         divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
1668                                  yscale, yscale);
1669         if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
1670             yscale = divisor.scale -= 1;            // [that is, divisor *= 10]
1671         
1672         // In order to find out whether the divide generates the exact result,
1673         // we avoid calling the above divide method. 'quotient' holds the
1674         // return BigDecimal object whose scale will be set to 'scl'.
1675         BigDecimal quotient;
1676         int scl = checkScale(preferredScale + yscale - xscale + mcp);
1677         if (checkScale((long)mcp + yscale) > xscale)
1678             dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
1679         else
1680             divisor = divisor.setScale(checkScale((long)xscale - mcp),
1681                                        ROUND_UNNECESSARY);
1682         quotient = divideAndRound(dividend.intCompact, dividend.intVal,
1683                                   divisor.intCompact, divisor.intVal,
1684                                   scl, mc.roundingMode.oldMode,
1685                                   checkScale(preferredScale));
1686         // doRound, here, only affects 1000000000 case.
1687         quotient = doRound(quotient, mc);
1688         
1689         return quotient;
1690     }
1691 
1692     /**
1693      * Returns a {@code BigDecimal} whose value is the integer part
1694      * of the quotient {@code (this / divisor)} rounded down.  The
1695      * preferred scale of the result is {@code (this.scale() -
1696      * divisor.scale())}.
1697      *
1698      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1699      * @return The integer part of {@code this / divisor}.
1700      * @throws ArithmeticException if {@code divisor==0}
1701      * @since  1.5
1702      */
1703     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1704         // Calculate preferred scale
1705         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1706         if (this.compareMagnitude(divisor) < 0) {
1707             // much faster when this << divisor
1708             return BigDecimal.valueOf(0, preferredScale);
1709         }
1710 
1711         if(this.signum() == 0 && divisor.signum() != 0)
1712             return this.setScale(preferredScale, ROUND_UNNECESSARY);
1713 
1714         // Perform a divide with enough digits to round to a correct
1715         // integer value; then remove any fractional digits
1716 
1717         int maxDigits = (int)Math.min(this.precision() +
1718                                       (long)Math.ceil(10.0*divisor.precision()/3.0) +
1719                                       Math.abs((long)this.scale() - divisor.scale()) + 2,
1720                                       Integer.MAX_VALUE);
1721         BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1722                                                                    RoundingMode.DOWN));
1723         if (quotient.scale > 0) {
1724             quotient = quotient.setScale(0, RoundingMode.DOWN);
1725             quotient.stripZerosToMatchScale(preferredScale);
1726         }
1727         
1728         if (quotient.scale < preferredScale) {
1729             // pad with zeros if necessary
1730             quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1731         }
1732         return quotient;
1733     }
1734 
1735     /**
1736      * Returns a {@code BigDecimal} whose value is the integer part
1737      * of {@code (this / divisor)}.  Since the integer part of the
1738      * exact quotient does not depend on the rounding mode, the
1739      * rounding mode does not affect the values returned by this
1740      * method.  The preferred scale of the result is
1741      * {@code (this.scale() - divisor.scale())}.  An
1742      * {@code ArithmeticException} is thrown if the integer part of
1743      * the exact quotient needs more than {@code mc.precision}
1744      * digits.
1745      *
1746      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1747      * @param  mc the context to use.
1748      * @return The integer part of {@code this / divisor}.
1749      * @throws ArithmeticException if {@code divisor==0}
1750      * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1751      *         requires a precision of more than {@code mc.precision} digits.
1752      * @since  1.5
1753      * @author Joseph D. Darcy
1754      */
1755     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1756         if (mc.precision == 0 ||                        // exact result
1757             (this.compareMagnitude(divisor) < 0) )   // zero result
1758             return divideToIntegralValue(divisor);
1759         
1760         // Calculate preferred scale
1761         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1762         
1763         /*
1764          * Perform a normal divide to mc.precision digits.  If the
1765          * remainder has absolute value less than the divisor, the
1766          * integer portion of the quotient fits into mc.precision
1767          * digits.  Next, remove any fractional digits from the
1768          * quotient and adjust the scale to the preferred value.
1769          */
1770         BigDecimal result = this.
1771             divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1772         
1773         if (result.scale() < 0) {
1774             /*
1775              * Result is an integer. See if quotient represents the
1776              * full integer portion of the exact quotient; if it does,
1777              * the computed remainder will be less than the divisor.
1778              */
1779             BigDecimal product = result.multiply(divisor);
1780             // If the quotient is the full integer value,
1781             // |dividend-product| < |divisor|.
1782             if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1783                 throw new ArithmeticException("Division impossible");
1784             }
1785         } else if (result.scale() > 0) { 
1786             /*
1787              * Integer portion of quotient will fit into precision
1788              * digits; recompute quotient to scale 0 to avoid double
1789              * rounding and then try to adjust, if necessary.
1790              */
1791             result = result.setScale(0, RoundingMode.DOWN);
1792         }
1793         // else result.scale() == 0; 
1794         
1795         int precisionDiff;
1796         if ((preferredScale > result.scale()) &&
1797             (precisionDiff = mc.precision - result.precision()) > 0) {
1798             return result.setScale(result.scale() +
1799                                    Math.min(precisionDiff, preferredScale - result.scale) );
1800         } else {
1801             result.stripZerosToMatchScale(preferredScale);
1802             return result;
1803         }
1804     }
1805 
1806     /**
1807      * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1808      *
1809      * <p>The remainder is given by
1810      * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1811      * Note that this is not the modulo operation (the result can be
1812      * negative).
1813      *
1814      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1815      * @return {@code this % divisor}.
1816      * @throws ArithmeticException if {@code divisor==0}
1817      * @since  1.5
1818      */
1819     public BigDecimal remainder(BigDecimal divisor) {
1820         BigDecimal divrem[] = this.divideAndRemainder(divisor);
1821         return divrem[1];
1822     }
1823 
1824 
1825     /**
1826      * Returns a {@code BigDecimal} whose value is {@code (this %
1827      * divisor)}, with rounding according to the context settings.
1828      * The {@code MathContext} settings affect the implicit divide
1829      * used to compute the remainder.  The remainder computation
1830      * itself is by definition exact.  Therefore, the remainder may
1831      * contain more than {@code mc.getPrecision()} digits.
1832      *
1833      * <p>The remainder is given by
1834      * {@code this.subtract(this.divideToIntegralValue(divisor,
1835      * mc).multiply(divisor))}.  Note that this is not the modulo
1836      * operation (the result can be negative).
1837      *
1838      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1839      * @param  mc the context to use.
1840      * @return {@code this % divisor}, rounded as necessary.
1841      * @throws ArithmeticException if {@code divisor==0}
1842      * @throws ArithmeticException if the result is inexact but the
1843      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1844      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1845      *         require a precision of more than {@code mc.precision} digits.
1846      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1847      * @since  1.5
1848      */
1849     public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1850         BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1851         return divrem[1];
1852     }
1853 
1854     /**
1855      * Returns a two-element {@code BigDecimal} array containing the
1856      * result of {@code divideToIntegralValue} followed by the result of
1857      * {@code remainder} on the two operands.
1858      *
1859      * <p>Note that if both the integer quotient and remainder are
1860      * needed, this method is faster than using the
1861      * {@code divideToIntegralValue} and {@code remainder} methods
1862      * separately because the division need only be carried out once.
1863      *
1864      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1865      *         and the remainder computed.
1866      * @return a two element {@code BigDecimal} array: the quotient
1867      *         (the result of {@code divideToIntegralValue}) is the initial element
1868      *         and the remainder is the final element.
1869      * @throws ArithmeticException if {@code divisor==0}
1870      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1871      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1872      * @since  1.5
1873      */
1874     public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1875         // we use the identity  x = i * y + r to determine r
1876         BigDecimal[] result = new BigDecimal[2];
1877 
1878         result[0] = this.divideToIntegralValue(divisor);
1879         result[1] = this.subtract(result[0].multiply(divisor));
1880         return result;
1881     }
1882 
1883     /**
1884      * Returns a two-element {@code BigDecimal} array containing the
1885      * result of {@code divideToIntegralValue} followed by the result of
1886      * {@code remainder} on the two operands calculated with rounding
1887      * according to the context settings.
1888      *
1889      * <p>Note that if both the integer quotient and remainder are
1890      * needed, this method is faster than using the
1891      * {@code divideToIntegralValue} and {@code remainder} methods
1892      * separately because the division need only be carried out once.
1893      *
1894      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1895      *         and the remainder computed.
1896      * @param  mc the context to use.
1897      * @return a two element {@code BigDecimal} array: the quotient
1898      *         (the result of {@code divideToIntegralValue}) is the
1899      *         initial element and the remainder is the final element.
1900      * @throws ArithmeticException if {@code divisor==0}
1901      * @throws ArithmeticException if the result is inexact but the
1902      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1903      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1904      *         require a precision of more than {@code mc.precision} digits.
1905      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1906      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1907      * @since  1.5
1908      */
1909     public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1910         if (mc.precision == 0)
1911             return divideAndRemainder(divisor);
1912 
1913         BigDecimal[] result = new BigDecimal[2];
1914         BigDecimal lhs = this;
1915 
1916         result[0] = lhs.divideToIntegralValue(divisor, mc);
1917         result[1] = lhs.subtract(result[0].multiply(divisor));
1918         return result;
1919     }
1920 
1921     /**
1922      * Returns a {@code BigDecimal} whose value is
1923      * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
1924      * unlimited precision.
1925      *
1926      * <p>The parameter {@code n} must be in the range 0 through
1927      * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
1928      * #ONE}.
1929      *
1930      * Note that future releases may expand the allowable exponent
1931      * range of this method.
1932      *
1933      * @param  n power to raise this {@code BigDecimal} to.
1934      * @return <tt>this<sup>n</sup></tt>
1935      * @throws ArithmeticException if {@code n} is out of range.
1936      * @since  1.5
1937      */
1938     public BigDecimal pow(int n) {
1939         if (n < 0 || n > 999999999)
1940             throw new ArithmeticException("Invalid operation");
1941         // No need to calculate pow(n) if result will over/underflow.
1942         // Don't attempt to support "supernormal" numbers.
1943         int newScale = checkScale((long)scale * n);
1944         this.inflate();
1945         return new BigDecimal(intVal.pow(n), newScale);
1946     }
1947 
1948 
1949     /**
1950      * Returns a {@code BigDecimal} whose value is
1951      * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
1952      * the core algorithm defined in ANSI standard X3.274-1996 with
1953      * rounding according to the context settings.  In general, the
1954      * returned numerical value is within two ulps of the exact
1955      * numerical value for the chosen precision.  Note that future
1956      * releases may use a different algorithm with a decreased
1957      * allowable error bound and increased allowable exponent range.
1958      *
1959      * <p>The X3.274-1996 algorithm is:
1960      *
1961      * <ul>
1962      * <li> An {@code ArithmeticException} exception is thrown if
1963      *  <ul>
1964      *    <li>{@code abs(n) > 999999999}
1965      *    <li>{@code mc.precision == 0} and {@code n < 0}
1966      *    <li>{@code mc.precision > 0} and {@code n} has more than
1967      *    {@code mc.precision} decimal digits
1968      *  </ul>
1969      *
1970      * <li> if {@code n} is zero, {@link #ONE} is returned even if
1971      * {@code this} is zero, otherwise
1972      * <ul>
1973      *   <li> if {@code n} is positive, the result is calculated via
1974      *   the repeated squaring technique into a single accumulator.
1975      *   The individual multiplications with the accumulator use the
1976      *   same math context settings as in {@code mc} except for a
1977      *   precision increased to {@code mc.precision + elength + 1}
1978      *   where {@code elength} is the number of decimal digits in
1979      *   {@code n}.
1980      *
1981      *   <li> if {@code n} is negative, the result is calculated as if
1982      *   {@code n} were positive; this value is then divided into one
1983      *   using the working precision specified above.
1984      *
1985      *   <li> The final value from either the positive or negative case
1986      *   is then rounded to the destination precision.
1987      *   </ul>
1988      * </ul>
1989      *
1990      * @param  n power to raise this {@code BigDecimal} to.
1991      * @param  mc the context to use.
1992      * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
1993      *         algorithm
1994      * @throws ArithmeticException if the result is inexact but the
1995      *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
1996      *         of range.
1997      * @since  1.5
1998      */
1999     public BigDecimal pow(int n, MathContext mc) {
2000         if (mc.precision == 0)
2001             return pow(n);
2002         if (n < -999999999 || n > 999999999)
2003             throw new ArithmeticException("Invalid operation");
2004         if (n == 0)
2005             return ONE;                      // x**0 == 1 in X3.274
2006         this.inflate();
2007         BigDecimal lhs = this;
2008         MathContext workmc = mc;           // working settings
2009         int mag = Math.abs(n);               // magnitude of n
2010         if (mc.precision > 0) {
2011 
2012             int elength = longDigitLength(mag); // length of n in digits
2013             if (elength > mc.precision)        // X3.274 rule
2014                 throw new ArithmeticException("Invalid operation");
2015             workmc = new MathContext(mc.precision + elength + 1,
2016                                       mc.roundingMode);
2017         }
2018         // ready to carry out power calculation...
2019         BigDecimal acc = ONE;           // accumulator
2020         boolean seenbit = false;        // set once we've seen a 1-bit
2021         for (int i=1;;i++) {            // for each bit [top bit ignored]
2022             mag += mag;                 // shift left 1 bit
2023             if (mag < 0) {              // top bit is set
2024                 seenbit = true;         // OK, we're off
2025                 acc = acc.multiply(lhs, workmc); // acc=acc*x
2026             }
2027             if (i == 31)
2028                 break;                  // that was the last bit
2029             if (seenbit)
2030                 acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
2031                 // else (!seenbit) no point in squaring ONE
2032         }
2033         // if negative n, calculate the reciprocal using working precision
2034         if (n<0)                          // [hence mc.precision>0]
2035             acc=ONE.divide(acc, workmc);
2036         // round to final precision and strip zeros
2037         return doRound(acc, mc);
2038     }
2039 
2040     /**
2041      * Returns a {@code BigDecimal} whose value is the absolute value
2042      * of this {@code BigDecimal}, and whose scale is
2043      * {@code this.scale()}.
2044      *
2045      * @return {@code abs(this)}
2046      */
2047     public BigDecimal abs() {
2048         return (signum() < 0 ? negate() : this);
2049     }
2050 
2051     /**
2052      * Returns a {@code BigDecimal} whose value is the absolute value
2053      * of this {@code BigDecimal}, with rounding according to the
2054      * context settings.
2055      *
2056      * @param mc the context to use.
2057      * @return {@code abs(this)}, rounded as necessary.
2058      * @throws ArithmeticException if the result is inexact but the
2059      *         rounding mode is {@code UNNECESSARY}.
2060      * @since 1.5
2061      */
2062     public BigDecimal abs(MathContext mc) {
2063         return (signum() < 0 ? negate(mc) : plus(mc));
2064     }
2065 
2066     /**
2067      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2068      * and whose scale is {@code this.scale()}.
2069      *
2070      * @return {@code -this}.
2071      */
2072     public BigDecimal negate() {
2073         BigDecimal result;
2074         if (intCompact != INFLATED)
2075             result = BigDecimal.valueOf(-intCompact, scale);
2076         else {
2077             result = new BigDecimal(intVal.negate(), scale);
2078             result.precision = precision;
2079         }
2080         return result;
2081     }
2082 
2083     /**
2084      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2085      * with rounding according to the context settings.
2086      *
2087      * @param mc the context to use.
2088      * @return {@code -this}, rounded as necessary.
2089      * @throws ArithmeticException if the result is inexact but the
2090      *         rounding mode is {@code UNNECESSARY}.
2091      * @since  1.5
2092      */
2093     public BigDecimal negate(MathContext mc) {
2094         return negate().plus(mc);
2095     }
2096 
2097     /**
2098      * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2099      * scale is {@code this.scale()}.
2100      *
2101      * <p>This method, which simply returns this {@code BigDecimal}
2102      * is included for symmetry with the unary minus method {@link
2103      * #negate()}.
2104      *
2105      * @return {@code this}.
2106      * @see #negate()
2107      * @since  1.5
2108      */
2109     public BigDecimal plus() {
2110         return this;
2111     }
2112 
2113     /**
2114      * Returns a {@code BigDecimal} whose value is {@code (+this)},
2115      * with rounding according to the context settings.
2116      *
2117      * <p>The effect of this method is identical to that of the {@link
2118      * #round(MathContext)} method.
2119      *
2120      * @param mc the context to use.
2121      * @return {@code this}, rounded as necessary.  A zero result will
2122      *         have a scale of 0.
2123      * @throws ArithmeticException if the result is inexact but the
2124      *         rounding mode is {@code UNNECESSARY}.
2125      * @see    #round(MathContext)
2126      * @since  1.5
2127      */
2128     public BigDecimal plus(MathContext mc) {
2129         if (mc.precision == 0)                 // no rounding please
2130             return this;
2131         return doRound(this, mc);
2132     }
2133 
2134     /**
2135      * Returns the signum function of this {@code BigDecimal}.
2136      *
2137      * @return -1, 0, or 1 as the value of this {@code BigDecimal}
2138      *         is negative, zero, or positive.
2139      */
2140     public int signum() {
2141         return (intCompact != INFLATED)?
2142             Long.signum(intCompact):
2143             intVal.signum();
2144     }
2145 
2146     /**
2147      * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
2148      * or positive, the scale is the number of digits to the right of
2149      * the decimal point.  If negative, the unscaled value of the
2150      * number is multiplied by ten to the power of the negation of the
2151      * scale.  For example, a scale of {@code -3} means the unscaled
2152      * value is multiplied by 1000.
2153      *
2154      * @return the scale of this {@code BigDecimal}.
2155      */
2156     public int scale() {
2157         return scale;
2158     }
2159 
2160     /**
2161      * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2162      * precision is the number of digits in the unscaled value.)
2163      *
2164      * <p>The precision of a zero value is 1.
2165      *
2166      * @return the precision of this {@code BigDecimal}.
2167      * @since  1.5
2168      */
2169     public int precision() {
2170         int result = precision;
2171         if (result == 0) {
2172             long s = intCompact;
2173             if (s != INFLATED)
2174                 result = longDigitLength(s);
2175             else
2176                 result = bigDigitLength(inflate());
2177             precision = result;
2178         }
2179         return result;
2180     }
2181 
2182 
2183     /**
2184      * Returns a {@code BigInteger} whose value is the <i>unscaled
2185      * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
2186      * 10<sup>this.scale()</sup>)</tt>.)
2187      *
2188      * @return the unscaled value of this {@code BigDecimal}.
2189      * @since  1.2
2190      */
2191     public BigInteger unscaledValue() {
2192         return this.inflate();
2193     }
2194 
2195     // Rounding Modes
2196 
2197     /**
2198      * Rounding mode to round away from zero.  Always increments the
2199      * digit prior to a nonzero discarded fraction.  Note that this rounding
2200      * mode never decreases the magnitude of the calculated value.
2201      */
2202     public final static int ROUND_UP =           0;
2203 
2204     /**
2205      * Rounding mode to round towards zero.  Never increments the digit
2206      * prior to a discarded fraction (i.e., truncates).  Note that this
2207      * rounding mode never increases the magnitude of the calculated value.
2208      */
2209     public final static int ROUND_DOWN =         1;
2210 
2211     /**
2212      * Rounding mode to round towards positive infinity.  If the
2213      * {@code BigDecimal} is positive, behaves as for
2214      * {@code ROUND_UP}; if negative, behaves as for
2215      * {@code ROUND_DOWN}.  Note that this rounding mode never
2216      * decreases the calculated value.
2217      */
2218     public final static int ROUND_CEILING =      2;
2219 
2220     /**
2221      * Rounding mode to round towards negative infinity.  If the
2222      * {@code BigDecimal} is positive, behave as for
2223      * {@code ROUND_DOWN}; if negative, behave as for
2224      * {@code ROUND_UP}.  Note that this rounding mode never
2225      * increases the calculated value.
2226      */
2227     public final static int ROUND_FLOOR =        3;
2228 
2229     /**
2230      * Rounding mode to round towards {@literal "nearest neighbor"}
2231      * unless both neighbors are equidistant, in which case round up.
2232      * Behaves as for {@code ROUND_UP} if the discarded fraction is
2233      * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
2234      * that this is the rounding mode that most of us were taught in
2235      * grade school.
2236      */
2237     public final static int ROUND_HALF_UP =      4;
2238 
2239     /**
2240      * Rounding mode to round towards {@literal "nearest neighbor"}
2241      * unless both neighbors are equidistant, in which case round
2242      * down.  Behaves as for {@code ROUND_UP} if the discarded
2243      * fraction is {@literal >} 0.5; otherwise, behaves as for
2244      * {@code ROUND_DOWN}.
2245      */
2246     public final static int ROUND_HALF_DOWN =    5;
2247 
2248     /**
2249      * Rounding mode to round towards the {@literal "nearest neighbor"}
2250      * unless both neighbors are equidistant, in which case, round
2251      * towards the even neighbor.  Behaves as for
2252      * {@code ROUND_HALF_UP} if the digit to the left of the
2253      * discarded fraction is odd; behaves as for
2254      * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
2255      * rounding mode that minimizes cumulative error when applied
2256      * repeatedly over a sequence of calculations.
2257      */
2258     public final static int ROUND_HALF_EVEN =    6;
2259 
2260     /**
2261      * Rounding mode to assert that the requested operation has an exact
2262      * result, hence no rounding is necessary.  If this rounding mode is
2263      * specified on an operation that yields an inexact result, an
2264      * {@code ArithmeticException} is thrown.
2265      */
2266     public final static int ROUND_UNNECESSARY =  7;
2267 
2268 
2269     // Scaling/Rounding Operations
2270 
2271     /**
2272      * Returns a {@code BigDecimal} rounded according to the
2273      * {@code MathContext} settings.  If the precision setting is 0 then
2274      * no rounding takes place.
2275      *
2276      * <p>The effect of this method is identical to that of the
2277      * {@link #plus(MathContext)} method.
2278      *
2279      * @param mc the context to use.
2280      * @return a {@code BigDecimal} rounded according to the
2281      *         {@code MathContext} settings.
2282      * @throws ArithmeticException if the rounding mode is
2283      *         {@code UNNECESSARY} and the
2284      *         {@code BigDecimal}  operation would require rounding.
2285      * @see    #plus(MathContext)
2286      * @since  1.5
2287      */
2288     public BigDecimal round(MathContext mc) {
2289         return plus(mc);
2290     }
2291 
2292     /**
2293      * Returns a {@code BigDecimal} whose scale is the specified
2294      * value, and whose unscaled value is determined by multiplying or
2295      * dividing this {@code BigDecimal}'s unscaled value by the
2296      * appropriate power of ten to maintain its overall value.  If the
2297      * scale is reduced by the operation, the unscaled value must be
2298      * divided (rather than multiplied), and the value may be changed;
2299      * in this case, the specified rounding mode is applied to the
2300      * division.
2301      *
2302      * <p>Note that since BigDecimal objects are immutable, calls of
2303      * this method do <i>not</i> result in the original object being
2304      * modified, contrary to the usual convention of having methods
2305      * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2306      * Instead, {@code setScale} returns an object with the proper
2307      * scale; the returned object may or may not be newly allocated.
2308      *
2309      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2310      * @param  roundingMode The rounding mode to apply.
2311      * @return a {@code BigDecimal} whose scale is the specified value,
2312      *         and whose unscaled value is determined by multiplying or
2313      *         dividing this {@code BigDecimal}'s unscaled value by the
2314      *         appropriate power of ten to maintain its overall value.
2315      * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2316      *         and the specified scaling operation would require
2317      *         rounding.
2318      * @see    RoundingMode
2319      * @since  1.5
2320      */
2321     public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2322         return setScale(newScale, roundingMode.oldMode);
2323     }
2324 
2325     /**
2326      * Returns a {@code BigDecimal} whose scale is the specified
2327      * value, and whose unscaled value is determined by multiplying or
2328      * dividing this {@code BigDecimal}'s unscaled value by the
2329      * appropriate power of ten to maintain its overall value.  If the
2330      * scale is reduced by the operation, the unscaled value must be
2331      * divided (rather than multiplied), and the value may be changed;
2332      * in this case, the specified rounding mode is applied to the
2333      * division.
2334      *
2335      * <p>Note that since BigDecimal objects are immutable, calls of
2336      * this method do <i>not</i> result in the original object being
2337      * modified, contrary to the usual convention of having methods
2338      * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2339      * Instead, {@code setScale} returns an object with the proper
2340      * scale; the returned object may or may not be newly allocated.
2341      *
2342      * <p>The new {@link #setScale(int, RoundingMode)} method should
2343      * be used in preference to this legacy method.
2344      *
2345      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2346      * @param  roundingMode The rounding mode to apply.
2347      * @return a {@code BigDecimal} whose scale is the specified value,
2348      *         and whose unscaled value is determined by multiplying or
2349      *         dividing this {@code BigDecimal}'s unscaled value by the
2350      *         appropriate power of ten to maintain its overall value.
2351      * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2352      *         and the specified scaling operation would require
2353      *         rounding.
2354      * @throws IllegalArgumentException if {@code roundingMode} does not
2355      *         represent a valid rounding mode.
2356      * @see    #ROUND_UP
2357      * @see    #ROUND_DOWN
2358      * @see    #ROUND_CEILING
2359      * @see    #ROUND_FLOOR
2360      * @see    #ROUND_HALF_UP
2361      * @see    #ROUND_HALF_DOWN
2362      * @see    #ROUND_HALF_EVEN
2363      * @see    #ROUND_UNNECESSARY
2364      */
2365     public BigDecimal setScale(int newScale, int roundingMode) {
2366         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2367             throw new IllegalArgumentException("Invalid rounding mode");
2368 
2369         int oldScale = this.scale;
2370         if (newScale == oldScale)        // easy case
2371             return this;
2372         if (this.signum() == 0)            // zero can have any scale
2373             return BigDecimal.valueOf(0, newScale);
2374         
2375         long rs = this.intCompact;
2376         if (newScale > oldScale) {
2377             int raise = checkScale((long)newScale - oldScale);
2378             BigInteger rb = null;
2379             if (rs == INFLATED ||
2380                 (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
2381                 rb = bigMultiplyPowerTen(raise);
2382             return new BigDecimal(rb, rs, newScale,
2383                                   (precision > 0) ? precision + raise : 0);
2384         } else {
2385             // newScale < oldScale -- drop some digits
2386             // Can't predict the precision due to the effect of rounding.
2387             int drop = checkScale((long)oldScale - newScale);
2388             if (drop < LONG_TEN_POWERS_TABLE.length)
2389                 return divideAndRound(rs, this.intVal,
2390                                       LONG_TEN_POWERS_TABLE[drop], null,
2391                                       newScale, roundingMode, newScale);
2392             else
2393                 return divideAndRound(rs, this.intVal,
2394                                       INFLATED, bigTenToThe(drop),
2395                                       newScale, roundingMode, newScale);
2396         }
2397     }
2398 
2399     /**
2400      * Returns a {@code BigDecimal} whose scale is the specified
2401      * value, and whose value is numerically equal to this
2402      * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2403      * if this is not possible.
2404      *
2405      * <p>This call is typically used to increase the scale, in which
2406      * case it is guaranteed that there exists a {@code BigDecimal}
2407      * of the specified scale and the correct value.  The call can
2408      * also be used to reduce the scale if the caller knows that the
2409      * {@code BigDecimal} has sufficiently many zeros at the end of
2410      * its fractional part (i.e., factors of ten in its integer value)
2411      * to allow for the rescaling without changing its value.
2412      *
2413      * <p>This method returns the same result as the two-argument
2414      * versions of {@code setScale}, but saves the caller the trouble
2415      * of specifying a rounding mode in cases where it is irrelevant.
2416      *
2417      * <p>Note that since {@code BigDecimal} objects are immutable,
2418      * calls of this method do <i>not</i> result in the original
2419      * object being modified, contrary to the usual convention of
2420      * having methods named <tt>set<i>X</i></tt> mutate field
2421      * <i>{@code X}</i>.  Instead, {@code setScale} returns an
2422      * object with the proper scale; the returned object may or may
2423      * not be newly allocated.
2424      *
2425      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2426      * @return a {@code BigDecimal} whose scale is the specified value, and
2427      *         whose unscaled value is determined by multiplying or dividing
2428      *         this {@code BigDecimal}'s unscaled value by the appropriate
2429      *         power of ten to maintain its overall value.
2430      * @throws ArithmeticException if the specified scaling operation would
2431      *         require rounding.
2432      * @see    #setScale(int, int)
2433      * @see    #setScale(int, RoundingMode)
2434      */
2435     public BigDecimal setScale(int newScale) {
2436         return setScale(newScale, ROUND_UNNECESSARY);
2437     }
2438 
2439     // Decimal Point Motion Operations
2440 
2441     /**
2442      * Returns a {@code BigDecimal} which is equivalent to this one
2443      * with the decimal point moved {@code n} places to the left.  If
2444      * {@code n} is non-negative, the call merely adds {@code n} to
2445      * the scale.  If {@code n} is negative, the call is equivalent
2446      * to {@code movePointRight(-n)}.  The {@code BigDecimal}
2447      * returned by this call has value <tt>(this &times;
2448      * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
2449      * 0)}.
2450      *
2451      * @param  n number of places to move the decimal point to the left.
2452      * @return a {@code BigDecimal} which is equivalent to this one with the
2453      *         decimal point moved {@code n} places to the left.
2454      * @throws ArithmeticException if scale overflows.
2455      */
2456     public BigDecimal movePointLeft(int n) {
2457         // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2458         int newScale = checkScale((long)scale + n);
2459         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2460         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2461     }
2462 
2463     /**
2464      * Returns a {@code BigDecimal} which is equivalent to this one
2465      * with the decimal point moved {@code n} places to the right.
2466      * If {@code n} is non-negative, the call merely subtracts
2467      * {@code n} from the scale.  If {@code n} is negative, the call
2468      * is equivalent to {@code movePointLeft(-n)}.  The
2469      * {@code BigDecimal} returned by this call has value <tt>(this
2470      * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
2471      * 0)}.
2472      *
2473      * @param  n number of places to move the decimal point to the right.
2474      * @return a {@code BigDecimal} which is equivalent to this one
2475      *         with the decimal point moved {@code n} places to the right.
2476      * @throws ArithmeticException if scale overflows.
2477      */
2478     public BigDecimal movePointRight(int n) {
2479         // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2480         int newScale = checkScale((long)scale - n);
2481         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2482         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2483     }
2484 
2485     /**
2486      * Returns a BigDecimal whose numerical value is equal to
2487      * ({@code this} * 10<sup>n</sup>).  The scale of
2488      * the result is {@code (this.scale() - n)}.
2489      *
2490      * @throws ArithmeticException if the scale would be
2491      *         outside the range of a 32-bit integer.
2492      *
2493      * @since 1.5
2494      */
2495     public BigDecimal scaleByPowerOfTen(int n) {
2496         return new BigDecimal(intVal, intCompact,
2497                               checkScale((long)scale - n), precision);
2498     }
2499 
2500     /**
2501      * Returns a {@code BigDecimal} which is numerically equal to
2502      * this one but with any trailing zeros removed from the
2503      * representation.  For example, stripping the trailing zeros from
2504      * the {@code BigDecimal} value {@code 600.0}, which has
2505      * [{@code BigInteger}, {@code scale}] components equals to
2506      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2507      * {@code scale}] components equals to [6, -2]
2508      *
2509      * @return a numerically equal {@code BigDecimal} with any
2510      * trailing zeros removed.
2511      * @since 1.5
2512      */
2513     public BigDecimal stripTrailingZeros() {
2514         this.inflate();
2515         BigDecimal result = new BigDecimal(intVal, scale);
2516         result.stripZerosToMatchScale(Long.MIN_VALUE);
2517         return result;
2518     }
2519 
2520     // Comparison Operations
2521 
2522     /**
2523      * Compares this {@code BigDecimal} with the specified
2524      * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2525      * equal in value but have a different scale (like 2.0 and 2.00)
2526      * are considered equal by this method.  This method is provided
2527      * in preference to individual methods for each of the six boolean
2528      * comparison operators ({@literal <}, ==,
2529      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2530      * suggested idiom for performing these comparisons is:
2531      * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2532      * &lt;<i>op</i>&gt; is one of the six comparison operators.
2533      *
2534      * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
2535      *         to be compared.
2536      * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2537      *          less than, equal to, or greater than {@code val}.
2538      */
2539     public int compareTo(BigDecimal val) {
2540         // Quick path for equal scale and non-inflated case.
2541         if (scale == val.scale) {
2542             long xs = intCompact;
2543             long ys = val.intCompact;
2544             if (xs != INFLATED && ys != INFLATED)
2545                 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2546         }
2547         int xsign = this.signum();
2548         int ysign = val.signum();
2549         if (xsign != ysign)
2550             return (xsign > ysign) ? 1 : -1;
2551         if (xsign == 0)
2552             return 0;
2553         int cmp = compareMagnitude(val);
2554         return (xsign > 0) ? cmp : -cmp;
2555     }
2556 
2557     /**
2558      * Version of compareTo that ignores sign.
2559      */
2560     private int compareMagnitude(BigDecimal val) {
2561         // Match scales, avoid unnecessary inflation
2562         long ys = val.intCompact;
2563         long xs = this.intCompact;
2564         if (xs == 0)
2565             return (ys == 0) ? 0 : -1;
2566         if (ys == 0)
2567             return 1;
2568         
2569         int sdiff = this.scale - val.scale;
2570         if (sdiff != 0) {
2571             // Avoid matching scales if the (adjusted) exponents differ
2572             int xae = this.precision() - this.scale;   // [-1]
2573             int yae = val.precision() - val.scale;     // [-1]
2574             if (xae < yae)
2575                 return -1;
2576             if (xae > yae)
2577                 return 1;
2578             BigInteger rb = null;
2579             if (sdiff < 0) {
2580                 if ( (xs == INFLATED ||
2581                       (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
2582                      ys == INFLATED) {
2583                     rb = bigMultiplyPowerTen(-sdiff);
2584                     return rb.compareMagnitude(val.intVal);
2585                 }
2586             } else { // sdiff > 0
2587                 if ( (ys == INFLATED ||
2588                       (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
2589                      xs == INFLATED) {
2590                     rb = val.bigMultiplyPowerTen(sdiff);
2591                     return this.intVal.compareMagnitude(rb);
2592                 }
2593             }
2594         }
2595         if (xs != INFLATED)
2596             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2597         else if (ys != INFLATED)
2598             return 1;
2599         else
2600             return this.intVal.compareMagnitude(val.intVal);
2601     }
2602 
2603     /**
2604      * Compares this {@code BigDecimal} with the specified
2605      * {@code Object} for equality.  Unlike {@link
2606      * #compareTo(BigDecimal) compareTo}, this method considers two
2607      * {@code BigDecimal} objects equal only if they are equal in
2608      * value and scale (thus 2.0 is not equal to 2.00 when compared by
2609      * this method).
2610      *
2611      * @param  x {@code Object} to which this {@code BigDecimal} is
2612      *         to be compared.
2613      * @return {@code true} if and only if the specified {@code Object} is a
2614      *         {@code BigDecimal} whose value and scale are equal to this
2615      *         {@code BigDecimal}'s.
2616      * @see    #compareTo(java.math.BigDecimal)
2617      * @see    #hashCode
2618      */
2619     @Override
2620     public boolean equals(Object x) {
2621         if (!(x instanceof BigDecimal))
2622             return false;
2623         BigDecimal xDec = (BigDecimal) x;
2624         if (x == this)
2625             return true;
2626         if (scale != xDec.scale)
2627             return false;
2628         long s = this.intCompact;
2629         long xs = xDec.intCompact;
2630         if (s != INFLATED) {
2631             if (xs == INFLATED)
2632                 xs = compactValFor(xDec.intVal);
2633             return xs == s;
2634         } else if (xs != INFLATED)
2635             return xs == compactValFor(this.intVal);
2636 
2637         return this.inflate().equals(xDec.inflate());
2638     }
2639 
2640     /**
2641      * Returns the minimum of this {@code BigDecimal} and
2642      * {@code val}.
2643      *
2644      * @param  val value with which the minimum is to be computed.
2645      * @return the {@code BigDecimal} whose value is the lesser of this
2646      *         {@code BigDecimal} and {@code val}.  If they are equal,
2647      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2648      *         method, {@code this} is returned.
2649      * @see    #compareTo(java.math.BigDecimal)
2650      */
2651     public BigDecimal min(BigDecimal val) {
2652         return (compareTo(val) <= 0 ? this : val);
2653     }
2654 
2655     /**
2656      * Returns the maximum of this {@code BigDecimal} and {@code val}.
2657      *
2658      * @param  val value with which the maximum is to be computed.
2659      * @return the {@code BigDecimal} whose value is the greater of this
2660      *         {@code BigDecimal} and {@code val}.  If they are equal,
2661      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2662      *         method, {@code this} is returned.
2663      * @see    #compareTo(java.math.BigDecimal)
2664      */
2665     public BigDecimal max(BigDecimal val) {
2666         return (compareTo(val) >= 0 ? this : val);
2667     }
2668 
2669     // Hash Function
2670 
2671     /**
2672      * Returns the hash code for this {@code BigDecimal}.  Note that
2673      * two {@code BigDecimal} objects that are numerically equal but
2674      * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2675      * have the same hash code.
2676      *
2677      * @return hash code for this {@code BigDecimal}.
2678      * @see #equals(Object)
2679      */
2680     @Override
2681     public int hashCode() {
2682         if (intCompact != INFLATED) {
2683             long val2 = (intCompact < 0)? -intCompact : intCompact;
2684             int temp = (int)( ((int)(val2 >>> 32)) * 31  +
2685                               (val2 & LONG_MASK));
2686             return 31*((intCompact < 0) ?-temp:temp) + scale;
2687         } else
2688             return 31*intVal.hashCode() + scale;
2689     }
2690 
2691     // Format Converters
2692 
2693     /**
2694      * Returns the string representation of this {@code BigDecimal},
2695      * using scientific notation if an exponent is needed.
2696      *
2697      * <p>A standard canonical string form of the {@code BigDecimal}
2698      * is created as though by the following steps: first, the
2699      * absolute value of the unscaled value of the {@code BigDecimal}
2700      * is converted to a string in base ten using the characters
2701      * {@code '0'} through {@code '9'} with no leading zeros (except
2702      * if its value is zero, in which case a single {@code '0'}
2703      * character is used).
2704      *
2705      * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2706      * negated scale, plus the number of characters in the converted
2707      * unscaled value, less one.  That is,
2708      * {@code -scale+(ulength-1)}, where {@code ulength} is the
2709      * length of the absolute value of the unscaled value in decimal
2710      * digits (its <i>precision</i>).
2711      *
2712      * <p>If the scale is greater than or equal to zero and the
2713      * adjusted exponent is greater than or equal to {@code -6}, the
2714      * number will be converted to a character form without using
2715      * exponential notation.  In this case, if the scale is zero then
2716      * no decimal point is added and if the scale is positive a
2717      * decimal point will be inserted with the scale specifying the
2718      * number of characters to the right of the decimal point.
2719      * {@code '0'} characters are added to the left of the converted
2720      * unscaled value as necessary.  If no character precedes the
2721      * decimal point after this insertion then a conventional
2722      * {@code '0'} character is prefixed.
2723      *
2724      * <p>Otherwise (that is, if the scale is negative, or the
2725      * adjusted exponent is less than {@code -6}), the number will be
2726      * converted to a character form using exponential notation.  In
2727      * this case, if the converted {@code BigInteger} has more than
2728      * one digit a decimal point is inserted after the first digit.
2729      * An exponent in character form is then suffixed to the converted
2730      * unscaled value (perhaps with inserted decimal point); this
2731      * comprises the letter {@code 'E'} followed immediately by the
2732      * adjusted exponent converted to a character form.  The latter is
2733      * in base ten, using the characters {@code '0'} through
2734      * {@code '9'} with no leading zeros, and is always prefixed by a
2735      * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the
2736      * adjusted exponent is negative, {@code '+'}
2737      * (<tt>'&#92;u002B'</tt>) otherwise).
2738      *
2739      * <p>Finally, the entire string is prefixed by a minus sign
2740      * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled
2741      * value is less than zero.  No sign character is prefixed if the
2742      * unscaled value is zero or positive.
2743      *
2744      * <p><b>Examples:</b>
2745      * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2746      * on the left, the resulting string is shown on the right.
2747      * <pre>
2748      * [123,0]      "123"
2749      * [-123,0]     "-123"
2750      * [123,-1]     "1.23E+3"
2751      * [123,-3]     "1.23E+5"
2752      * [123,1]      "12.3"
2753      * [123,5]      "0.00123"
2754      * [123,10]     "1.23E-8"
2755      * [-123,12]    "-1.23E-10"
2756      * </pre>
2757      *
2758      * <b>Notes:</b>
2759      * <ol>
2760      *
2761      * <li>There is a one-to-one mapping between the distinguishable
2762      * {@code BigDecimal} values and the result of this conversion.
2763      * That is, every distinguishable {@code BigDecimal} value
2764      * (unscaled value and scale) has a unique string representation
2765      * as a result of using {@code toString}.  If that string
2766      * representation is converted back to a {@code BigDecimal} using
2767      * the {@link #BigDecimal(String)} constructor, then the original
2768      * value will be recovered.
2769      *
2770      * <li>The string produced for a given number is always the same;
2771      * it is not affected by locale.  This means that it can be used
2772      * as a canonical string representation for exchanging decimal
2773      * data, or as a key for a Hashtable, etc.  Locale-sensitive
2774      * number formatting and parsing is handled by the {@link
2775      * java.text.NumberFormat} class and its subclasses.
2776      *
2777      * <li>The {@link #toEngineeringString} method may be used for
2778      * presenting numbers with exponents in engineering notation, and the
2779      * {@link #setScale(int,RoundingMode) setScale} method may be used for
2780      * rounding a {@code BigDecimal} so it has a known number of digits after
2781      * the decimal point.
2782      *
2783      * <li>The digit-to-character mapping provided by
2784      * {@code Character.forDigit} is used.
2785      *
2786      * </ol>
2787      *
2788      * @return string representation of this {@code BigDecimal}.
2789      * @see    Character#forDigit
2790      * @see    #BigDecimal(java.lang.String)
2791      */
2792     @Override
2793     public String toString() {
2794         String sc = stringCache;
2795         if (sc == null)
2796             stringCache = sc = layoutChars(true);
2797         return sc;
2798     }
2799 
2800     /**
2801      * Returns a string representation of this {@code BigDecimal},
2802      * using engineering notation if an exponent is needed.
2803      *
2804      * <p>Returns a string that represents the {@code BigDecimal} as
2805      * described in the {@link #toString()} method, except that if
2806      * exponential notation is used, the power of ten is adjusted to
2807      * be a multiple of three (engineering notation) such that the
2808      * integer part of nonzero values will be in the range 1 through
2809      * 999.  If exponential notation is used for zero values, a
2810      * decimal point and one or two fractional zero digits are used so
2811      * that the scale of the zero value is preserved.  Note that
2812      * unlike the output of {@link #toString()}, the output of this
2813      * method is <em>not</em> guaranteed to recover the same [integer,
2814      * scale] pair of this {@code BigDecimal} if the output string is
2815      * converting back to a {@code BigDecimal} using the {@linkplain
2816      * #BigDecimal(String) string constructor}.  The result of this method meets
2817      * the weaker constraint of always producing a numerically equal
2818      * result from applying the string constructor to the method's output.
2819      *
2820      * @return string representation of this {@code BigDecimal}, using
2821      *         engineering notation if an exponent is needed.
2822      * @since  1.5
2823      */
2824     public String toEngineeringString() {
2825         return layoutChars(false);
2826     }
2827 
2828     /**
2829      * Returns a string representation of this {@code BigDecimal}
2830      * without an exponent field.  For values with a positive scale,
2831      * the number of digits to the right of the decimal point is used
2832      * to indicate scale.  For values with a zero or negative scale,
2833      * the resulting string is generated as if the value were
2834      * converted to a numerically equal value with zero scale and as
2835      * if all the trailing zeros of the zero scale value were present
2836      * in the result.
2837      *
2838      * The entire string is prefixed by a minus sign character '-'
2839      * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
2840      * zero. No sign character is prefixed if the unscaled value is
2841      * zero or positive.
2842      *
2843      * Note that if the result of this method is passed to the
2844      * {@linkplain #BigDecimal(String) string constructor}, only the
2845      * numerical value of this {@code BigDecimal} will necessarily be
2846      * recovered; the representation of the new {@code BigDecimal}
2847      * may have a different scale.  In particular, if this
2848      * {@code BigDecimal} has a negative scale, the string resulting
2849      * from this method will have a scale of zero when processed by
2850      * the string constructor.
2851      *
2852      * (This method behaves analogously to the {@code toString}
2853      * method in 1.4 and earlier releases.)
2854      *
2855      * @return a string representation of this {@code BigDecimal}
2856      * without an exponent field.
2857      * @since 1.5
2858      * @see #toString()
2859      * @see #toEngineeringString()
2860      */
2861     public String toPlainString() {
2862         BigDecimal bd = this;
2863         if (bd.scale < 0)
2864             bd = bd.setScale(0);
2865         bd.inflate();
2866         if (bd.scale == 0)      // No decimal point
2867             return bd.intVal.toString();
2868         return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
2869     }
2870 
2871     /* Returns a digit.digit string */
2872     private String getValueString(int signum, String intString, int scale) {
2873         /* Insert decimal point */
2874         StringBuilder buf;
2875         int insertionPoint = intString.length() - scale;
2876         if (insertionPoint == 0) {  /* Point goes right before intVal */
2877             return (signum<0 ? "-0." : "0.") + intString;
2878         } else if (insertionPoint > 0) { /* Point goes inside intVal */
2879             buf = new StringBuilder(intString);
2880             buf.insert(insertionPoint, '.');
2881             if (signum < 0)
2882                 buf.insert(0, '-');
2883         } else { /* We must insert zeros between point and intVal */
2884             buf = new StringBuilder(3-insertionPoint + intString.length());
2885             buf.append(signum<0 ? "-0." : "0.");
2886             for (int i=0; i<-insertionPoint; i++)
2887                 buf.append('0');
2888             buf.append(intString);
2889         }
2890         return buf.toString();
2891     }
2892 
2893     /**
2894      * Converts this {@code BigDecimal} to a {@code BigInteger}.
2895      * This conversion is analogous to a <a
2896      * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2897      * primitive conversion</i></a> from {@code double} to
2898      * {@code long} as defined in the <a
2899      * href="http://java.sun.com/docs/books/jls/html/">Java Language
2900      * Specification</a>: any fractional part of this
2901      * {@code BigDecimal} will be discarded.  Note that this
2902      * conversion can lose information about the precision of the
2903      * {@code BigDecimal} value.
2904      * <p>
2905      * To have an exception thrown if the conversion is inexact (in
2906      * other words if a nonzero fractional part is discarded), use the
2907      * {@link #toBigIntegerExact()} method.
2908      *
2909      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2910      */
2911     public BigInteger toBigInteger() {
2912         // force to an integer, quietly
2913         return this.setScale(0, ROUND_DOWN).inflate();
2914     }
2915 
2916     /**
2917      * Converts this {@code BigDecimal} to a {@code BigInteger},
2918      * checking for lost information.  An exception is thrown if this
2919      * {@code BigDecimal} has a nonzero fractional part.
2920      *
2921      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2922      * @throws ArithmeticException if {@code this} has a nonzero
2923      *         fractional part.
2924      * @since  1.5
2925      */
2926     public BigInteger toBigIntegerExact() {
2927         // round to an integer, with Exception if decimal part non-0
2928         return this.setScale(0, ROUND_UNNECESSARY).inflate();
2929     }
2930 
2931     /**
2932      * Converts this {@code BigDecimal} to a {@code long}.  This
2933      * conversion is analogous to a <a
2934      * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2935      * primitive conversion</i></a> from {@code double} to
2936      * {@code short} as defined in the <a
2937      * href="http://java.sun.com/docs/books/jls/html/">Java Language
2938      * Specification</a>: any fractional part of this
2939      * {@code BigDecimal} will be discarded, and if the resulting
2940      * "{@code BigInteger}" is too big to fit in a
2941      * {@code long}, only the low-order 64 bits are returned.
2942      * Note that this conversion can lose information about the
2943      * overall magnitude and precision of this {@code BigDecimal} value as well
2944      * as return a result with the opposite sign.
2945      *
2946      * @return this {@code BigDecimal} converted to a {@code long}.
2947      */
2948     public long longValue(){
2949         return (intCompact != INFLATED && scale == 0) ?
2950             intCompact:
2951             toBigInteger().longValue();
2952     }
2953 
2954     /**
2955      * Converts this {@code BigDecimal} to a {@code long}, checking
2956      * for lost information.  If this {@code BigDecimal} has a
2957      * nonzero fractional part or is out of the possible range for a
2958      * {@code long} result then an {@code ArithmeticException} is
2959      * thrown.
2960      *
2961      * @return this {@code BigDecimal} converted to a {@code long}.
2962      * @throws ArithmeticException if {@code this} has a nonzero
2963      *         fractional part, or will not fit in a {@code long}.
2964      * @since  1.5
2965      */
2966     public long longValueExact() {
2967         if (intCompact != INFLATED && scale == 0)
2968             return intCompact;
2969         // If more than 19 digits in integer part it cannot possibly fit
2970         if ((precision() - scale) > 19) // [OK for negative scale too]
2971             throw new java.lang.ArithmeticException("Overflow");
2972         // Fastpath zero and < 1.0 numbers (the latter can be very slow
2973         // to round if very small)
2974         if (this.signum() == 0)
2975             return 0;
2976         if ((this.precision() - this.scale) <= 0)
2977             throw new ArithmeticException("Rounding necessary");
2978         // round to an integer, with Exception if decimal part non-0
2979         BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
2980         if (num.precision() >= 19) // need to check carefully
2981             LongOverflow.check(num);
2982         return num.inflate().longValue();
2983     }
2984 
2985     private static class LongOverflow {
2986         /** BigInteger equal to Long.MIN_VALUE. */
2987         private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
2988 
2989         /** BigInteger equal to Long.MAX_VALUE. */
2990         private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
2991 
2992         public static void check(BigDecimal num) {
2993             num.inflate();
2994             if ((num.intVal.compareTo(LONGMIN) < 0) ||
2995                 (num.intVal.compareTo(LONGMAX) > 0))
2996                 throw new java.lang.ArithmeticException("Overflow");
2997         }
2998     }
2999 
3000     /**
3001      * Converts this {@code BigDecimal} to an {@code int}.  This
3002      * conversion is analogous to a <a
3003      * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
3004      * primitive conversion</i></a> from {@code double} to
3005      * {@code short} as defined in the <a
3006      * href="http://java.sun.com/docs/books/jls/html/">Java Language
3007      * Specification</a>: any fractional part of this
3008      * {@code BigDecimal} will be discarded, and if the resulting
3009      * "{@code BigInteger}" is too big to fit in an
3010      * {@code int}, only the low-order 32 bits are returned.
3011      * Note that this conversion can lose information about the
3012      * overall magnitude and precision of this {@code BigDecimal}
3013      * value as well as return a result with the opposite sign.
3014      *
3015      * @return this {@code BigDecimal} converted to an {@code int}.
3016      */
3017     public int intValue() {
3018         return  (intCompact != INFLATED && scale == 0) ?
3019             (int)intCompact :
3020             toBigInteger().intValue();
3021     }
3022 
3023     /**
3024      * Converts this {@code BigDecimal} to an {@code int}, checking
3025      * for lost information.  If this {@code BigDecimal} has a
3026      * nonzero fractional part or is out of the possible range for an
3027      * {@code int} result then an {@code ArithmeticException} is
3028      * thrown.
3029      *
3030      * @return this {@code BigDecimal} converted to an {@code int}.
3031      * @throws ArithmeticException if {@code this} has a nonzero
3032      *         fractional part, or will not fit in an {@code int}.
3033      * @since  1.5
3034      */
3035     public int intValueExact() {
3036        long num;
3037        num = this.longValueExact();     // will check decimal part
3038        if ((int)num != num)
3039            throw new java.lang.ArithmeticException("Overflow");
3040        return (int)num;
3041     }
3042 
3043     /**
3044      * Converts this {@code BigDecimal} to a {@code short}, checking
3045      * for lost information.  If this {@code BigDecimal} has a
3046      * nonzero fractional part or is out of the possible range for a
3047      * {@code short} result then an {@code ArithmeticException} is
3048      * thrown.
3049      *
3050      * @return this {@code BigDecimal} converted to a {@code short}.
3051      * @throws ArithmeticException if {@code this} has a nonzero
3052      *         fractional part, or will not fit in a {@code short}.
3053      * @since  1.5
3054      */
3055     public short shortValueExact() {
3056        long num;
3057        num = this.longValueExact();     // will check decimal part
3058        if ((short)num != num)
3059            throw new java.lang.ArithmeticException("Overflow");
3060        return (short)num;
3061     }
3062 
3063     /**
3064      * Converts this {@code BigDecimal} to a {@code byte}, checking
3065      * for lost information.  If this {@code BigDecimal} has a
3066      * nonzero fractional part or is out of the possible range for a
3067      * {@code byte} result then an {@code ArithmeticException} is
3068      * thrown.
3069      *
3070      * @return this {@code BigDecimal} converted to a {@code byte}.
3071      * @throws ArithmeticException if {@code this} has a nonzero
3072      *         fractional part, or will not fit in a {@code byte}.
3073      * @since  1.5
3074      */
3075     public byte byteValueExact() {
3076        long num;
3077        num = this.longValueExact();     // will check decimal part
3078        if ((byte)num != num)
3079            throw new java.lang.ArithmeticException("Overflow");
3080        return (byte)num;
3081     }
3082 
3083     /**
3084      * Converts this {@code BigDecimal} to a {@code float}.
3085      * This conversion is similar to the <a
3086      * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
3087      * primitive conversion</i></a> from {@code double} to
3088      * {@code float} defined in the <a
3089      * href="http://java.sun.com/docs/books/jls/html/">Java Language
3090      * Specification</a>: if this {@code BigDecimal} has too great a
3091      * magnitude to represent as a {@code float}, it will be
3092      * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3093      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3094      * the return value is finite, this conversion can lose
3095      * information about the precision of the {@code BigDecimal}
3096      * value.
3097      *
3098      * @return this {@code BigDecimal} converted to a {@code float}.
3099      */
3100     public float floatValue(){
3101         if (scale == 0 && intCompact != INFLATED)
3102                 return (float)intCompact;
3103         // Somewhat inefficient, but guaranteed to work.
3104         return Float.parseFloat(this.toString());
3105     }
3106 
3107     /**
3108      * Converts this {@code BigDecimal} to a {@code double}.
3109      * This conversion is similar to the <a
3110      * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
3111      * primitive conversion</i></a> from {@code double} to
3112      * {@code float} as defined in the <a
3113      * href="http://java.sun.com/docs/books/jls/html/">Java Language
3114      * Specification</a>: if this {@code BigDecimal} has too great a
3115      * magnitude represent as a {@code double}, it will be
3116      * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3117      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3118      * the return value is finite, this conversion can lose
3119      * information about the precision of the {@code BigDecimal}
3120      * value.
3121      *
3122      * @return this {@code BigDecimal} converted to a {@code double}.
3123      */
3124     public double doubleValue(){
3125         if (scale == 0 && intCompact != INFLATED)
3126             return (double)intCompact;
3127         // Somewhat inefficient, but guaranteed to work.
3128         return Double.parseDouble(this.toString());
3129     }
3130 
3131     /**
3132      * Returns the size of an ulp, a unit in the last place, of this
3133      * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3134      * value is the positive distance between this value and the
3135      * {@code BigDecimal} value next larger in magnitude with the
3136      * same number of digits.  An ulp of a zero value is numerically
3137      * equal to 1 with the scale of {@code this}.  The result is
3138      * stored with the same scale as {@code this} so the result
3139      * for zero and nonzero values is equal to {@code [1,
3140      * this.scale()]}.
3141      *
3142      * @return the size of an ulp of {@code this}
3143      * @since 1.5
3144      */
3145     public BigDecimal ulp() {
3146         return BigDecimal.valueOf(1, this.scale());
3147     }
3148 
3149     
3150     // Private class to build a string representation for BigDecimal object.
3151     // "StringBuilderHelper" is constructed as a thread local variable so it is
3152     // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3153     // representation of BigDecimal. The cmpCharArray holds all the characters for 
3154     // the compact representation of BigDecimal (except for '-' sign' if it is
3155     // negative) if its intCompact field is not INFLATED. It is shared by all
3156     // calls to toString() and its variants in that particular thread.
3157     static class StringBuilderHelper {
3158         final StringBuilder sb;    // Placeholder for BigDecimal string
3159         final char[] cmpCharArray; // character array to place the intCompact
3160 
3161         StringBuilderHelper() {
3162             sb = new StringBuilder();
3163             // All non negative longs can be made to fit into 19 character array.
3164             cmpCharArray = new char[19];
3165         }
3166 
3167         // Accessors.
3168         StringBuilder getStringBuilder() {
3169             sb.setLength(0);
3170             return sb;
3171         }
3172 
3173         char[] getCompactCharArray() {
3174             return cmpCharArray;
3175         }
3176         
3177         /**
3178          * Places characters representing the intCompact in {@code long} into
3179          * cmpCharArray and returns the offset to the array where the
3180          * representation starts.
3181          *
3182          * @param intCompact the number to put into the cmpCharArray.
3183          * @return offset to the array where the representation starts.
3184          * Note: intCompact must be greater or equal to zero.
3185          */
3186         int putIntCompact(long intCompact) {
3187             assert intCompact >= 0;
3188 
3189             long q;
3190             int r;
3191             // since we start from the least significant digit, charPos points to
3192             // the last character in cmpCharArray.
3193             int charPos = cmpCharArray.length;
3194 
3195             // Get 2 digits/iteration using longs until quotient fits into an int
3196             while (intCompact > Integer.MAX_VALUE) {
3197                 q = intCompact / 100;
3198                 r = (int)(intCompact - q * 100);
3199                 intCompact = q;
3200                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3201                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3202             }
3203 
3204             // Get 2 digits/iteration using ints when i2 >= 100
3205             int q2;
3206             int i2 = (int)intCompact;
3207             while (i2 >= 100) {
3208                 q2 = i2 / 100;
3209                 r  = i2 - q2 * 100;
3210                 i2 = q2;
3211                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3212                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3213             }
3214 
3215             cmpCharArray[--charPos] = DIGIT_ONES[i2];
3216             if (i2 >= 10)
3217                 cmpCharArray[--charPos] = DIGIT_TENS[i2];
3218             
3219             return charPos;
3220         }
3221         
3222         final static char[] DIGIT_TENS = {
3223             '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
3224             '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
3225             '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
3226             '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
3227             '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
3228             '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
3229             '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
3230             '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
3231             '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
3232             '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
3233         };
3234         
3235         final static char[] DIGIT_ONES = {
3236             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3237             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3238             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3239             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3240             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3241             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3242             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3243             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3244             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3245             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3246         };
3247     }
3248 
3249     /**
3250      * Lay out this {@code BigDecimal} into a {@code char[]} array.
3251      * The Java 1.2 equivalent to this was called {@code getValueString}.
3252      *
3253      * @param  sci {@code true} for Scientific exponential notation;
3254      *          {@code false} for Engineering
3255      * @return string with canonical string representation of this
3256      *         {@code BigDecimal}
3257      */
3258     private String layoutChars(boolean sci) {
3259         if (scale == 0)                      // zero scale is trivial
3260             return (intCompact != INFLATED) ?
3261                 Long.toString(intCompact):
3262                 intVal.toString();
3263         
3264         StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
3265         char[] coeff;
3266         int offset;  // offset is the starting index for coeff array
3267         // Get the significand as an absolute value
3268         if (intCompact != INFLATED) {
3269             offset = sbHelper.putIntCompact(Math.abs(intCompact));
3270             coeff  = sbHelper.getCompactCharArray();
3271         } else {
3272             offset = 0;
3273             coeff  = intVal.abs().toString().toCharArray();
3274         }
3275         
3276         // Construct a buffer, with sufficient capacity for all cases.
3277         // If E-notation is needed, length will be: +1 if negative, +1
3278         // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3279         // Otherwise it could have +1 if negative, plus leading "0.00000"
3280         StringBuilder buf = sbHelper.getStringBuilder();
3281         if (signum() < 0)             // prefix '-' if negative
3282             buf.append('-');
3283         int coeffLen = coeff.length - offset;
3284         long adjusted = -(long)scale + (coeffLen -1);
3285         if ((scale >= 0) && (adjusted >= -6)) { // plain number
3286             int pad = scale - coeffLen;         // count of padding zeros
3287             if (pad >= 0) {                     // 0.xxx form
3288                 buf.append('0');
3289                 buf.append('.');
3290                 for (; pad>0; pad--) {
3291                     buf.append('0');
3292                 }
3293                 buf.append(coeff, offset, coeffLen);
3294             } else {                         // xx.xx form
3295                 buf.append(coeff, offset, -pad);
3296                 buf.append('.');
3297                 buf.append(coeff, -pad + offset, scale);
3298             }
3299         } else { // E-notation is needed
3300             if (sci) {                       // Scientific notation
3301                 buf.append(coeff[offset]);   // first character
3302                 if (coeffLen > 1) {          // more to come
3303                     buf.append('.');
3304                     buf.append(coeff, offset + 1, coeffLen - 1);
3305                 }
3306             } else {                         // Engineering notation
3307                 int sig = (int)(adjusted % 3);
3308                 if (sig < 0)
3309                     sig += 3;                // [adjusted was negative]
3310                 adjusted -= sig;             // now a multiple of 3
3311                 sig++;
3312                 if (signum() == 0) {
3313                     switch (sig) {
3314                     case 1:
3315                         buf.append('0'); // exponent is a multiple of three
3316                         break;
3317                     case 2:
3318                         buf.append("0.00");
3319                         adjusted += 3;
3320                         break;
3321                     case 3:
3322                         buf.append("0.0");
3323                         adjusted += 3;
3324                         break;
3325                     default:
3326                         throw new AssertionError("Unexpected sig value " + sig);
3327                     }
3328                 } else if (sig >= coeffLen) {   // significand all in integer
3329                     buf.append(coeff, offset, coeffLen);
3330                     // may need some zeros, too
3331                     for (int i = sig - coeffLen; i > 0; i--)
3332                         buf.append('0');
3333                 } else {                     // xx.xxE form
3334                     buf.append(coeff, offset, sig);
3335                     buf.append('.');
3336                     buf.append(coeff, offset + sig, coeffLen - sig);
3337                 }
3338             }
3339             if (adjusted != 0) {             // [!sci could have made 0]
3340                 buf.append('E');
3341                 if (adjusted > 0)            // force sign for positive
3342                     buf.append('+');
3343                 buf.append(adjusted);
3344             }
3345         }
3346         return buf.toString();
3347     }
3348     
3349     /**
3350      * Return 10 to the power n, as a {@code BigInteger}.
3351      *
3352      * @param  n the power of ten to be returned (>=0)
3353      * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3354      */
3355     private static BigInteger bigTenToThe(int n) {
3356         if (n < 0)
3357             return BigInteger.ZERO;
3358 
3359         if (n < BIG_TEN_POWERS_TABLE_MAX) {
3360             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3361             if (n < pows.length)
3362                 return pows[n];
3363             else
3364                 return expandBigIntegerTenPowers(n);
3365         }
3366         // BigInteger.pow is slow, so make 10**n by constructing a
3367         // BigInteger from a character string (still not very fast)
3368         char tenpow[] = new char[n + 1];
3369         tenpow[0] = '1';
3370         for (int i = 1; i <= n; i++)
3371             tenpow[i] = '0';
3372         return new BigInteger(tenpow);
3373     }
3374 
3375     /**
3376      * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3377      *
3378      * @param n the power of ten to be returned (>=0)
3379      * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3380      *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
3381      *         expanded to the size greater than n.
3382      */
3383     private static BigInteger expandBigIntegerTenPowers(int n) {
3384         synchronized(BigDecimal.class) {
3385             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3386             int curLen = pows.length;
3387             // The following comparison and the above synchronized statement is
3388             // to prevent multiple threads from expanding the same array.
3389             if (curLen <= n) {
3390                 int newLen = curLen << 1;
3391                 while (newLen <= n)
3392                     newLen <<= 1;
3393                 pows = Arrays.copyOf(pows, newLen);
3394                 for (int i = curLen; i < newLen; i++)
3395                     pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3396                 // Based on the following facts:
3397                 // 1. pows is a private local varible;
3398                 // 2. the following store is a volatile store.
3399                 // the newly created array elements can be safely published.
3400                 BIG_TEN_POWERS_TABLE = pows;
3401             }
3402             return pows[n];
3403         }
3404     }
3405     
3406     private static final long[] LONG_TEN_POWERS_TABLE = {
3407         1,                     // 0 / 10^0
3408         10,                    // 1 / 10^1
3409         100,                   // 2 / 10^2
3410         1000,                  // 3 / 10^3
3411         10000,                 // 4 / 10^4
3412         100000,                // 5 / 10^5
3413         1000000,               // 6 / 10^6
3414         10000000,              // 7 / 10^7
3415         100000000,             // 8 / 10^8
3416         1000000000,            // 9 / 10^9
3417         10000000000L,          // 10 / 10^10
3418         100000000000L,         // 11 / 10^11
3419         1000000000000L,        // 12 / 10^12
3420         10000000000000L,       // 13 / 10^13
3421         100000000000000L,      // 14 / 10^14
3422         1000000000000000L,     // 15 / 10^15
3423         10000000000000000L,    // 16 / 10^16
3424         100000000000000000L,   // 17 / 10^17
3425         1000000000000000000L   // 18 / 10^18
3426     };
3427     
3428     private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
3429         BigInteger.valueOf(10),       BigInteger.valueOf(100),
3430         BigInteger.valueOf(1000),     BigInteger.valueOf(10000),
3431         BigInteger.valueOf(100000),   BigInteger.valueOf(1000000),
3432         BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
3433         BigInteger.valueOf(1000000000),
3434         BigInteger.valueOf(10000000000L),
3435         BigInteger.valueOf(100000000000L),
3436         BigInteger.valueOf(1000000000000L),
3437         BigInteger.valueOf(10000000000000L),
3438         BigInteger.valueOf(100000000000000L),
3439         BigInteger.valueOf(1000000000000000L),
3440         BigInteger.valueOf(10000000000000000L),
3441         BigInteger.valueOf(100000000000000000L),
3442         BigInteger.valueOf(1000000000000000000L)     
3443     };
3444 
3445     private static final int BIG_TEN_POWERS_TABLE_INITLEN = 
3446         BIG_TEN_POWERS_TABLE.length;
3447     private static final int BIG_TEN_POWERS_TABLE_MAX =
3448         16 * BIG_TEN_POWERS_TABLE_INITLEN;
3449     
3450     private static final long THRESHOLDS_TABLE[] = {
3451         Long.MAX_VALUE,                     // 0
3452         Long.MAX_VALUE/10L,                 // 1        
3453         Long.MAX_VALUE/100L,                // 2  
3454         Long.MAX_VALUE/1000L,               // 3   
3455         Long.MAX_VALUE/10000L,              // 4
3456         Long.MAX_VALUE/100000L,             // 5 
3457         Long.MAX_VALUE/1000000L,            // 6                
3458         Long.MAX_VALUE/10000000L,           // 7                
3459         Long.MAX_VALUE/100000000L,          // 8                
3460         Long.MAX_VALUE/1000000000L,         // 9   
3461         Long.MAX_VALUE/10000000000L,        // 10   
3462         Long.MAX_VALUE/100000000000L,       // 11               
3463         Long.MAX_VALUE/1000000000000L,      // 12
3464         Long.MAX_VALUE/10000000000000L,     // 13
3465         Long.MAX_VALUE/100000000000000L,    // 14
3466         Long.MAX_VALUE/1000000000000000L,   // 15
3467         Long.MAX_VALUE/10000000000000000L,  // 16
3468         Long.MAX_VALUE/100000000000000000L, // 17
3469         Long.MAX_VALUE/1000000000000000000L // 18
3470     };
3471     
3472     /**
3473      * Compute val * 10 ^ n; return this product if it is
3474      * representable as a long, INFLATED otherwise.
3475      */
3476     private static long longMultiplyPowerTen(long val, int n) {
3477         if (val == 0 || n <= 0)
3478             return val;
3479         long[] tab = LONG_TEN_POWERS_TABLE;
3480         long[] bounds = THRESHOLDS_TABLE;
3481         if (n < tab.length && n < bounds.length) {
3482             long tenpower = tab[n];
3483             if (val == 1)
3484                 return tenpower;
3485             if (Math.abs(val) <= bounds[n])
3486                 return val * tenpower;
3487         }
3488         return INFLATED;
3489     }
3490 
3491     /**
3492      * Compute this * 10 ^ n.
3493      * Needed mainly to allow special casing to trap zero value
3494      */
3495     private BigInteger bigMultiplyPowerTen(int n) {
3496         if (n <= 0)
3497             return this.inflate();
3498         
3499         if (intCompact != INFLATED)
3500             return bigTenToThe(n).multiply(intCompact);
3501         else
3502             return intVal.multiply(bigTenToThe(n));
3503     }
3504 
3505     /**
3506      * Assign appropriate BigInteger to intVal field if intVal is
3507      * null, i.e. the compact representation is in use.
3508      */
3509     private BigInteger inflate() {
3510         if (intVal == null)
3511             intVal = BigInteger.valueOf(intCompact);
3512         return intVal;
3513     }
3514 
3515     /**
3516      * Match the scales of two {@code BigDecimal}s to align their
3517      * least significant digits.
3518      * 
3519      * <p>If the scales of val[0] and val[1] differ, rescale
3520      * (non-destructively) the lower-scaled {@code BigDecimal} so
3521      * they match.  That is, the lower-scaled reference will be
3522      * replaced by a reference to a new object with the same scale as
3523      * the other {@code BigDecimal}.
3524      *
3525      * @param  val array of two elements referring to the two
3526      *         {@code BigDecimal}s to be aligned.
3527      */
3528     private static void matchScale(BigDecimal[] val) {
3529         if (val[0].scale == val[1].scale) {
3530             return;
3531         } else if (val[0].scale < val[1].scale) {
3532             val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3533         } else if (val[1].scale < val[0].scale) {
3534             val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3535         }
3536     }
3537 
3538     /**
3539      * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3540      * deserialize it).
3541      *
3542      * @param s the stream being read.
3543      */
3544     private void readObject(java.io.ObjectInputStream s)
3545         throws java.io.IOException, ClassNotFoundException {
3546         // Read in all fields
3547         s.defaultReadObject();
3548         // validate possibly bad fields
3549         if (intVal == null) {
3550             String message = "BigDecimal: null intVal in stream";
3551             throw new java.io.StreamCorruptedException(message);
3552         // [all values of scale are now allowed]
3553         }
3554         intCompact = compactValFor(intVal);
3555     }
3556 
3557    /**
3558     * Serialize this {@code BigDecimal} to the stream in question
3559     *
3560     * @param s the stream to serialize to.
3561     */
3562    private void writeObject(java.io.ObjectOutputStream s)
3563        throws java.io.IOException {
3564        // Must inflate to maintain compatible serial form.
3565        this.inflate();
3566 
3567        // Write proper fields
3568        s.defaultWriteObject();
3569    }
3570 
3571    
3572     /**
3573      * Returns the length of the absolute value of a {@code long}, in decimal
3574      * digits.
3575      * 
3576      * @param x the {@code long}
3577      * @return the length of the unscaled value, in deciaml digits.
3578      */
3579     private static int longDigitLength(long x) {
3580         /*
3581          * As described in "Bit Twiddling Hacks" by Sean Anderson,
3582          * (http://graphics.stanford.edu/~seander/bithacks.html)
3583          * integer log 10 of x is within 1 of 
3584          * (1233/4096)* (1 + integer log 2 of x).
3585          * The fraction 1233/4096 approximates log10(2). So we first
3586          * do a version of log2 (a variant of Long class with
3587          * pre-checks and opposite directionality) and then scale and
3588          * check against powers table. This is a little simpler in
3589          * present context than the version in Hacker's Delight sec
3590          * 11-4.  Adding one to bit length allows comparing downward
3591          * from the LONG_TEN_POWERS_TABLE that we need anyway.
3592          */
3593         assert x != INFLATED;
3594         if (x < 0)
3595             x = -x;
3596         if (x < 10) // must screen for 0, might as well 10
3597             return 1;
3598         int n = 64; // not 63, to avoid needing to add 1 later
3599         int y = (int)(x >>> 32);
3600         if (y == 0) { n -= 32; y = (int)x; }
3601         if (y >>> 16 == 0) { n -= 16; y <<= 16; }
3602         if (y >>> 24 == 0) { n -=  8; y <<=  8; }
3603         if (y >>> 28 == 0) { n -=  4; y <<=  4; }
3604         if (y >>> 30 == 0) { n -=  2; y <<=  2; }
3605         int r = (((y >>> 31) + n) * 1233) >>> 12;
3606         long[] tab = LONG_TEN_POWERS_TABLE;
3607         // if r >= length, must have max possible digits for long
3608         return (r >= tab.length || x < tab[r])? r : r+1;
3609     }
3610 
3611     /**
3612      * Returns the length of the absolute value of a BigInteger, in
3613      * decimal digits.
3614      *
3615      * @param b the BigInteger
3616      * @return the length of the unscaled value, in decimal digits
3617      */
3618     private static int bigDigitLength(BigInteger b) {
3619         /*
3620          * Same idea as the long version, but we need a better
3621          * approximation of log10(2). Using 646456993/2^31
3622          * is accurate up to max possible reported bitLength.
3623          */
3624         if (b.signum == 0)
3625             return 1;
3626         int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3627         return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3628     }
3629 
3630     
3631     /**
3632      * Remove insignificant trailing zeros from this
3633      * {@code BigDecimal} until the preferred scale is reached or no
3634      * more zeros can be removed.  If the preferred scale is less than
3635      * Integer.MIN_VALUE, all the trailing zeros will be removed.
3636      *
3637      * {@code BigInteger} assistance could help, here?
3638      *
3639      * <p>WARNING: This method should only be called on new objects as
3640      * it mutates the value fields.
3641      *
3642      * @return this {@code BigDecimal} with a scale possibly reduced
3643      * to be closed to the preferred scale.
3644      */
3645     private BigDecimal stripZerosToMatchScale(long preferredScale) {
3646         boolean compact = (intCompact != INFLATED);
3647         this.inflate();
3648         BigInteger qr[];                // quotient-remainder pair
3649         while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
3650                 scale > preferredScale) {
3651             if (intVal.testBit(0))
3652                 break;                  // odd number cannot end in 0
3653             qr = intVal.divideAndRemainder(BigInteger.TEN);
3654             if (qr[1].signum() != 0)
3655                 break;                  // non-0 remainder
3656             intVal=qr[0];
3657             scale = checkScale((long)scale-1);  // could Overflow
3658             if (precision > 0)          // adjust precision if known
3659               precision--;
3660         }
3661         if (intVal != null)
3662             intCompact = compactValFor(intVal);
3663         return this;
3664     }
3665     
3666     /**
3667      * Check a scale for Underflow or Overflow.  If this BigDecimal is
3668      * nonzero, throw an exception if the scale is outof range. If this 
3669      * is zero, saturate the scale to the extreme value of the right
3670      * sign if the scale is out of range.
3671      *
3672      * @param val The new scale.
3673      * @throws ArithmeticException (overflow or underflow) if the new
3674      *         scale is out of range.
3675      * @return validated scale as an int.
3676      */
3677     private int checkScale(long val) {
3678         int asInt = (int)val;
3679         if (asInt != val) {
3680             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3681             BigInteger b;
3682             if (intCompact != 0 &&
3683                 ((b = intVal) == null || b.signum() != 0))
3684                 throw new ArithmeticException(asInt>0 ? "Undeflow":"Overflow");
3685         }
3686         return asInt;
3687     }
3688     
3689     /**
3690      * Round an operand; used only if digits &gt; 0.  Does not change
3691      * {@code this}; if rounding is needed a new {@code BigDecimal}
3692      * is created and returned.
3693      *
3694      * @param mc the context to use.
3695      * @throws ArithmeticException if the result is inexact but the
3696      *         rounding mode is {@code UNNECESSARY}.
3697      */
3698     private BigDecimal roundOp(MathContext mc) {
3699         BigDecimal rounded = doRound(this, mc);
3700         return rounded;
3701     }
3702 
3703     /** Round this BigDecimal according to the MathContext settings;
3704      *  used only if precision {@literal >} 0.
3705      *
3706      * <p>WARNING: This method should only be called on new objects as
3707      * it mutates the value fields.
3708      *
3709      * @param mc the context to use.
3710      * @throws ArithmeticException if the rounding mode is
3711      *         {@code RoundingMode.UNNECESSARY} and the
3712      *         {@code BigDecimal} operation would require rounding.
3713      */
3714     private void roundThis(MathContext mc) {
3715         BigDecimal rounded = doRound(this, mc);
3716         if (rounded == this)                 // wasn't rounded
3717             return;
3718         this.intVal     = rounded.intVal;
3719         this.intCompact = rounded.intCompact;
3720         this.scale      = rounded.scale;
3721         this.precision  = rounded.precision;
3722     }
3723 
3724     /**
3725      * Returns a {@code BigDecimal} rounded according to the
3726      * MathContext settings; used only if {@code mc.precision > 0}.
3727      * Does not change {@code this}; if rounding is needed a new
3728      * {@code BigDecimal} is created and returned.
3729      *
3730      * @param mc the context to use.
3731      * @return a {@code BigDecimal} rounded according to the MathContext
3732      *         settings.  May return this, if no rounding needed.
3733      * @throws ArithmeticException if the rounding mode is
3734      *         {@code RoundingMode.UNNECESSARY} and the
3735      *         result is inexact.
3736      */
3737     private static BigDecimal doRound(BigDecimal d, MathContext mc) {
3738         int mcp = mc.precision;
3739         int drop;
3740         // This might (rarely) iterate to cover the 999=>1000 case
3741         while ((drop = d.precision() - mcp) > 0) {
3742             int newScale = d.checkScale((long)d.scale - drop);
3743             int mode = mc.roundingMode.oldMode;
3744             if (drop < LONG_TEN_POWERS_TABLE.length)
3745                 d = divideAndRound(d.intCompact, d.intVal,
3746                                    LONG_TEN_POWERS_TABLE[drop], null,
3747                                    newScale, mode, newScale);
3748             else
3749                 d = divideAndRound(d.intCompact, d.intVal,
3750                                    INFLATED, bigTenToThe(drop),
3751                                    newScale, mode, newScale);
3752         }
3753         return d;
3754     }
3755 
3756     /**
3757      * Returns the compact value for given {@code BigInteger}, or
3758      * INFLATED if too big. Relies on internal representation of
3759      * {@code BigInteger}.
3760      */
3761     private static long compactValFor(BigInteger b) {
3762         int[] m = b.mag;
3763         int len = m.length;
3764         if (len == 0)
3765             return 0;
3766         int d = m[0];
3767         if (len > 2 || (len == 2 && d < 0))
3768             return INFLATED;
3769 
3770         long u = (len == 2)?
3771             (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3772             (((long)d)   & LONG_MASK);
3773         return (b.signum < 0)? -u : u;
3774     }
3775 
3776     private static int longCompareMagnitude(long x, long y) {
3777         if (x < 0)
3778             x = -x;
3779         if (y < 0)
3780             y = -y;
3781         return (x < y) ? -1 : ((x == y) ? 0 : 1);
3782     }
3783 
3784     private static int saturateLong(long s) {
3785         int i = (int)s;
3786         return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); 
3787     }
3788     
3789     /*
3790      * Internal printing routine
3791      */
3792     private static void print(String name, BigDecimal bd) {
3793         System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
3794                           name,
3795                           bd.intCompact,
3796                           bd.intVal,
3797                           bd.scale,
3798                           bd.precision);
3799     }
3800 
3801     /**
3802      * Check internal invariants of this BigDecimal.  These invariants
3803      * include:
3804      *
3805      * <ul>
3806      *
3807      * <li>The object must be initialized; either intCompact must not be
3808      * INFLATED or intVal is non-null.  Both of these conditions may
3809      * be true.
3810      *
3811      * <li>If both intCompact and intVal and set, their values must be
3812      * consistent.
3813      * 
3814      * <li>If precision is nonzero, it must have the right value.
3815      * </ul>
3816      * 
3817      * Note: Since this is an audit method, we are not supposed to change the
3818      * state of this BigDecimal object.
3819      */
3820     private BigDecimal audit() {
3821         if (intCompact == INFLATED) {
3822             if (intVal == null) {
3823                 print("audit", this);
3824                 throw new AssertionError("null intVal");
3825             }
3826             // Check precision
3827             if (precision > 0 && precision != bigDigitLength(intVal)) {
3828                 print("audit", this);
3829                 throw new AssertionError("precision mismatch");
3830             }
3831         } else {
3832             if (intVal != null) {
3833                 long val = intVal.longValue();
3834                 if (val != intCompact) {
3835                     print("audit", this);
3836                     throw new AssertionError("Inconsistent state, intCompact=" + 
3837                                              intCompact + "\t intVal=" + val);
3838                 }
3839             }
3840             // Check precision
3841             if (precision > 0 && precision != longDigitLength(intCompact)) {
3842                 print("audit", this);
3843                 throw new AssertionError("precision mismatch");
3844             }
3845         }
3846         return this;
3847     }
3848 }