1 /*
   2  * Copyright (c) 1996, 2011, Oracle and/or its affiliates. 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * 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><b>Preferred Scales for Results of Arithmetic Operations
 125  * </b></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  * @author  Sergey V. Kuksenko
 219  */
 220 public class BigDecimal extends Number implements Comparable<BigDecimal> {
 221     /**
 222      * The unscaled value of this BigDecimal, as returned by {@link
 223      * #unscaledValue}.
 224      *
 225      * @serial
 226      * @see #unscaledValue
 227      */
 228     private final BigInteger intVal;
 229 
 230     /**
 231      * The scale of this BigDecimal, as returned by {@link #scale}.
 232      *
 233      * @serial
 234      * @see #scale
 235      */
 236     private final int scale;  // Note: this may have any value, so
 237                               // calculations must be done in longs
 238 
 239     /**
 240      * The number of decimal digits in this BigDecimal, or 0 if the
 241      * number of digits are not known (lookaside information).  If
 242      * nonzero, the value is guaranteed correct.  Use the precision()
 243      * method to obtain and set the value if it might be 0.  This
 244      * field is mutable until set nonzero.
 245      *
 246      * @since  1.5
 247      */
 248     private transient int precision;
 249 
 250     /**
 251      * Used to store the canonical string representation, if computed.
 252      */
 253     private transient String stringCache;
 254 
 255     /**
 256      * Sentinel value for {@link #intCompact} indicating the
 257      * significand information is only available from {@code intVal}.
 258      */
 259     static final long INFLATED = Long.MIN_VALUE;
 260 
 261     private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);
 262 
 263     /**
 264      * If the absolute value of the significand of this BigDecimal is
 265      * less than or equal to {@code Long.MAX_VALUE}, the value can be
 266      * compactly stored in this field and used in computations.
 267      */
 268     private final transient long intCompact;
 269 
 270     // All 18-digit base ten strings fit into a long; not all 19-digit
 271     // strings will
 272     private static final int MAX_COMPACT_DIGITS = 18;
 273 
 274     /* Appease the serialization gods */
 275     private static final long serialVersionUID = 6108874887143696463L;
 276 
 277     private static final ThreadLocal<StringBuilderHelper>
 278         threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
 279         @Override
 280         protected StringBuilderHelper initialValue() {
 281             return new StringBuilderHelper();
 282         }
 283     };
 284 
 285     // Cache of common small BigDecimal values.
 286     private static final BigDecimal zeroThroughTen[] = {
 287         new BigDecimal(BigInteger.ZERO,       0,  0, 1),
 288         new BigDecimal(BigInteger.ONE,        1,  0, 1),
 289         new BigDecimal(BigInteger.valueOf(2), 2,  0, 1),
 290         new BigDecimal(BigInteger.valueOf(3), 3,  0, 1),
 291         new BigDecimal(BigInteger.valueOf(4), 4,  0, 1),
 292         new BigDecimal(BigInteger.valueOf(5), 5,  0, 1),
 293         new BigDecimal(BigInteger.valueOf(6), 6,  0, 1),
 294         new BigDecimal(BigInteger.valueOf(7), 7,  0, 1),
 295         new BigDecimal(BigInteger.valueOf(8), 8,  0, 1),
 296         new BigDecimal(BigInteger.valueOf(9), 9,  0, 1),
 297         new BigDecimal(BigInteger.TEN,        10, 0, 2),
 298     };
 299 
 300     // Cache of zero scaled by 0 - 15
 301     private static final BigDecimal[] ZERO_SCALED_BY = {
 302         zeroThroughTen[0],
 303         new BigDecimal(BigInteger.ZERO, 0, 1, 1),
 304         new BigDecimal(BigInteger.ZERO, 0, 2, 1),
 305         new BigDecimal(BigInteger.ZERO, 0, 3, 1),
 306         new BigDecimal(BigInteger.ZERO, 0, 4, 1),
 307         new BigDecimal(BigInteger.ZERO, 0, 5, 1),
 308         new BigDecimal(BigInteger.ZERO, 0, 6, 1),
 309         new BigDecimal(BigInteger.ZERO, 0, 7, 1),
 310         new BigDecimal(BigInteger.ZERO, 0, 8, 1),
 311         new BigDecimal(BigInteger.ZERO, 0, 9, 1),
 312         new BigDecimal(BigInteger.ZERO, 0, 10, 1),
 313         new BigDecimal(BigInteger.ZERO, 0, 11, 1),
 314         new BigDecimal(BigInteger.ZERO, 0, 12, 1),
 315         new BigDecimal(BigInteger.ZERO, 0, 13, 1),
 316         new BigDecimal(BigInteger.ZERO, 0, 14, 1),
 317         new BigDecimal(BigInteger.ZERO, 0, 15, 1),
 318     };
 319 
 320     // Half of Long.MIN_VALUE & Long.MAX_VALUE.
 321     private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
 322     private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
 323 
 324     // Constants
 325     /**
 326      * The value 0, with a scale of 0.
 327      *
 328      * @since  1.5
 329      */
 330     public static final BigDecimal ZERO =
 331         zeroThroughTen[0];
 332 
 333     /**
 334      * The value 1, with a scale of 0.
 335      *
 336      * @since  1.5
 337      */
 338     public static final BigDecimal ONE =
 339         zeroThroughTen[1];
 340 
 341     /**
 342      * The value 10, with a scale of 0.
 343      *
 344      * @since  1.5
 345      */
 346     public static final BigDecimal TEN =
 347         zeroThroughTen[10];
 348 
 349     // Constructors
 350 
 351     /**
 352      * Trusted package private constructor.
 353      * Trusted simply means if val is INFLATED, intVal could not be null and
 354      * if intVal is null, val could not be INFLATED.
 355      */
 356     BigDecimal(BigInteger intVal, long val, int scale, int prec) {
 357         this.scale = scale;
 358         this.precision = prec;
 359         this.intCompact = val;
 360         this.intVal = intVal;
 361     }
 362 
 363     /**
 364      * Translates a character array representation of a
 365      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 366      * same sequence of characters as the {@link #BigDecimal(String)}
 367      * constructor, while allowing a sub-array to be specified.
 368      *
 369      * <p>Note that if the sequence of characters is already available
 370      * within a character array, using this constructor is faster than
 371      * converting the {@code char} array to string and using the
 372      * {@code BigDecimal(String)} constructor .
 373      *
 374      * @param  in {@code char} array that is the source of characters.
 375      * @param  offset first character in the array to inspect.
 376      * @param  len number of characters to consider.
 377      * @throws NumberFormatException if {@code in} is not a valid
 378      *         representation of a {@code BigDecimal} or the defined subarray
 379      *         is not wholly within {@code in}.
 380      * @since  1.5
 381      */
 382     public BigDecimal(char[] in, int offset, int len) {
 383         this(in,offset,len,MathContext.UNLIMITED);
 384     }
 385 
 386     /**
 387      * Translates a character array representation of a
 388      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 389      * same sequence of characters as the {@link #BigDecimal(String)}
 390      * constructor, while allowing a sub-array to be specified and
 391      * with rounding according to the context settings.
 392      *
 393      * <p>Note that if the sequence of characters is already available
 394      * within a character array, using this constructor is faster than
 395      * converting the {@code char} array to string and using the
 396      * {@code BigDecimal(String)} constructor .
 397      *
 398      * @param  in {@code char} array that is the source of characters.
 399      * @param  offset first character in the array to inspect.
 400      * @param  len number of characters to consider..
 401      * @param  mc the context to use.
 402      * @throws ArithmeticException if the result is inexact but the
 403      *         rounding mode is {@code UNNECESSARY}.
 404      * @throws NumberFormatException if {@code in} is not a valid
 405      *         representation of a {@code BigDecimal} or the defined subarray
 406      *         is not wholly within {@code in}.
 407      * @since  1.5
 408      */
 409     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
 410         // protect against huge length.
 411         if (offset + len > in.length || offset < 0)
 412             throw new NumberFormatException("Bad offset or len arguments for char[] input.");
 413         // This is the primary string to BigDecimal constructor; all
 414         // incoming strings end up here; it uses explicit (inline)
 415         // parsing for speed and generates at most one intermediate
 416         // (temporary) object (a char[] array) for non-compact case.
 417 
 418         // Use locals for all fields values until completion
 419         int prec = 0;                 // record precision value
 420         int scl = 0;                  // record scale value
 421         long rs = 0;                  // the compact value in long
 422         BigInteger rb = null;         // the inflated value in BigInteger
 423         // use array bounds checking to handle too-long, len == 0,
 424         // bad offset, etc.
 425         try {
 426             // handle the sign
 427             boolean isneg = false;          // assume positive
 428             if (in[offset] == '-') {
 429                 isneg = true;               // leading minus means negative
 430                 offset++;
 431                 len--;
 432             } else if (in[offset] == '+') { // leading + allowed
 433                 offset++;
 434                 len--;
 435             }
 436 
 437             // should now be at numeric part of the significand
 438             boolean dot = false;             // true when there is a '.'
 439             long exp = 0;                    // exponent
 440             char c;                          // current character
 441             boolean isCompact = (len <= MAX_COMPACT_DIGITS);
 442             // integer significand array & idx is the index to it. The array
 443             // is ONLY used when we can't use a compact representation.
 444             int idx = 0;
 445             if (isCompact) {
 446                 // First compact case, we need not to preserve the character
 447                 // and we can just compute the value in place.
 448                 for (; len > 0; offset++, len--) {
 449                     c = in[offset];
 450                     if ((c == '0')) { // have zero
 451                         if (prec == 0)
 452                             prec = 1;
 453                         else if (rs != 0) {
 454                             rs *= 10;
 455                             ++prec;
 456                         } // else digit is a redundant leading zero
 457                         if (dot)
 458                             ++scl;
 459                     } else if ((c >= '1' && c <= '9')) { // have digit
 460                         int digit = c - '0';
 461                         if (prec != 1 || rs != 0)
 462                             ++prec; // prec unchanged if preceded by 0s
 463                         rs = rs * 10 + digit;
 464                         if (dot)
 465                             ++scl;
 466                     } else if (c == '.') {   // have dot
 467                         // have dot
 468                         if (dot) // two dots
 469                             throw new NumberFormatException();
 470                         dot = true;
 471                     } else if (Character.isDigit(c)) { // slow path
 472                         int digit = Character.digit(c, 10);
 473                         if (digit == 0) {
 474                             if (prec == 0)
 475                                 prec = 1;
 476                             else if (rs != 0) {
 477                                 rs *= 10;
 478                                 ++prec;
 479                             } // else digit is a redundant leading zero
 480                         } else {
 481                             if (prec != 1 || rs != 0)
 482                                 ++prec; // prec unchanged if preceded by 0s
 483                             rs = rs * 10 + digit;
 484                         }
 485                         if (dot)
 486                             ++scl;
 487                     } else if ((c == 'e') || (c == 'E')) {
 488                         exp = parseExp(in, offset, len);
 489                         // Next test is required for backwards compatibility
 490                         if ((int) exp != exp) // overflow
 491                             throw new NumberFormatException();
 492                         break; // [saves a test]
 493                     } else {
 494                         throw new NumberFormatException();
 495                     }
 496                 }
 497                 if (prec == 0) // no digits found
 498                     throw new NumberFormatException();
 499                 // Adjust scale if exp is not zero.
 500                 if (exp != 0) { // had significant exponent
 501                     scl = adjustScale(scl, exp);
 502                 }
 503                 rs = isneg ? -rs : rs;
 504                 int mcp = mc.precision;
 505                 int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];
 506                                        // therefore, this subtract cannot overflow
 507                 if (mcp > 0 && drop > 0) {  // do rounding
 508                     while (drop > 0) {
 509                         scl = checkScaleNonZero((long) scl - drop);
 510                         rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 511                         prec = longDigitLength(rs);
 512                         drop = prec - mcp;
 513                     }
 514                 }
 515             } else {
 516                 char coeff[] = new char[len];
 517                 for (; len > 0; offset++, len--) {
 518                     c = in[offset];
 519                     // have digit
 520                     if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
 521                         // First compact case, we need not to preserve the character
 522                         // and we can just compute the value in place.
 523                         if (c == '0' || Character.digit(c, 10) == 0) {
 524                             if (prec == 0) {
 525                                 coeff[idx] = c;
 526                                 prec = 1;
 527                             } else if (idx != 0) {
 528                                 coeff[idx++] = c;
 529                                 ++prec;
 530                             } // else c must be a redundant leading zero
 531                         } else {
 532                             if (prec != 1 || idx != 0)
 533                                 ++prec; // prec unchanged if preceded by 0s
 534                             coeff[idx++] = c;
 535                         }
 536                         if (dot)
 537                             ++scl;
 538                         continue;
 539                     }
 540                     // have dot
 541                     if (c == '.') {
 542                         // have dot
 543                         if (dot) // two dots
 544                             throw new NumberFormatException();
 545                         dot = true;
 546                         continue;
 547                     }
 548                     // exponent expected
 549                     if ((c != 'e') && (c != 'E'))
 550                         throw new NumberFormatException();
 551                     exp = parseExp(in, offset, len);
 552                     // Next test is required for backwards compatibility
 553                     if ((int) exp != exp) // overflow
 554                         throw new NumberFormatException();
 555                     break; // [saves a test]
 556                 }
 557                 // here when no characters left
 558                 if (prec == 0) // no digits found
 559                     throw new NumberFormatException();
 560                 // Adjust scale if exp is not zero.
 561                 if (exp != 0) { // had significant exponent
 562                     scl = adjustScale(scl, exp);
 563                 }
 564                 // Remove leading zeros from precision (digits count)
 565                 rb = new BigInteger(coeff, isneg ? -1 : 1, prec);
 566                 rs = compactValFor(rb);
 567                 int mcp = mc.precision;
 568                 if (mcp > 0 && (prec > mcp)) {
 569                     if (rs == INFLATED) {
 570                         int drop = prec - mcp;
 571                         while (drop > 0) {
 572                             scl = checkScaleNonZero((long) scl - drop);
 573                             rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);
 574                             rs = compactValFor(rb);
 575                             if (rs != INFLATED) {
 576                                 prec = longDigitLength(rs);
 577                                 break;
 578                             }
 579                             prec = bigDigitLength(rb);
 580                             drop = prec - mcp;
 581                         }
 582                     }
 583                     if (rs != INFLATED) {
 584                         int drop = prec - mcp;
 585                         while (drop > 0) {
 586                             scl = checkScaleNonZero((long) scl - drop);
 587                             rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 588                             prec = longDigitLength(rs);
 589                             drop = prec - mcp;
 590                         }
 591                         rb = null;
 592                     }
 593                 }
 594             }
 595         } catch (ArrayIndexOutOfBoundsException e) {
 596             throw new NumberFormatException();
 597         } catch (NegativeArraySizeException e) {
 598             throw new NumberFormatException();
 599         }
 600         this.scale = scl;
 601         this.precision = prec;
 602         this.intCompact = rs;
 603         this.intVal = rb;
 604     }
 605 
 606     private int adjustScale(int scl, long exp) {
 607         long adjustedScale = scl - exp;
 608         if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)
 609             throw new NumberFormatException("Scale out of range.");
 610         scl = (int) adjustedScale;
 611         return scl;
 612     }
 613 
 614     /*
 615      * parse exponent
 616      */
 617     private static long parseExp(char[] in, int offset, int len){
 618         long exp = 0;
 619         offset++;
 620         char c = in[offset];
 621         len--;
 622         boolean negexp = (c == '-');
 623         // optional sign
 624         if (negexp || c == '+') {
 625             offset++;
 626             c = in[offset];
 627             len--;
 628         }
 629         if (len <= 0) // no exponent digits
 630             throw new NumberFormatException();
 631         // skip leading zeros in the exponent
 632         while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {
 633             offset++;
 634             c = in[offset];
 635             len--;
 636         }
 637         if (len > 10) // too many nonzero exponent digits
 638             throw new NumberFormatException();
 639         // c now holds first digit of exponent
 640         for (;; len--) {
 641             int v;
 642             if (c >= '0' && c <= '9') {
 643                 v = c - '0';
 644             } else {
 645                 v = Character.digit(c, 10);
 646                 if (v < 0) // not a digit
 647                     throw new NumberFormatException();
 648             }
 649             exp = exp * 10 + v;
 650             if (len == 1)
 651                 break; // that was final character
 652             offset++;
 653             c = in[offset];
 654         }
 655         if (negexp) // apply sign
 656             exp = -exp;
 657         return exp;
 658     }
 659 
 660     /**
 661      * Translates a character array representation of a
 662      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 663      * same sequence of characters as the {@link #BigDecimal(String)}
 664      * constructor.
 665      *
 666      * <p>Note that if the sequence of characters is already available
 667      * as a character array, using this constructor is faster than
 668      * converting the {@code char} array to string and using the
 669      * {@code BigDecimal(String)} constructor .
 670      *
 671      * @param in {@code char} array that is the source of characters.
 672      * @throws NumberFormatException if {@code in} is not a valid
 673      *         representation of a {@code BigDecimal}.
 674      * @since  1.5
 675      */
 676     public BigDecimal(char[] in) {
 677         this(in, 0, in.length);
 678     }
 679 
 680     /**
 681      * Translates a character array representation of a
 682      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 683      * same sequence of characters as the {@link #BigDecimal(String)}
 684      * constructor and with rounding according to the context
 685      * settings.
 686      *
 687      * <p>Note that if the sequence of characters is already available
 688      * as a character array, using this constructor is faster than
 689      * converting the {@code char} array to string and using the
 690      * {@code BigDecimal(String)} constructor .
 691      *
 692      * @param  in {@code char} array that is the source of characters.
 693      * @param  mc the context to use.
 694      * @throws ArithmeticException if the result is inexact but the
 695      *         rounding mode is {@code UNNECESSARY}.
 696      * @throws NumberFormatException if {@code in} is not a valid
 697      *         representation of a {@code BigDecimal}.
 698      * @since  1.5
 699      */
 700     public BigDecimal(char[] in, MathContext mc) {
 701         this(in, 0, in.length, mc);
 702     }
 703 
 704     /**
 705      * Translates the string representation of a {@code BigDecimal}
 706      * into a {@code BigDecimal}.  The string representation consists
 707      * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
 708      * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
 709      * zero or more decimal digits ("the integer"), optionally
 710      * followed by a fraction, optionally followed by an exponent.
 711      *
 712      * <p>The fraction consists of a decimal point followed by zero
 713      * or more decimal digits.  The string must contain at least one
 714      * digit in either the integer or the fraction.  The number formed
 715      * by the sign, the integer and the fraction is referred to as the
 716      * <i>significand</i>.
 717      *
 718      * <p>The exponent consists of the character {@code 'e'}
 719      * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
 720      * followed by one or more decimal digits.  The value of the
 721      * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
 722      * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
 723      *
 724      * <p>More formally, the strings this constructor accepts are
 725      * described by the following grammar:
 726      * <blockquote>
 727      * <dl>
 728      * <dt><i>BigDecimalString:</i>
 729      * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
 730      * <p>
 731      * <dt><i>Sign:</i>
 732      * <dd>{@code +}
 733      * <dd>{@code -}
 734      * <p>
 735      * <dt><i>Significand:</i>
 736      * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
 737      * <dd>{@code .} <i>FractionPart</i>
 738      * <dd><i>IntegerPart</i>
 739      * <p>
 740      * <dt><i>IntegerPart:</i>
 741      * <dd><i>Digits</i>
 742      * <p>
 743      * <dt><i>FractionPart:</i>
 744      * <dd><i>Digits</i>
 745      * <p>
 746      * <dt><i>Exponent:</i>
 747      * <dd><i>ExponentIndicator SignedInteger</i>
 748      * <p>
 749      * <dt><i>ExponentIndicator:</i>
 750      * <dd>{@code e}
 751      * <dd>{@code E}
 752      * <p>
 753      * <dt><i>SignedInteger:</i>
 754      * <dd><i>Sign<sub>opt</sub> Digits</i>
 755      * <p>
 756      * <dt><i>Digits:</i>
 757      * <dd><i>Digit</i>
 758      * <dd><i>Digits Digit</i>
 759      * <p>
 760      * <dt><i>Digit:</i>
 761      * <dd>any character for which {@link Character#isDigit}
 762      * returns {@code true}, including 0, 1, 2 ...
 763      * </dl>
 764      * </blockquote>
 765      *
 766      * <p>The scale of the returned {@code BigDecimal} will be the
 767      * number of digits in the fraction, or zero if the string
 768      * contains no decimal point, subject to adjustment for any
 769      * exponent; if the string contains an exponent, the exponent is
 770      * subtracted from the scale.  The value of the resulting scale
 771      * must lie between {@code Integer.MIN_VALUE} and
 772      * {@code Integer.MAX_VALUE}, inclusive.
 773      *
 774      * <p>The character-to-digit mapping is provided by {@link
 775      * java.lang.Character#digit} set to convert to radix 10.  The
 776      * String may not contain any extraneous characters (whitespace,
 777      * for example).
 778      *
 779      * <p><b>Examples:</b><br>
 780      * The value of the returned {@code BigDecimal} is equal to
 781      * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
 782      * For each string on the left, the resulting representation
 783      * [{@code BigInteger}, {@code scale}] is shown on the right.
 784      * <pre>
 785      * "0"            [0,0]
 786      * "0.00"         [0,2]
 787      * "123"          [123,0]
 788      * "-123"         [-123,0]
 789      * "1.23E3"       [123,-1]
 790      * "1.23E+3"      [123,-1]
 791      * "12.3E+7"      [123,-6]
 792      * "12.0"         [120,1]
 793      * "12.3"         [123,1]
 794      * "0.00123"      [123,5]
 795      * "-1.23E-12"    [-123,14]
 796      * "1234.5E-4"    [12345,5]
 797      * "0E+7"         [0,-7]
 798      * "-0"           [0,0]
 799      * </pre>
 800      *
 801      * <p>Note: For values other than {@code float} and
 802      * {@code double} NaN and &plusmn;Infinity, this constructor is
 803      * compatible with the values returned by {@link Float#toString}
 804      * and {@link Double#toString}.  This is generally the preferred
 805      * way to convert a {@code float} or {@code double} into a
 806      * BigDecimal, as it doesn't suffer from the unpredictability of
 807      * the {@link #BigDecimal(double)} constructor.
 808      *
 809      * @param val String representation of {@code BigDecimal}.
 810      *
 811      * @throws NumberFormatException if {@code val} is not a valid
 812      *         representation of a {@code BigDecimal}.
 813      */
 814     public BigDecimal(String val) {
 815         this(val.toCharArray(), 0, val.length());
 816     }
 817 
 818     /**
 819      * Translates the string representation of a {@code BigDecimal}
 820      * into a {@code BigDecimal}, accepting the same strings as the
 821      * {@link #BigDecimal(String)} constructor, with rounding
 822      * according to the context settings.
 823      *
 824      * @param  val string representation of a {@code BigDecimal}.
 825      * @param  mc the context to use.
 826      * @throws ArithmeticException if the result is inexact but the
 827      *         rounding mode is {@code UNNECESSARY}.
 828      * @throws NumberFormatException if {@code val} is not a valid
 829      *         representation of a BigDecimal.
 830      * @since  1.5
 831      */
 832     public BigDecimal(String val, MathContext mc) {
 833         this(val.toCharArray(), 0, val.length(), mc);
 834     }
 835 
 836     /**
 837      * Translates a {@code double} into a {@code BigDecimal} which
 838      * is the exact decimal representation of the {@code double}'s
 839      * binary floating-point value.  The scale of the returned
 840      * {@code BigDecimal} is the smallest value such that
 841      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 842      * <p>
 843      * <b>Notes:</b>
 844      * <ol>
 845      * <li>
 846      * The results of this constructor can be somewhat unpredictable.
 847      * One might assume that writing {@code new BigDecimal(0.1)} in
 848      * Java creates a {@code BigDecimal} which is exactly equal to
 849      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
 850      * actually equal to
 851      * 0.1000000000000000055511151231257827021181583404541015625.
 852      * This is because 0.1 cannot be represented exactly as a
 853      * {@code double} (or, for that matter, as a binary fraction of
 854      * any finite length).  Thus, the value that is being passed
 855      * <i>in</i> to the constructor is not exactly equal to 0.1,
 856      * appearances notwithstanding.
 857      *
 858      * <li>
 859      * The {@code String} constructor, on the other hand, is
 860      * perfectly predictable: writing {@code new BigDecimal("0.1")}
 861      * creates a {@code BigDecimal} which is <i>exactly</i> equal to
 862      * 0.1, as one would expect.  Therefore, it is generally
 863      * recommended that the {@linkplain #BigDecimal(String)
 864      * <tt>String</tt> constructor} be used in preference to this one.
 865      *
 866      * <li>
 867      * When a {@code double} must be used as a source for a
 868      * {@code BigDecimal}, note that this constructor provides an
 869      * exact conversion; it does not give the same result as
 870      * converting the {@code double} to a {@code String} using the
 871      * {@link Double#toString(double)} method and then using the
 872      * {@link #BigDecimal(String)} constructor.  To get that result,
 873      * use the {@code static} {@link #valueOf(double)} method.
 874      * </ol>
 875      *
 876      * @param val {@code double} value to be converted to
 877      *        {@code BigDecimal}.
 878      * @throws NumberFormatException if {@code val} is infinite or NaN.
 879      */
 880     public BigDecimal(double val) {
 881         this(val,MathContext.UNLIMITED);
 882     }
 883 
 884     /**
 885      * Translates a {@code double} into a {@code BigDecimal}, with
 886      * rounding according to the context settings.  The scale of the
 887      * {@code BigDecimal} is the smallest value such that
 888      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 889      *
 890      * <p>The results of this constructor can be somewhat unpredictable
 891      * and its use is generally not recommended; see the notes under
 892      * the {@link #BigDecimal(double)} constructor.
 893      *
 894      * @param  val {@code double} value to be converted to
 895      *         {@code BigDecimal}.
 896      * @param  mc the context to use.
 897      * @throws ArithmeticException if the result is inexact but the
 898      *         RoundingMode is UNNECESSARY.
 899      * @throws NumberFormatException if {@code val} is infinite or NaN.
 900      * @since  1.5
 901      */
 902     public BigDecimal(double val, MathContext mc) {
 903         if (Double.isInfinite(val) || Double.isNaN(val))
 904             throw new NumberFormatException("Infinite or NaN");
 905         // Translate the double into sign, exponent and significand, according
 906         // to the formulae in JLS, Section 20.10.22.
 907         int sign = (val >= 0.0 ? 1 : -1); // Preserving sign of zero doesn't matter
 908         int exponent = Math.getExponent(val);
 909         long valBits = Double.doubleToLongBits(val);
 910         long significand = (exponent == (Double.MIN_EXPONENT-1)
 911                             ? (valBits & ((1L << 52) - 1)) << 1
 912                             : (valBits & ((1L << 52) - 1)) | (1L << 52));
 913         // At this point, val == sign * significand * 2**exponent.
 914 
 915         /*
 916          * Special case zero to supress nonterminating normalization and bogus
 917          * scale calculation.
 918          */
 919         if (significand == 0) {
 920             this.intVal = BigInteger.ZERO;
 921             this.scale = 0;
 922             this.intCompact = 0;
 923             this.precision = 1;
 924             return;
 925         }
 926         // Normalize
 927         while ((significand & 1) == 0) { // i.e., significand is even
 928             significand >>= 1;
 929             exponent++;
 930         }
 931         int scale = 0;
 932         // Calculate intVal and scale
 933         BigInteger intVal;
 934         long compactVal = sign * significand;
 935         if (exponent == 0) {
 936             // If the exponent is zero, the significant fits in a long
 937             assert compactVal != INFLATED;
 938             intVal = null;
 939         } else {
 940             if (exponent < 0) {
 941                 intVal = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
 942                 scale = -exponent;
 943             } else { //  (exponent > 0)
 944                 intVal = BigInteger.valueOf(2).pow(exponent).multiply(compactVal);
 945             }
 946             compactVal = compactValFor(intVal);
 947         }
 948         int prec = 0;
 949         int mcp = mc.precision;
 950         if (mcp > 0) { // do rounding
 951             int mode = mc.roundingMode.oldMode;
 952             int drop;
 953             if (compactVal == INFLATED) {
 954                 prec = bigDigitLength(intVal);
 955                 drop = prec - mcp;
 956                 while (drop > 0) {
 957                     scale = checkScaleNonZero((long) scale - drop);
 958                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
 959                     compactVal = compactValFor(intVal);
 960                     if (compactVal != INFLATED) {
 961                         break;
 962                     }
 963                     prec = bigDigitLength(intVal);
 964                     drop = prec - mcp;
 965                 }
 966             }
 967             if (compactVal != INFLATED) {
 968                 prec = longDigitLength(compactVal);
 969                 drop = prec - mcp;
 970                 while (drop > 0) {
 971                     scale = checkScaleNonZero((long) scale - drop);
 972                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 973                     prec = longDigitLength(compactVal);
 974                     drop = prec - mcp;
 975                 }
 976                 intVal = null;
 977             }
 978         }
 979         this.intVal = intVal;
 980         this.intCompact = compactVal;
 981         this.scale = scale;
 982         this.precision = prec;
 983     }
 984 
 985     /**
 986      * Translates a {@code BigInteger} into a {@code BigDecimal}.
 987      * The scale of the {@code BigDecimal} is zero.
 988      *
 989      * @param val {@code BigInteger} value to be converted to
 990      *            {@code BigDecimal}.
 991      */
 992     public BigDecimal(BigInteger val) {
 993         scale = 0;
 994         intVal = val;
 995         intCompact = compactValFor(val);
 996     }
 997 
 998     /**
 999      * Translates a {@code BigInteger} into a {@code BigDecimal}
1000      * rounding according to the context settings.  The scale of the
1001      * {@code BigDecimal} is zero.
1002      *
1003      * @param val {@code BigInteger} value to be converted to
1004      *            {@code BigDecimal}.
1005      * @param  mc the context to use.
1006      * @throws ArithmeticException if the result is inexact but the
1007      *         rounding mode is {@code UNNECESSARY}.
1008      * @since  1.5
1009      */
1010     public BigDecimal(BigInteger val, MathContext mc) {
1011         this(val,0,mc);
1012     }
1013 
1014     /**
1015      * Translates a {@code BigInteger} unscaled value and an
1016      * {@code int} scale into a {@code BigDecimal}.  The value of
1017      * the {@code BigDecimal} is
1018      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1019      *
1020      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1021      * @param scale scale of the {@code BigDecimal}.
1022      */
1023     public BigDecimal(BigInteger unscaledVal, int scale) {
1024         // Negative scales are now allowed
1025         this.intVal = unscaledVal;
1026         this.intCompact = compactValFor(unscaledVal);
1027         this.scale = scale;
1028     }
1029 
1030     /**
1031      * Translates a {@code BigInteger} unscaled value and an
1032      * {@code int} scale into a {@code BigDecimal}, with rounding
1033      * according to the context settings.  The value of the
1034      * {@code BigDecimal} is <tt>(unscaledVal &times;
1035      * 10<sup>-scale</sup>)</tt>, rounded according to the
1036      * {@code precision} and rounding mode settings.
1037      *
1038      * @param  unscaledVal unscaled value of the {@code BigDecimal}.
1039      * @param  scale scale of the {@code BigDecimal}.
1040      * @param  mc the context to use.
1041      * @throws ArithmeticException if the result is inexact but the
1042      *         rounding mode is {@code UNNECESSARY}.
1043      * @since  1.5
1044      */
1045     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1046         long compactVal = compactValFor(unscaledVal);
1047         int mcp = mc.precision;
1048         int prec = 0;
1049         if (mcp > 0) { // do rounding
1050             int mode = mc.roundingMode.oldMode;
1051             if (compactVal == INFLATED) {
1052                 prec = bigDigitLength(unscaledVal);
1053                 int drop = prec - mcp;
1054                 while (drop > 0) {
1055                     scale = checkScaleNonZero((long) scale - drop);
1056                     unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);
1057                     compactVal = compactValFor(unscaledVal);
1058                     if (compactVal != INFLATED) {
1059                         break;
1060                     }
1061                     prec = bigDigitLength(unscaledVal);
1062                     drop = prec - mcp;
1063                 }
1064             }
1065             if (compactVal != INFLATED) {
1066                 prec = longDigitLength(compactVal);
1067                 int drop = prec - mcp;     // drop can't be more than 18
1068                 while (drop > 0) {
1069                     scale = checkScaleNonZero((long) scale - drop);
1070                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);
1071                     prec = longDigitLength(compactVal);
1072                     drop = prec - mcp;
1073                 }
1074                 unscaledVal = null;
1075             }
1076         }
1077         this.intVal = unscaledVal;
1078         this.intCompact = compactVal;
1079         this.scale = scale;
1080         this.precision = prec;
1081     }
1082 
1083     /**
1084      * Translates an {@code int} into a {@code BigDecimal}.  The
1085      * scale of the {@code BigDecimal} is zero.
1086      *
1087      * @param val {@code int} value to be converted to
1088      *            {@code BigDecimal}.
1089      * @since  1.5
1090      */
1091     public BigDecimal(int val) {
1092         this.intCompact = val;
1093         this.scale = 0;
1094         this.intVal = null;
1095     }
1096 
1097     /**
1098      * Translates an {@code int} into a {@code BigDecimal}, with
1099      * rounding according to the context settings.  The scale of the
1100      * {@code BigDecimal}, before any rounding, is zero.
1101      *
1102      * @param  val {@code int} value to be converted to {@code BigDecimal}.
1103      * @param  mc the context to use.
1104      * @throws ArithmeticException if the result is inexact but the
1105      *         rounding mode is {@code UNNECESSARY}.
1106      * @since  1.5
1107      */
1108     public BigDecimal(int val, MathContext mc) {
1109         int mcp = mc.precision;
1110         long compactVal = val;
1111         int scale = 0;
1112         int prec = 0;
1113         if (mcp > 0) { // do rounding
1114             prec = longDigitLength(compactVal);
1115             int drop = prec - mcp; // drop can't be more than 18
1116             while (drop > 0) {
1117                 scale = checkScaleNonZero((long) scale - drop);
1118                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1119                 prec = longDigitLength(compactVal);
1120                 drop = prec - mcp;
1121             }
1122         }
1123         this.intVal = null;
1124         this.intCompact = compactVal;
1125         this.scale = scale;
1126         this.precision = prec;
1127     }
1128 
1129     /**
1130      * Translates a {@code long} into a {@code BigDecimal}.  The
1131      * scale of the {@code BigDecimal} is zero.
1132      *
1133      * @param val {@code long} value to be converted to {@code BigDecimal}.
1134      * @since  1.5
1135      */
1136     public BigDecimal(long val) {
1137         this.intCompact = val;
1138         this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1139         this.scale = 0;
1140     }
1141 
1142     /**
1143      * Translates a {@code long} into a {@code BigDecimal}, with
1144      * rounding according to the context settings.  The scale of the
1145      * {@code BigDecimal}, before any rounding, is zero.
1146      *
1147      * @param  val {@code long} value to be converted to {@code BigDecimal}.
1148      * @param  mc the context to use.
1149      * @throws ArithmeticException if the result is inexact but the
1150      *         rounding mode is {@code UNNECESSARY}.
1151      * @since  1.5
1152      */
1153     public BigDecimal(long val, MathContext mc) {
1154         int mcp = mc.precision;
1155         int mode = mc.roundingMode.oldMode;
1156         int prec = 0;
1157         int scale = 0;
1158         BigInteger intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1159         if (mcp > 0) { // do rounding
1160             if (val == INFLATED) {
1161                 prec = 19;
1162                 int drop = prec - mcp;
1163                 while (drop > 0) {
1164                     scale = checkScaleNonZero((long) scale - drop);
1165                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
1166                     val = compactValFor(intVal);
1167                     if (val != INFLATED) {
1168                         break;
1169                     }
1170                     prec = bigDigitLength(intVal);
1171                     drop = prec - mcp;
1172                 }
1173             }
1174             if (val != INFLATED) {
1175                 prec = longDigitLength(val);
1176                 int drop = prec - mcp;
1177                 while (drop > 0) {
1178                     scale = checkScaleNonZero((long) scale - drop);
1179                     val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1180                     prec = longDigitLength(val);
1181                     drop = prec - mcp;
1182                 }
1183                 intVal = null;
1184             }
1185         }
1186         this.intVal = intVal;
1187         this.intCompact = val;
1188         this.scale = scale;
1189         this.precision = prec;
1190     }
1191 
1192     // Static Factory Methods
1193 
1194     /**
1195      * Translates a {@code long} unscaled value and an
1196      * {@code int} scale into a {@code BigDecimal}.  This
1197      * {@literal "static factory method"} is provided in preference to
1198      * a ({@code long}, {@code int}) constructor because it
1199      * allows for reuse of frequently used {@code BigDecimal} values..
1200      *
1201      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1202      * @param scale scale of the {@code BigDecimal}.
1203      * @return a {@code BigDecimal} whose value is
1204      *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1205      */
1206     public static BigDecimal valueOf(long unscaledVal, int scale) {
1207         if (scale == 0)
1208             return valueOf(unscaledVal);
1209         else if (unscaledVal == 0) {
1210             return zeroValueOf(scale);
1211         }
1212         return new BigDecimal(unscaledVal == INFLATED ?
1213                               INFLATED_BIGINT : null,
1214                               unscaledVal, scale, 0);
1215     }
1216 
1217     /**
1218      * Translates a {@code long} value into a {@code BigDecimal}
1219      * with a scale of zero.  This {@literal "static factory method"}
1220      * is provided in preference to a ({@code long}) constructor
1221      * because it allows for reuse of frequently used
1222      * {@code BigDecimal} values.
1223      *
1224      * @param val value of the {@code BigDecimal}.
1225      * @return a {@code BigDecimal} whose value is {@code val}.
1226      */
1227     public static BigDecimal valueOf(long val) {
1228         if (val >= 0 && val < zeroThroughTen.length)
1229             return zeroThroughTen[(int)val];
1230         else if (val != INFLATED)
1231             return new BigDecimal(null, val, 0, 0);
1232         return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1233     }
1234 
1235     static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1236         if (scale == 0 && unscaledVal >= 0 && unscaledVal < zeroThroughTen.length) {
1237             return zeroThroughTen[(int) unscaledVal];
1238         } else if (unscaledVal == 0) {
1239             return zeroValueOf(scale);
1240         }
1241         return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1242                 unscaledVal, scale, prec);
1243     }
1244 
1245     static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1246         long val = compactValFor(intVal);
1247         if (val == 0) {
1248             return zeroValueOf(scale);
1249         } else if (scale == 0 && val >= 0 && val < zeroThroughTen.length) {
1250             return zeroThroughTen[(int) val];
1251         }
1252         return new BigDecimal(intVal, val, scale, prec);
1253     }
1254 
1255     static BigDecimal zeroValueOf(int scale) {
1256         if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1257             return ZERO_SCALED_BY[scale];
1258         else
1259             return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1260     }
1261 
1262     /**
1263      * Translates a {@code double} into a {@code BigDecimal}, using
1264      * the {@code double}'s canonical string representation provided
1265      * by the {@link Double#toString(double)} method.
1266      *
1267      * <p><b>Note:</b> This is generally the preferred way to convert
1268      * a {@code double} (or {@code float}) into a
1269      * {@code BigDecimal}, as the value returned is equal to that
1270      * resulting from constructing a {@code BigDecimal} from the
1271      * result of using {@link Double#toString(double)}.
1272      *
1273      * @param  val {@code double} to convert to a {@code BigDecimal}.
1274      * @return a {@code BigDecimal} whose value is equal to or approximately
1275      *         equal to the value of {@code val}.
1276      * @throws NumberFormatException if {@code val} is infinite or NaN.
1277      * @since  1.5
1278      */
1279     public static BigDecimal valueOf(double val) {
1280         // Reminder: a zero double returns '0.0', so we cannot fastpath
1281         // to use the constant ZERO.  This might be important enough to
1282         // justify a factory approach, a cache, or a few private
1283         // constants, later.
1284         return new BigDecimal(Double.toString(val));
1285     }
1286 
1287     // Arithmetic Operations
1288     /**
1289      * Returns a {@code BigDecimal} whose value is {@code (this +
1290      * augend)}, and whose scale is {@code max(this.scale(),
1291      * augend.scale())}.
1292      *
1293      * @param  augend value to be added to this {@code BigDecimal}.
1294      * @return {@code this + augend}
1295      */
1296     public BigDecimal add(BigDecimal augend) {
1297         if (this.intCompact != INFLATED) {
1298             if ((augend.intCompact != INFLATED)) {
1299                 return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
1300             } else {
1301                 return add(this.intCompact, this.scale, augend.intVal, augend.scale);
1302             }
1303         } else {
1304             if ((augend.intCompact != INFLATED)) {
1305                 return add(augend.intCompact, augend.scale, this.intVal, this.scale);
1306             } else {
1307                 return add(this.intVal, this.scale, augend.intVal, augend.scale);
1308             }
1309         }
1310     }
1311 
1312     /**
1313      * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1314      * with rounding according to the context settings.
1315      *
1316      * If either number is zero and the precision setting is nonzero then
1317      * the other number, rounded if necessary, is used as the result.
1318      *
1319      * @param  augend value to be added to this {@code BigDecimal}.
1320      * @param  mc the context to use.
1321      * @return {@code this + augend}, rounded as necessary.
1322      * @throws ArithmeticException if the result is inexact but the
1323      *         rounding mode is {@code UNNECESSARY}.
1324      * @since  1.5
1325      */
1326     public BigDecimal add(BigDecimal augend, MathContext mc) {
1327         if (mc.precision == 0)
1328             return add(augend);
1329         BigDecimal lhs = this;
1330 
1331         // If either number is zero then the other number, rounded and
1332         // scaled if necessary, is used as the result.
1333         {
1334             boolean lhsIsZero = lhs.signum() == 0;
1335             boolean augendIsZero = augend.signum() == 0;
1336 
1337             if (lhsIsZero || augendIsZero) {
1338                 int preferredScale = Math.max(lhs.scale(), augend.scale());
1339                 BigDecimal result;
1340 
1341                 if (lhsIsZero && augendIsZero)
1342                     return zeroValueOf(preferredScale);
1343                 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1344 
1345                 if (result.scale() == preferredScale)
1346                     return result;
1347                 else if (result.scale() > preferredScale) {
1348                     return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);
1349                 } else { // result.scale < preferredScale
1350                     int precisionDiff = mc.precision - result.precision();
1351                     int scaleDiff     = preferredScale - result.scale();
1352 
1353                     if (precisionDiff >= scaleDiff)
1354                         return result.setScale(preferredScale); // can achieve target scale
1355                     else
1356                         return result.setScale(result.scale() + precisionDiff);
1357                 }
1358             }
1359         }
1360 
1361         long padding = (long) lhs.scale - augend.scale;
1362         if (padding != 0) { // scales differ; alignment needed
1363             BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1364             matchScale(arg);
1365             lhs = arg[0];
1366             augend = arg[1];
1367         }
1368         return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);
1369     }
1370 
1371     /**
1372      * Returns an array of length two, the sum of whose entries is
1373      * equal to the rounded sum of the {@code BigDecimal} arguments.
1374      *
1375      * <p>If the digit positions of the arguments have a sufficient
1376      * gap between them, the value smaller in magnitude can be
1377      * condensed into a {@literal "sticky bit"} and the end result will
1378      * round the same way <em>if</em> the precision of the final
1379      * result does not include the high order digit of the small
1380      * magnitude operand.
1381      *
1382      * <p>Note that while strictly speaking this is an optimization,
1383      * it makes a much wider range of additions practical.
1384      *
1385      * <p>This corresponds to a pre-shift operation in a fixed
1386      * precision floating-point adder; this method is complicated by
1387      * variable precision of the result as determined by the
1388      * MathContext.  A more nuanced operation could implement a
1389      * {@literal "right shift"} on the smaller magnitude operand so
1390      * that the number of digits of the smaller operand could be
1391      * reduced even though the significands partially overlapped.
1392      */
1393     private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {
1394         assert padding != 0;
1395         BigDecimal big;
1396         BigDecimal small;
1397 
1398         if (padding < 0) { // lhs is big; augend is small
1399             big = lhs;
1400             small = augend;
1401         } else { // lhs is small; augend is big
1402             big = augend;
1403             small = lhs;
1404         }
1405 
1406         /*
1407          * This is the estimated scale of an ulp of the result; it assumes that
1408          * the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>
1409          * 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>
1410          * 98.8)
1411          */
1412         long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;
1413 
1414         /*
1415          * The low-order digit position of big is big.scale().  This
1416          * is true regardless of whether big has a positive or
1417          * negative scale.  The high-order digit position of small is
1418          * small.scale - (small.precision() - 1).  To do the full
1419          * condensation, the digit positions of big and small must be
1420          * disjoint *and* the digit positions of small should not be
1421          * directly visible in the result.
1422          */
1423         long smallHighDigitPos = (long) small.scale - small.precision() + 1;
1424         if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1425             smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1426             small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1427         }
1428 
1429         // Since addition is symmetric, preserving input order in
1430         // returned operands doesn't matter
1431         BigDecimal[] result = {big, small};
1432         return result;
1433     }
1434 
1435     /**
1436      * Returns a {@code BigDecimal} whose value is {@code (this -
1437      * subtrahend)}, and whose scale is {@code max(this.scale(),
1438      * subtrahend.scale())}.
1439      *
1440      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1441      * @return {@code this - subtrahend}
1442      */
1443     public BigDecimal subtract(BigDecimal subtrahend) {
1444         if (this.intCompact != INFLATED) {
1445             if ((subtrahend.intCompact != INFLATED)) {
1446                 return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);
1447             } else {
1448                 return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1449             }
1450         } else {
1451             if ((subtrahend.intCompact != INFLATED)) {
1452                 // Pair of subtrahend values given before pair of
1453                 // values from this BigDecimal to avoid need for
1454                 // method overloading on the specialized add method
1455                 return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);
1456             } else {
1457                 return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1458             }
1459         }
1460     }
1461 
1462     /**
1463      * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1464      * with rounding according to the context settings.
1465      *
1466      * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1467      * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1468      *
1469      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1470      * @param  mc the context to use.
1471      * @return {@code this - subtrahend}, rounded as necessary.
1472      * @throws ArithmeticException if the result is inexact but the
1473      *         rounding mode is {@code UNNECESSARY}.
1474      * @since  1.5
1475      */
1476     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1477         if (mc.precision == 0)
1478             return subtract(subtrahend);
1479         // share the special rounding code in add()
1480         return add(subtrahend.negate(), mc);
1481     }
1482 
1483     /**
1484      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1485      * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1486      * multiplicand.scale())}.
1487      *
1488      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1489      * @return {@code this * multiplicand}
1490      */
1491     public BigDecimal multiply(BigDecimal multiplicand) {
1492         int productScale = checkScale((long) scale + multiplicand.scale);
1493         if (this.intCompact != INFLATED) {
1494             if ((multiplicand.intCompact != INFLATED)) {
1495                 return multiply(this.intCompact, multiplicand.intCompact, productScale);
1496             } else {
1497                 return multiply(this.intCompact, multiplicand.intVal, productScale);
1498             }
1499         } else {
1500             if ((multiplicand.intCompact != INFLATED)) {
1501                 return multiply(multiplicand.intCompact, this.intVal, productScale);
1502             } else {
1503                 return multiply(this.intVal, multiplicand.intVal, productScale);
1504             }
1505         }
1506     }
1507 
1508     /**
1509      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1510      * multiplicand)</tt>, with rounding according to the context settings.
1511      *
1512      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1513      * @param  mc the context to use.
1514      * @return {@code this * multiplicand}, rounded as necessary.
1515      * @throws ArithmeticException if the result is inexact but the
1516      *         rounding mode is {@code UNNECESSARY}.
1517      * @since  1.5
1518      */
1519     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1520         if (mc.precision == 0)
1521             return multiply(multiplicand);
1522         int productScale = checkScale((long) scale + multiplicand.scale);
1523         if (this.intCompact != INFLATED) {
1524             if ((multiplicand.intCompact != INFLATED)) {
1525                 return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
1526             } else {
1527                 return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
1528             }
1529         } else {
1530             if ((multiplicand.intCompact != INFLATED)) {
1531                 return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
1532             } else {
1533                 return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
1534             }
1535         }
1536     }
1537 
1538     /**
1539      * Returns a {@code BigDecimal} whose value is {@code (this /
1540      * divisor)}, and whose scale is as specified.  If rounding must
1541      * be performed to generate a result with the specified scale, the
1542      * specified rounding mode is applied.
1543      *
1544      * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1545      * should be used in preference to this legacy method.
1546      *
1547      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1548      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1549      * @param  roundingMode rounding mode to apply.
1550      * @return {@code this / divisor}
1551      * @throws ArithmeticException if {@code divisor} is zero,
1552      *         {@code roundingMode==ROUND_UNNECESSARY} and
1553      *         the specified scale is insufficient to represent the result
1554      *         of the division exactly.
1555      * @throws IllegalArgumentException if {@code roundingMode} does not
1556      *         represent a valid rounding mode.
1557      * @see    #ROUND_UP
1558      * @see    #ROUND_DOWN
1559      * @see    #ROUND_CEILING
1560      * @see    #ROUND_FLOOR
1561      * @see    #ROUND_HALF_UP
1562      * @see    #ROUND_HALF_DOWN
1563      * @see    #ROUND_HALF_EVEN
1564      * @see    #ROUND_UNNECESSARY
1565      */
1566     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1567         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1568             throw new IllegalArgumentException("Invalid rounding mode");
1569         if (this.intCompact != INFLATED) {
1570             if ((divisor.intCompact != INFLATED)) {
1571                 return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1572             } else {
1573                 return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1574             }
1575         } else {
1576             if ((divisor.intCompact != INFLATED)) {
1577                 return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1578             } else {
1579                 return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1580             }
1581         }
1582     }
1583 
1584     /**
1585      * Returns a {@code BigDecimal} whose value is {@code (this /
1586      * divisor)}, and whose scale is as specified.  If rounding must
1587      * be performed to generate a result with the specified scale, the
1588      * specified rounding mode is applied.
1589      *
1590      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1591      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1592      * @param  roundingMode rounding mode to apply.
1593      * @return {@code this / divisor}
1594      * @throws ArithmeticException if {@code divisor} is zero,
1595      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1596      *         the specified scale is insufficient to represent the result
1597      *         of the division exactly.
1598      * @since 1.5
1599      */
1600     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1601         return divide(divisor, scale, roundingMode.oldMode);
1602     }
1603 
1604     /**
1605      * Returns a {@code BigDecimal} whose value is {@code (this /
1606      * divisor)}, and whose scale is {@code this.scale()}.  If
1607      * rounding must be performed to generate a result with the given
1608      * scale, the specified rounding mode is applied.
1609      *
1610      * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1611      * should be used in preference to this legacy method.
1612      *
1613      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1614      * @param  roundingMode rounding mode to apply.
1615      * @return {@code this / divisor}
1616      * @throws ArithmeticException if {@code divisor==0}, or
1617      *         {@code roundingMode==ROUND_UNNECESSARY} and
1618      *         {@code this.scale()} is insufficient to represent the result
1619      *         of the division exactly.
1620      * @throws IllegalArgumentException if {@code roundingMode} does not
1621      *         represent a valid rounding mode.
1622      * @see    #ROUND_UP
1623      * @see    #ROUND_DOWN
1624      * @see    #ROUND_CEILING
1625      * @see    #ROUND_FLOOR
1626      * @see    #ROUND_HALF_UP
1627      * @see    #ROUND_HALF_DOWN
1628      * @see    #ROUND_HALF_EVEN
1629      * @see    #ROUND_UNNECESSARY
1630      */
1631     public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1632         return this.divide(divisor, scale, roundingMode);
1633     }
1634 
1635     /**
1636      * Returns a {@code BigDecimal} whose value is {@code (this /
1637      * divisor)}, and whose scale is {@code this.scale()}.  If
1638      * rounding must be performed to generate a result with the given
1639      * scale, the specified rounding mode is applied.
1640      *
1641      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1642      * @param  roundingMode rounding mode to apply.
1643      * @return {@code this / divisor}
1644      * @throws ArithmeticException if {@code divisor==0}, or
1645      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1646      *         {@code this.scale()} is insufficient to represent the result
1647      *         of the division exactly.
1648      * @since 1.5
1649      */
1650     public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1651         return this.divide(divisor, scale, roundingMode.oldMode);
1652     }
1653 
1654     /**
1655      * Returns a {@code BigDecimal} whose value is {@code (this /
1656      * divisor)}, and whose preferred scale is {@code (this.scale() -
1657      * divisor.scale())}; if the exact quotient cannot be
1658      * represented (because it has a non-terminating decimal
1659      * expansion) an {@code ArithmeticException} is thrown.
1660      *
1661      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1662      * @throws ArithmeticException if the exact quotient does not have a
1663      *         terminating decimal expansion
1664      * @return {@code this / divisor}
1665      * @since 1.5
1666      * @author Joseph D. Darcy
1667      */
1668     public BigDecimal divide(BigDecimal divisor) {
1669         /*
1670          * Handle zero cases first.
1671          */
1672         if (divisor.signum() == 0) {   // x/0
1673             if (this.signum() == 0)    // 0/0
1674                 throw new ArithmeticException("Division undefined");  // NaN
1675             throw new ArithmeticException("Division by zero");
1676         }
1677 
1678         // Calculate preferred scale
1679         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1680 
1681         if (this.signum() == 0) // 0/y
1682             return zeroValueOf(preferredScale);
1683         else {
1684             /*
1685              * If the quotient this/divisor has a terminating decimal
1686              * expansion, the expansion can have no more than
1687              * (a.precision() + ceil(10*b.precision)/3) digits.
1688              * Therefore, create a MathContext object with this
1689              * precision and do a divide with the UNNECESSARY rounding
1690              * mode.
1691              */
1692             MathContext mc = new MathContext( (int)Math.min(this.precision() +
1693                                                             (long)Math.ceil(10.0*divisor.precision()/3.0),
1694                                                             Integer.MAX_VALUE),
1695                                               RoundingMode.UNNECESSARY);
1696             BigDecimal quotient;
1697             try {
1698                 quotient = this.divide(divisor, mc);
1699             } catch (ArithmeticException e) {
1700                 throw new ArithmeticException("Non-terminating decimal expansion; " +
1701                                               "no exact representable decimal result.");
1702             }
1703 
1704             int quotientScale = quotient.scale();
1705 
1706             // divide(BigDecimal, mc) tries to adjust the quotient to
1707             // the desired one by removing trailing zeros; since the
1708             // exact divide method does not have an explicit digit
1709             // limit, we can add zeros too.
1710             if (preferredScale > quotientScale)
1711                 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1712 
1713             return quotient;
1714         }
1715     }
1716 
1717     /**
1718      * Returns a {@code BigDecimal} whose value is {@code (this /
1719      * divisor)}, with rounding according to the context settings.
1720      *
1721      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1722      * @param  mc the context to use.
1723      * @return {@code this / divisor}, rounded as necessary.
1724      * @throws ArithmeticException if the result is inexact but the
1725      *         rounding mode is {@code UNNECESSARY} or
1726      *         {@code mc.precision == 0} and the quotient has a
1727      *         non-terminating decimal expansion.
1728      * @since  1.5
1729      */
1730     public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1731         int mcp = mc.precision;
1732         if (mcp == 0)
1733             return divide(divisor);
1734 
1735         BigDecimal dividend = this;
1736         long preferredScale = (long)dividend.scale - divisor.scale;
1737         // Now calculate the answer.  We use the existing
1738         // divide-and-round method, but as this rounds to scale we have
1739         // to normalize the values here to achieve the desired result.
1740         // For x/y we first handle y=0 and x=0, and then normalize x and
1741         // y to give x' and y' with the following constraints:
1742         //   (a) 0.1 <= x' < 1
1743         //   (b)  x' <= y' < 10*x'
1744         // Dividing x'/y' with the required scale set to mc.precision then
1745         // will give a result in the range 0.1 to 1 rounded to exactly
1746         // the right number of digits (except in the case of a result of
1747         // 1.000... which can arise when x=y, or when rounding overflows
1748         // The 1.000... case will reduce properly to 1.
1749         if (divisor.signum() == 0) {      // x/0
1750             if (dividend.signum() == 0)    // 0/0
1751                 throw new ArithmeticException("Division undefined");  // NaN
1752             throw new ArithmeticException("Division by zero");
1753         }
1754         if (dividend.signum() == 0) // 0/y
1755             return zeroValueOf(saturateLong(preferredScale));
1756         int xscale = dividend.precision();
1757         int yscale = divisor.precision();
1758         if(dividend.intCompact!=INFLATED) {
1759             if(divisor.intCompact!=INFLATED) {
1760                 return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);
1761             } else {
1762                 return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);
1763             }
1764         } else {
1765             if(divisor.intCompact!=INFLATED) {
1766                 return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);
1767             } else {
1768                 return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);
1769             }
1770         }
1771     }
1772 
1773     /**
1774      * Returns a {@code BigDecimal} whose value is the integer part
1775      * of the quotient {@code (this / divisor)} rounded down.  The
1776      * preferred scale of the result is {@code (this.scale() -
1777      * divisor.scale())}.
1778      *
1779      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1780      * @return The integer part of {@code this / divisor}.
1781      * @throws ArithmeticException if {@code divisor==0}
1782      * @since  1.5
1783      */
1784     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1785         // Calculate preferred scale
1786         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1787         if (this.compareMagnitude(divisor) < 0) {
1788             // much faster when this << divisor
1789             return zeroValueOf(preferredScale);
1790         }
1791 
1792         if (this.signum() == 0 && divisor.signum() != 0)
1793             return this.setScale(preferredScale, ROUND_UNNECESSARY);
1794 
1795         // Perform a divide with enough digits to round to a correct
1796         // integer value; then remove any fractional digits
1797 
1798         int maxDigits = (int)Math.min(this.precision() +
1799                                       (long)Math.ceil(10.0*divisor.precision()/3.0) +
1800                                       Math.abs((long)this.scale() - divisor.scale()) + 2,
1801                                       Integer.MAX_VALUE);
1802         BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1803                                                                    RoundingMode.DOWN));
1804         if (quotient.scale > 0) {
1805             quotient = quotient.setScale(0, RoundingMode.DOWN);
1806             quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);
1807         }
1808 
1809         if (quotient.scale < preferredScale) {
1810             // pad with zeros if necessary
1811             quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1812         }
1813 
1814         return quotient;
1815     }
1816 
1817     /**
1818      * Returns a {@code BigDecimal} whose value is the integer part
1819      * of {@code (this / divisor)}.  Since the integer part of the
1820      * exact quotient does not depend on the rounding mode, the
1821      * rounding mode does not affect the values returned by this
1822      * method.  The preferred scale of the result is
1823      * {@code (this.scale() - divisor.scale())}.  An
1824      * {@code ArithmeticException} is thrown if the integer part of
1825      * the exact quotient needs more than {@code mc.precision}
1826      * digits.
1827      *
1828      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1829      * @param  mc the context to use.
1830      * @return The integer part of {@code this / divisor}.
1831      * @throws ArithmeticException if {@code divisor==0}
1832      * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1833      *         requires a precision of more than {@code mc.precision} digits.
1834      * @since  1.5
1835      * @author Joseph D. Darcy
1836      */
1837     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1838         if (mc.precision == 0 || // exact result
1839             (this.compareMagnitude(divisor) < 0)) // zero result
1840             return divideToIntegralValue(divisor);
1841 
1842         // Calculate preferred scale
1843         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1844 
1845         /*
1846          * Perform a normal divide to mc.precision digits.  If the
1847          * remainder has absolute value less than the divisor, the
1848          * integer portion of the quotient fits into mc.precision
1849          * digits.  Next, remove any fractional digits from the
1850          * quotient and adjust the scale to the preferred value.
1851          */
1852         BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1853 
1854         if (result.scale() < 0) {
1855             /*
1856              * Result is an integer. See if quotient represents the
1857              * full integer portion of the exact quotient; if it does,
1858              * the computed remainder will be less than the divisor.
1859              */
1860             BigDecimal product = result.multiply(divisor);
1861             // If the quotient is the full integer value,
1862             // |dividend-product| < |divisor|.
1863             if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1864                 throw new ArithmeticException("Division impossible");
1865             }
1866         } else if (result.scale() > 0) {
1867             /*
1868              * Integer portion of quotient will fit into precision
1869              * digits; recompute quotient to scale 0 to avoid double
1870              * rounding and then try to adjust, if necessary.
1871              */
1872             result = result.setScale(0, RoundingMode.DOWN);
1873         }
1874         // else result.scale() == 0;
1875 
1876         int precisionDiff;
1877         if ((preferredScale > result.scale()) &&
1878             (precisionDiff = mc.precision - result.precision()) > 0) {
1879             return result.setScale(result.scale() +
1880                                    Math.min(precisionDiff, preferredScale - result.scale) );
1881         } else {
1882             return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);
1883         }
1884     }
1885 
1886     /**
1887      * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1888      *
1889      * <p>The remainder is given by
1890      * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1891      * Note that this is not the modulo operation (the result can be
1892      * negative).
1893      *
1894      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1895      * @return {@code this % divisor}.
1896      * @throws ArithmeticException if {@code divisor==0}
1897      * @since  1.5
1898      */
1899     public BigDecimal remainder(BigDecimal divisor) {
1900         BigDecimal divrem[] = this.divideAndRemainder(divisor);
1901         return divrem[1];
1902     }
1903 
1904 
1905     /**
1906      * Returns a {@code BigDecimal} whose value is {@code (this %
1907      * divisor)}, with rounding according to the context settings.
1908      * The {@code MathContext} settings affect the implicit divide
1909      * used to compute the remainder.  The remainder computation
1910      * itself is by definition exact.  Therefore, the remainder may
1911      * contain more than {@code mc.getPrecision()} digits.
1912      *
1913      * <p>The remainder is given by
1914      * {@code this.subtract(this.divideToIntegralValue(divisor,
1915      * mc).multiply(divisor))}.  Note that this is not the modulo
1916      * operation (the result can be negative).
1917      *
1918      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1919      * @param  mc the context to use.
1920      * @return {@code this % divisor}, rounded as necessary.
1921      * @throws ArithmeticException if {@code divisor==0}
1922      * @throws ArithmeticException if the result is inexact but the
1923      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1924      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1925      *         require a precision of more than {@code mc.precision} digits.
1926      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1927      * @since  1.5
1928      */
1929     public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1930         BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1931         return divrem[1];
1932     }
1933 
1934     /**
1935      * Returns a two-element {@code BigDecimal} array containing the
1936      * result of {@code divideToIntegralValue} followed by the result of
1937      * {@code remainder} on the two operands.
1938      *
1939      * <p>Note that if both the integer quotient and remainder are
1940      * needed, this method is faster than using the
1941      * {@code divideToIntegralValue} and {@code remainder} methods
1942      * separately because the division need only be carried out once.
1943      *
1944      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1945      *         and the remainder computed.
1946      * @return a two element {@code BigDecimal} array: the quotient
1947      *         (the result of {@code divideToIntegralValue}) is the initial element
1948      *         and the remainder is the final element.
1949      * @throws ArithmeticException if {@code divisor==0}
1950      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1951      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1952      * @since  1.5
1953      */
1954     public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1955         // we use the identity  x = i * y + r to determine r
1956         BigDecimal[] result = new BigDecimal[2];
1957 
1958         result[0] = this.divideToIntegralValue(divisor);
1959         result[1] = this.subtract(result[0].multiply(divisor));
1960         return result;
1961     }
1962 
1963     /**
1964      * Returns a two-element {@code BigDecimal} array containing the
1965      * result of {@code divideToIntegralValue} followed by the result of
1966      * {@code remainder} on the two operands calculated with rounding
1967      * according to the context settings.
1968      *
1969      * <p>Note that if both the integer quotient and remainder are
1970      * needed, this method is faster than using the
1971      * {@code divideToIntegralValue} and {@code remainder} methods
1972      * separately because the division need only be carried out once.
1973      *
1974      * @param  divisor value by which this {@code BigDecimal} is to be divided,
1975      *         and the remainder computed.
1976      * @param  mc the context to use.
1977      * @return a two element {@code BigDecimal} array: the quotient
1978      *         (the result of {@code divideToIntegralValue}) is the
1979      *         initial element and the remainder is the final element.
1980      * @throws ArithmeticException if {@code divisor==0}
1981      * @throws ArithmeticException if the result is inexact but the
1982      *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1983      *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1984      *         require a precision of more than {@code mc.precision} digits.
1985      * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1986      * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1987      * @since  1.5
1988      */
1989     public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1990         if (mc.precision == 0)
1991             return divideAndRemainder(divisor);
1992 
1993         BigDecimal[] result = new BigDecimal[2];
1994         BigDecimal lhs = this;
1995 
1996         result[0] = lhs.divideToIntegralValue(divisor, mc);
1997         result[1] = lhs.subtract(result[0].multiply(divisor));
1998         return result;
1999     }
2000 
2001     /**
2002      * Returns a {@code BigDecimal} whose value is
2003      * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
2004      * unlimited precision.
2005      *
2006      * <p>The parameter {@code n} must be in the range 0 through
2007      * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
2008      * #ONE}.
2009      *
2010      * Note that future releases may expand the allowable exponent
2011      * range of this method.
2012      *
2013      * @param  n power to raise this {@code BigDecimal} to.
2014      * @return <tt>this<sup>n</sup></tt>
2015      * @throws ArithmeticException if {@code n} is out of range.
2016      * @since  1.5
2017      */
2018     public BigDecimal pow(int n) {
2019         if (n < 0 || n > 999999999)
2020             throw new ArithmeticException("Invalid operation");
2021         // No need to calculate pow(n) if result will over/underflow.
2022         // Don't attempt to support "supernormal" numbers.
2023         int newScale = checkScale((long)scale * n);
2024         return new BigDecimal(this.inflated().pow(n), newScale);
2025     }
2026 
2027 
2028     /**
2029      * Returns a {@code BigDecimal} whose value is
2030      * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
2031      * the core algorithm defined in ANSI standard X3.274-1996 with
2032      * rounding according to the context settings.  In general, the
2033      * returned numerical value is within two ulps of the exact
2034      * numerical value for the chosen precision.  Note that future
2035      * releases may use a different algorithm with a decreased
2036      * allowable error bound and increased allowable exponent range.
2037      *
2038      * <p>The X3.274-1996 algorithm is:
2039      *
2040      * <ul>
2041      * <li> An {@code ArithmeticException} exception is thrown if
2042      *  <ul>
2043      *    <li>{@code abs(n) > 999999999}
2044      *    <li>{@code mc.precision == 0} and {@code n < 0}
2045      *    <li>{@code mc.precision > 0} and {@code n} has more than
2046      *    {@code mc.precision} decimal digits
2047      *  </ul>
2048      *
2049      * <li> if {@code n} is zero, {@link #ONE} is returned even if
2050      * {@code this} is zero, otherwise
2051      * <ul>
2052      *   <li> if {@code n} is positive, the result is calculated via
2053      *   the repeated squaring technique into a single accumulator.
2054      *   The individual multiplications with the accumulator use the
2055      *   same math context settings as in {@code mc} except for a
2056      *   precision increased to {@code mc.precision + elength + 1}
2057      *   where {@code elength} is the number of decimal digits in
2058      *   {@code n}.
2059      *
2060      *   <li> if {@code n} is negative, the result is calculated as if
2061      *   {@code n} were positive; this value is then divided into one
2062      *   using the working precision specified above.
2063      *
2064      *   <li> The final value from either the positive or negative case
2065      *   is then rounded to the destination precision.
2066      *   </ul>
2067      * </ul>
2068      *
2069      * @param  n power to raise this {@code BigDecimal} to.
2070      * @param  mc the context to use.
2071      * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
2072      *         algorithm
2073      * @throws ArithmeticException if the result is inexact but the
2074      *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
2075      *         of range.
2076      * @since  1.5
2077      */
2078     public BigDecimal pow(int n, MathContext mc) {
2079         if (mc.precision == 0)
2080             return pow(n);
2081         if (n < -999999999 || n > 999999999)
2082             throw new ArithmeticException("Invalid operation");
2083         if (n == 0)
2084             return ONE;                      // x**0 == 1 in X3.274
2085         BigDecimal lhs = this;
2086         MathContext workmc = mc;           // working settings
2087         int mag = Math.abs(n);               // magnitude of n
2088         if (mc.precision > 0) {
2089             int elength = longDigitLength(mag); // length of n in digits
2090             if (elength > mc.precision)        // X3.274 rule
2091                 throw new ArithmeticException("Invalid operation");
2092             workmc = new MathContext(mc.precision + elength + 1,
2093                                       mc.roundingMode);
2094         }
2095         // ready to carry out power calculation...
2096         BigDecimal acc = ONE;           // accumulator
2097         boolean seenbit = false;        // set once we've seen a 1-bit
2098         for (int i=1;;i++) {            // for each bit [top bit ignored]
2099             mag += mag;                 // shift left 1 bit
2100             if (mag < 0) {              // top bit is set
2101                 seenbit = true;         // OK, we're off
2102                 acc = acc.multiply(lhs, workmc); // acc=acc*x
2103             }
2104             if (i == 31)
2105                 break;                  // that was the last bit
2106             if (seenbit)
2107                 acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
2108                 // else (!seenbit) no point in squaring ONE
2109         }
2110         // if negative n, calculate the reciprocal using working precision
2111         if (n < 0) // [hence mc.precision>0]
2112             acc=ONE.divide(acc, workmc);
2113         // round to final precision and strip zeros
2114         return doRound(acc, mc);
2115     }
2116 
2117     /**
2118      * Returns a {@code BigDecimal} whose value is the absolute value
2119      * of this {@code BigDecimal}, and whose scale is
2120      * {@code this.scale()}.
2121      *
2122      * @return {@code abs(this)}
2123      */
2124     public BigDecimal abs() {
2125         return (signum() < 0 ? negate() : this);
2126     }
2127 
2128     /**
2129      * Returns a {@code BigDecimal} whose value is the absolute value
2130      * of this {@code BigDecimal}, with rounding according to the
2131      * context settings.
2132      *
2133      * @param mc the context to use.
2134      * @return {@code abs(this)}, rounded as necessary.
2135      * @throws ArithmeticException if the result is inexact but the
2136      *         rounding mode is {@code UNNECESSARY}.
2137      * @since 1.5
2138      */
2139     public BigDecimal abs(MathContext mc) {
2140         return (signum() < 0 ? negate(mc) : plus(mc));
2141     }
2142 
2143     /**
2144      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2145      * and whose scale is {@code this.scale()}.
2146      *
2147      * @return {@code -this}.
2148      */
2149     public BigDecimal negate() {
2150         if (intCompact == INFLATED) {
2151             return new BigDecimal(intVal.negate(), INFLATED, scale, precision);
2152         } else {
2153             return valueOf(-intCompact, scale, precision);
2154         }
2155     }
2156 
2157     /**
2158      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2159      * with rounding according to the context settings.
2160      *
2161      * @param mc the context to use.
2162      * @return {@code -this}, rounded as necessary.
2163      * @throws ArithmeticException if the result is inexact but the
2164      *         rounding mode is {@code UNNECESSARY}.
2165      * @since  1.5
2166      */
2167     public BigDecimal negate(MathContext mc) {
2168         return negate().plus(mc);
2169     }
2170 
2171     /**
2172      * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2173      * scale is {@code this.scale()}.
2174      *
2175      * <p>This method, which simply returns this {@code BigDecimal}
2176      * is included for symmetry with the unary minus method {@link
2177      * #negate()}.
2178      *
2179      * @return {@code this}.
2180      * @see #negate()
2181      * @since  1.5
2182      */
2183     public BigDecimal plus() {
2184         return this;
2185     }
2186 
2187     /**
2188      * Returns a {@code BigDecimal} whose value is {@code (+this)},
2189      * with rounding according to the context settings.
2190      *
2191      * <p>The effect of this method is identical to that of the {@link
2192      * #round(MathContext)} method.
2193      *
2194      * @param mc the context to use.
2195      * @return {@code this}, rounded as necessary.  A zero result will
2196      *         have a scale of 0.
2197      * @throws ArithmeticException if the result is inexact but the
2198      *         rounding mode is {@code UNNECESSARY}.
2199      * @see    #round(MathContext)
2200      * @since  1.5
2201      */
2202     public BigDecimal plus(MathContext mc) {
2203         if (mc.precision == 0)                 // no rounding please
2204             return this;
2205         return doRound(this, mc);
2206     }
2207 
2208     /**
2209      * Returns the signum function of this {@code BigDecimal}.
2210      *
2211      * @return -1, 0, or 1 as the value of this {@code BigDecimal}
2212      *         is negative, zero, or positive.
2213      */
2214     public int signum() {
2215         return (intCompact != INFLATED)?
2216             Long.signum(intCompact):
2217             intVal.signum();
2218     }
2219 
2220     /**
2221      * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
2222      * or positive, the scale is the number of digits to the right of
2223      * the decimal point.  If negative, the unscaled value of the
2224      * number is multiplied by ten to the power of the negation of the
2225      * scale.  For example, a scale of {@code -3} means the unscaled
2226      * value is multiplied by 1000.
2227      *
2228      * @return the scale of this {@code BigDecimal}.
2229      */
2230     public int scale() {
2231         return scale;
2232     }
2233 
2234     /**
2235      * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2236      * precision is the number of digits in the unscaled value.)
2237      *
2238      * <p>The precision of a zero value is 1.
2239      *
2240      * @return the precision of this {@code BigDecimal}.
2241      * @since  1.5
2242      */
2243     public int precision() {
2244         int result = precision;
2245         if (result == 0) {
2246             long s = intCompact;
2247             if (s != INFLATED)
2248                 result = longDigitLength(s);
2249             else
2250                 result = bigDigitLength(intVal);
2251             precision = result;
2252         }
2253         return result;
2254     }
2255 
2256 
2257     /**
2258      * Returns a {@code BigInteger} whose value is the <i>unscaled
2259      * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
2260      * 10<sup>this.scale()</sup>)</tt>.)
2261      *
2262      * @return the unscaled value of this {@code BigDecimal}.
2263      * @since  1.2
2264      */
2265     public BigInteger unscaledValue() {
2266         return this.inflated();
2267     }
2268 
2269     // Rounding Modes
2270 
2271     /**
2272      * Rounding mode to round away from zero.  Always increments the
2273      * digit prior to a nonzero discarded fraction.  Note that this rounding
2274      * mode never decreases the magnitude of the calculated value.
2275      */
2276     public final static int ROUND_UP =           0;
2277 
2278     /**
2279      * Rounding mode to round towards zero.  Never increments the digit
2280      * prior to a discarded fraction (i.e., truncates).  Note that this
2281      * rounding mode never increases the magnitude of the calculated value.
2282      */
2283     public final static int ROUND_DOWN =         1;
2284 
2285     /**
2286      * Rounding mode to round towards positive infinity.  If the
2287      * {@code BigDecimal} is positive, behaves as for
2288      * {@code ROUND_UP}; if negative, behaves as for
2289      * {@code ROUND_DOWN}.  Note that this rounding mode never
2290      * decreases the calculated value.
2291      */
2292     public final static int ROUND_CEILING =      2;
2293 
2294     /**
2295      * Rounding mode to round towards negative infinity.  If the
2296      * {@code BigDecimal} is positive, behave as for
2297      * {@code ROUND_DOWN}; if negative, behave as for
2298      * {@code ROUND_UP}.  Note that this rounding mode never
2299      * increases the calculated value.
2300      */
2301     public final static int ROUND_FLOOR =        3;
2302 
2303     /**
2304      * Rounding mode to round towards {@literal "nearest neighbor"}
2305      * unless both neighbors are equidistant, in which case round up.
2306      * Behaves as for {@code ROUND_UP} if the discarded fraction is
2307      * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
2308      * that this is the rounding mode that most of us were taught in
2309      * grade school.
2310      */
2311     public final static int ROUND_HALF_UP =      4;
2312 
2313     /**
2314      * Rounding mode to round towards {@literal "nearest neighbor"}
2315      * unless both neighbors are equidistant, in which case round
2316      * down.  Behaves as for {@code ROUND_UP} if the discarded
2317      * fraction is {@literal >} 0.5; otherwise, behaves as for
2318      * {@code ROUND_DOWN}.
2319      */
2320     public final static int ROUND_HALF_DOWN =    5;
2321 
2322     /**
2323      * Rounding mode to round towards the {@literal "nearest neighbor"}
2324      * unless both neighbors are equidistant, in which case, round
2325      * towards the even neighbor.  Behaves as for
2326      * {@code ROUND_HALF_UP} if the digit to the left of the
2327      * discarded fraction is odd; behaves as for
2328      * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
2329      * rounding mode that minimizes cumulative error when applied
2330      * repeatedly over a sequence of calculations.
2331      */
2332     public final static int ROUND_HALF_EVEN =    6;
2333 
2334     /**
2335      * Rounding mode to assert that the requested operation has an exact
2336      * result, hence no rounding is necessary.  If this rounding mode is
2337      * specified on an operation that yields an inexact result, an
2338      * {@code ArithmeticException} is thrown.
2339      */
2340     public final static int ROUND_UNNECESSARY =  7;
2341 
2342 
2343     // Scaling/Rounding Operations
2344 
2345     /**
2346      * Returns a {@code BigDecimal} rounded according to the
2347      * {@code MathContext} settings.  If the precision setting is 0 then
2348      * no rounding takes place.
2349      *
2350      * <p>The effect of this method is identical to that of the
2351      * {@link #plus(MathContext)} method.
2352      *
2353      * @param mc the context to use.
2354      * @return a {@code BigDecimal} rounded according to the
2355      *         {@code MathContext} settings.
2356      * @throws ArithmeticException if the rounding mode is
2357      *         {@code UNNECESSARY} and the
2358      *         {@code BigDecimal}  operation would require rounding.
2359      * @see    #plus(MathContext)
2360      * @since  1.5
2361      */
2362     public BigDecimal round(MathContext mc) {
2363         return plus(mc);
2364     }
2365 
2366     /**
2367      * Returns a {@code BigDecimal} whose scale is the specified
2368      * value, and whose unscaled value is determined by multiplying or
2369      * dividing this {@code BigDecimal}'s unscaled value by the
2370      * appropriate power of ten to maintain its overall value.  If the
2371      * scale is reduced by the operation, the unscaled value must be
2372      * divided (rather than multiplied), and the value may be changed;
2373      * in this case, the specified rounding mode is applied to the
2374      * division.
2375      *
2376      * <p>Note that since BigDecimal objects are immutable, calls of
2377      * this method do <i>not</i> result in the original object being
2378      * modified, contrary to the usual convention of having methods
2379      * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2380      * Instead, {@code setScale} returns an object with the proper
2381      * scale; the returned object may or may not be newly allocated.
2382      *
2383      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2384      * @param  roundingMode The rounding mode to apply.
2385      * @return a {@code BigDecimal} whose scale is the specified value,
2386      *         and whose unscaled value is determined by multiplying or
2387      *         dividing this {@code BigDecimal}'s unscaled value by the
2388      *         appropriate power of ten to maintain its overall value.
2389      * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2390      *         and the specified scaling operation would require
2391      *         rounding.
2392      * @see    RoundingMode
2393      * @since  1.5
2394      */
2395     public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2396         return setScale(newScale, roundingMode.oldMode);
2397     }
2398 
2399     /**
2400      * Returns a {@code BigDecimal} whose scale is the specified
2401      * value, and whose unscaled value is determined by multiplying or
2402      * dividing this {@code BigDecimal}'s unscaled value by the
2403      * appropriate power of ten to maintain its overall value.  If the
2404      * scale is reduced by the operation, the unscaled value must be
2405      * divided (rather than multiplied), and the value may be changed;
2406      * in this case, the specified rounding mode is applied to the
2407      * division.
2408      *
2409      * <p>Note that since BigDecimal objects are immutable, calls of
2410      * this method do <i>not</i> result in the original object being
2411      * modified, contrary to the usual convention of having methods
2412      * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2413      * Instead, {@code setScale} returns an object with the proper
2414      * scale; the returned object may or may not be newly allocated.
2415      *
2416      * <p>The new {@link #setScale(int, RoundingMode)} method should
2417      * be used in preference to this legacy method.
2418      *
2419      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2420      * @param  roundingMode The rounding mode to apply.
2421      * @return a {@code BigDecimal} whose scale is the specified value,
2422      *         and whose unscaled value is determined by multiplying or
2423      *         dividing this {@code BigDecimal}'s unscaled value by the
2424      *         appropriate power of ten to maintain its overall value.
2425      * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2426      *         and the specified scaling operation would require
2427      *         rounding.
2428      * @throws IllegalArgumentException if {@code roundingMode} does not
2429      *         represent a valid rounding mode.
2430      * @see    #ROUND_UP
2431      * @see    #ROUND_DOWN
2432      * @see    #ROUND_CEILING
2433      * @see    #ROUND_FLOOR
2434      * @see    #ROUND_HALF_UP
2435      * @see    #ROUND_HALF_DOWN
2436      * @see    #ROUND_HALF_EVEN
2437      * @see    #ROUND_UNNECESSARY
2438      */
2439     public BigDecimal setScale(int newScale, int roundingMode) {
2440         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2441             throw new IllegalArgumentException("Invalid rounding mode");
2442 
2443         int oldScale = this.scale;
2444         if (newScale == oldScale)        // easy case
2445             return this;
2446         if (this.signum() == 0)            // zero can have any scale
2447             return zeroValueOf(newScale);
2448         if(this.intCompact!=INFLATED) {
2449             long rs = this.intCompact;
2450             if (newScale > oldScale) {
2451                 int raise = checkScale((long) newScale - oldScale);
2452                 if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {
2453                     return valueOf(rs,newScale);
2454                 }
2455                 BigInteger rb = bigMultiplyPowerTen(raise);
2456                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2457             } else {
2458                 // newScale < oldScale -- drop some digits
2459                 // Can't predict the precision due to the effect of rounding.
2460                 int drop = checkScale((long) oldScale - newScale);
2461                 if (drop < LONG_TEN_POWERS_TABLE.length) {
2462                     return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);
2463                 } else {
2464                     return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);
2465                 }
2466             }
2467         } else {
2468             if (newScale > oldScale) {
2469                 int raise = checkScale((long) newScale - oldScale);
2470                 BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);
2471                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2472             } else {
2473                 // newScale < oldScale -- drop some digits
2474                 // Can't predict the precision due to the effect of rounding.
2475                 int drop = checkScale((long) oldScale - newScale);
2476                 if (drop < LONG_TEN_POWERS_TABLE.length)
2477                     return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,
2478                                           newScale);
2479                 else
2480                     return divideAndRound(this.intVal,  bigTenToThe(drop), newScale, roundingMode, newScale);
2481             }
2482         }
2483     }
2484 
2485     /**
2486      * Returns a {@code BigDecimal} whose scale is the specified
2487      * value, and whose value is numerically equal to this
2488      * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2489      * if this is not possible.
2490      *
2491      * <p>This call is typically used to increase the scale, in which
2492      * case it is guaranteed that there exists a {@code BigDecimal}
2493      * of the specified scale and the correct value.  The call can
2494      * also be used to reduce the scale if the caller knows that the
2495      * {@code BigDecimal} has sufficiently many zeros at the end of
2496      * its fractional part (i.e., factors of ten in its integer value)
2497      * to allow for the rescaling without changing its value.
2498      *
2499      * <p>This method returns the same result as the two-argument
2500      * versions of {@code setScale}, but saves the caller the trouble
2501      * of specifying a rounding mode in cases where it is irrelevant.
2502      *
2503      * <p>Note that since {@code BigDecimal} objects are immutable,
2504      * calls of this method do <i>not</i> result in the original
2505      * object being modified, contrary to the usual convention of
2506      * having methods named <tt>set<i>X</i></tt> mutate field
2507      * <i>{@code X}</i>.  Instead, {@code setScale} returns an
2508      * object with the proper scale; the returned object may or may
2509      * not be newly allocated.
2510      *
2511      * @param  newScale scale of the {@code BigDecimal} value to be returned.
2512      * @return a {@code BigDecimal} whose scale is the specified value, and
2513      *         whose unscaled value is determined by multiplying or dividing
2514      *         this {@code BigDecimal}'s unscaled value by the appropriate
2515      *         power of ten to maintain its overall value.
2516      * @throws ArithmeticException if the specified scaling operation would
2517      *         require rounding.
2518      * @see    #setScale(int, int)
2519      * @see    #setScale(int, RoundingMode)
2520      */
2521     public BigDecimal setScale(int newScale) {
2522         return setScale(newScale, ROUND_UNNECESSARY);
2523     }
2524 
2525     // Decimal Point Motion Operations
2526 
2527     /**
2528      * Returns a {@code BigDecimal} which is equivalent to this one
2529      * with the decimal point moved {@code n} places to the left.  If
2530      * {@code n} is non-negative, the call merely adds {@code n} to
2531      * the scale.  If {@code n} is negative, the call is equivalent
2532      * to {@code movePointRight(-n)}.  The {@code BigDecimal}
2533      * returned by this call has value <tt>(this &times;
2534      * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
2535      * 0)}.
2536      *
2537      * @param  n number of places to move the decimal point to the left.
2538      * @return a {@code BigDecimal} which is equivalent to this one with the
2539      *         decimal point moved {@code n} places to the left.
2540      * @throws ArithmeticException if scale overflows.
2541      */
2542     public BigDecimal movePointLeft(int n) {
2543         // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2544         int newScale = checkScale((long)scale + n);
2545         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2546         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2547     }
2548 
2549     /**
2550      * Returns a {@code BigDecimal} which is equivalent to this one
2551      * with the decimal point moved {@code n} places to the right.
2552      * If {@code n} is non-negative, the call merely subtracts
2553      * {@code n} from the scale.  If {@code n} is negative, the call
2554      * is equivalent to {@code movePointLeft(-n)}.  The
2555      * {@code BigDecimal} returned by this call has value <tt>(this
2556      * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
2557      * 0)}.
2558      *
2559      * @param  n number of places to move the decimal point to the right.
2560      * @return a {@code BigDecimal} which is equivalent to this one
2561      *         with the decimal point moved {@code n} places to the right.
2562      * @throws ArithmeticException if scale overflows.
2563      */
2564     public BigDecimal movePointRight(int n) {
2565         // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2566         int newScale = checkScale((long)scale - n);
2567         BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2568         return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2569     }
2570 
2571     /**
2572      * Returns a BigDecimal whose numerical value is equal to
2573      * ({@code this} * 10<sup>n</sup>).  The scale of
2574      * the result is {@code (this.scale() - n)}.
2575      *
2576      * @throws ArithmeticException if the scale would be
2577      *         outside the range of a 32-bit integer.
2578      *
2579      * @since 1.5
2580      */
2581     public BigDecimal scaleByPowerOfTen(int n) {
2582         return new BigDecimal(intVal, intCompact,
2583                               checkScale((long)scale - n), precision);
2584     }
2585 
2586     /**
2587      * Returns a {@code BigDecimal} which is numerically equal to
2588      * this one but with any trailing zeros removed from the
2589      * representation.  For example, stripping the trailing zeros from
2590      * the {@code BigDecimal} value {@code 600.0}, which has
2591      * [{@code BigInteger}, {@code scale}] components equals to
2592      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2593      * {@code scale}] components equals to [6, -2]
2594      *
2595      * @return a numerically equal {@code BigDecimal} with any
2596      * trailing zeros removed.
2597      * @since 1.5
2598      */
2599     public BigDecimal stripTrailingZeros() {
2600         if(intCompact!=INFLATED) {
2601             return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
2602         } else {
2603             return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
2604         }
2605     }
2606 
2607     // Comparison Operations
2608 
2609     /**
2610      * Compares this {@code BigDecimal} with the specified
2611      * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2612      * equal in value but have a different scale (like 2.0 and 2.00)
2613      * are considered equal by this method.  This method is provided
2614      * in preference to individual methods for each of the six boolean
2615      * comparison operators ({@literal <}, ==,
2616      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2617      * suggested idiom for performing these comparisons is:
2618      * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2619      * &lt;<i>op</i>&gt; is one of the six comparison operators.
2620      *
2621      * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
2622      *         to be compared.
2623      * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2624      *          less than, equal to, or greater than {@code val}.
2625      */
2626     public int compareTo(BigDecimal val) {
2627         // Quick path for equal scale and non-inflated case.
2628         if (scale == val.scale) {
2629             long xs = intCompact;
2630             long ys = val.intCompact;
2631             if (xs != INFLATED && ys != INFLATED)
2632                 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2633         }
2634         int xsign = this.signum();
2635         int ysign = val.signum();
2636         if (xsign != ysign)
2637             return (xsign > ysign) ? 1 : -1;
2638         if (xsign == 0)
2639             return 0;
2640         int cmp = compareMagnitude(val);
2641         return (xsign > 0) ? cmp : -cmp;
2642     }
2643 
2644     /**
2645      * Version of compareTo that ignores sign.
2646      */
2647     private int compareMagnitude(BigDecimal val) {
2648         // Match scales, avoid unnecessary inflation
2649         long ys = val.intCompact;
2650         long xs = this.intCompact;
2651         if (xs == 0)
2652             return (ys == 0) ? 0 : -1;
2653         if (ys == 0)
2654             return 1;
2655 
2656         int sdiff = this.scale - val.scale;
2657         if (sdiff != 0) {
2658             // Avoid matching scales if the (adjusted) exponents differ
2659             int xae = this.precision() - this.scale;   // [-1]
2660             int yae = val.precision() - val.scale;     // [-1]
2661             if (xae < yae)
2662                 return -1;
2663             if (xae > yae)
2664                 return 1;
2665             BigInteger rb = null;
2666             if (sdiff < 0) {
2667                 if ( (xs == INFLATED ||
2668                       (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
2669                      ys == INFLATED) {
2670                     rb = bigMultiplyPowerTen(-sdiff);
2671                     return rb.compareMagnitude(val.intVal);
2672                 }
2673             } else { // sdiff > 0
2674                 if ( (ys == INFLATED ||
2675                       (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
2676                      xs == INFLATED) {
2677                     rb = val.bigMultiplyPowerTen(sdiff);
2678                     return this.intVal.compareMagnitude(rb);
2679                 }
2680             }
2681         }
2682         if (xs != INFLATED)
2683             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2684         else if (ys != INFLATED)
2685             return 1;
2686         else
2687             return this.intVal.compareMagnitude(val.intVal);
2688     }
2689 
2690     /**
2691      * Compares this {@code BigDecimal} with the specified
2692      * {@code Object} for equality.  Unlike {@link
2693      * #compareTo(BigDecimal) compareTo}, this method considers two
2694      * {@code BigDecimal} objects equal only if they are equal in
2695      * value and scale (thus 2.0 is not equal to 2.00 when compared by
2696      * this method).
2697      *
2698      * @param  x {@code Object} to which this {@code BigDecimal} is
2699      *         to be compared.
2700      * @return {@code true} if and only if the specified {@code Object} is a
2701      *         {@code BigDecimal} whose value and scale are equal to this
2702      *         {@code BigDecimal}'s.
2703      * @see    #compareTo(java.math.BigDecimal)
2704      * @see    #hashCode
2705      */
2706     @Override
2707     public boolean equals(Object x) {
2708         if (!(x instanceof BigDecimal))
2709             return false;
2710         BigDecimal xDec = (BigDecimal) x;
2711         if (x == this)
2712             return true;
2713         if (scale != xDec.scale)
2714             return false;
2715         long s = this.intCompact;
2716         long xs = xDec.intCompact;
2717         if (s != INFLATED) {
2718             if (xs == INFLATED)
2719                 xs = compactValFor(xDec.intVal);
2720             return xs == s;
2721         } else if (xs != INFLATED)
2722             return xs == compactValFor(this.intVal);
2723 
2724         return this.inflated().equals(xDec.inflated());
2725     }
2726 
2727     /**
2728      * Returns the minimum of this {@code BigDecimal} and
2729      * {@code val}.
2730      *
2731      * @param  val value with which the minimum is to be computed.
2732      * @return the {@code BigDecimal} whose value is the lesser of this
2733      *         {@code BigDecimal} and {@code val}.  If they are equal,
2734      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2735      *         method, {@code this} is returned.
2736      * @see    #compareTo(java.math.BigDecimal)
2737      */
2738     public BigDecimal min(BigDecimal val) {
2739         return (compareTo(val) <= 0 ? this : val);
2740     }
2741 
2742     /**
2743      * Returns the maximum of this {@code BigDecimal} and {@code val}.
2744      *
2745      * @param  val value with which the maximum is to be computed.
2746      * @return the {@code BigDecimal} whose value is the greater of this
2747      *         {@code BigDecimal} and {@code val}.  If they are equal,
2748      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2749      *         method, {@code this} is returned.
2750      * @see    #compareTo(java.math.BigDecimal)
2751      */
2752     public BigDecimal max(BigDecimal val) {
2753         return (compareTo(val) >= 0 ? this : val);
2754     }
2755 
2756     // Hash Function
2757 
2758     /**
2759      * Returns the hash code for this {@code BigDecimal}.  Note that
2760      * two {@code BigDecimal} objects that are numerically equal but
2761      * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2762      * have the same hash code.
2763      *
2764      * @return hash code for this {@code BigDecimal}.
2765      * @see #equals(Object)
2766      */
2767     @Override
2768     public int hashCode() {
2769         if (intCompact != INFLATED) {
2770             long val2 = (intCompact < 0)? -intCompact : intCompact;
2771             int temp = (int)( ((int)(val2 >>> 32)) * 31  +
2772                               (val2 & LONG_MASK));
2773             return 31*((intCompact < 0) ?-temp:temp) + scale;
2774         } else
2775             return 31*intVal.hashCode() + scale;
2776     }
2777 
2778     // Format Converters
2779 
2780     /**
2781      * Returns the string representation of this {@code BigDecimal},
2782      * using scientific notation if an exponent is needed.
2783      *
2784      * <p>A standard canonical string form of the {@code BigDecimal}
2785      * is created as though by the following steps: first, the
2786      * absolute value of the unscaled value of the {@code BigDecimal}
2787      * is converted to a string in base ten using the characters
2788      * {@code '0'} through {@code '9'} with no leading zeros (except
2789      * if its value is zero, in which case a single {@code '0'}
2790      * character is used).
2791      *
2792      * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2793      * negated scale, plus the number of characters in the converted
2794      * unscaled value, less one.  That is,
2795      * {@code -scale+(ulength-1)}, where {@code ulength} is the
2796      * length of the absolute value of the unscaled value in decimal
2797      * digits (its <i>precision</i>).
2798      *
2799      * <p>If the scale is greater than or equal to zero and the
2800      * adjusted exponent is greater than or equal to {@code -6}, the
2801      * number will be converted to a character form without using
2802      * exponential notation.  In this case, if the scale is zero then
2803      * no decimal point is added and if the scale is positive a
2804      * decimal point will be inserted with the scale specifying the
2805      * number of characters to the right of the decimal point.
2806      * {@code '0'} characters are added to the left of the converted
2807      * unscaled value as necessary.  If no character precedes the
2808      * decimal point after this insertion then a conventional
2809      * {@code '0'} character is prefixed.
2810      *
2811      * <p>Otherwise (that is, if the scale is negative, or the
2812      * adjusted exponent is less than {@code -6}), the number will be
2813      * converted to a character form using exponential notation.  In
2814      * this case, if the converted {@code BigInteger} has more than
2815      * one digit a decimal point is inserted after the first digit.
2816      * An exponent in character form is then suffixed to the converted
2817      * unscaled value (perhaps with inserted decimal point); this
2818      * comprises the letter {@code 'E'} followed immediately by the
2819      * adjusted exponent converted to a character form.  The latter is
2820      * in base ten, using the characters {@code '0'} through
2821      * {@code '9'} with no leading zeros, and is always prefixed by a
2822      * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the
2823      * adjusted exponent is negative, {@code '+'}
2824      * (<tt>'&#92;u002B'</tt>) otherwise).
2825      *
2826      * <p>Finally, the entire string is prefixed by a minus sign
2827      * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled
2828      * value is less than zero.  No sign character is prefixed if the
2829      * unscaled value is zero or positive.
2830      *
2831      * <p><b>Examples:</b>
2832      * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2833      * on the left, the resulting string is shown on the right.
2834      * <pre>
2835      * [123,0]      "123"
2836      * [-123,0]     "-123"
2837      * [123,-1]     "1.23E+3"
2838      * [123,-3]     "1.23E+5"
2839      * [123,1]      "12.3"
2840      * [123,5]      "0.00123"
2841      * [123,10]     "1.23E-8"
2842      * [-123,12]    "-1.23E-10"
2843      * </pre>
2844      *
2845      * <b>Notes:</b>
2846      * <ol>
2847      *
2848      * <li>There is a one-to-one mapping between the distinguishable
2849      * {@code BigDecimal} values and the result of this conversion.
2850      * That is, every distinguishable {@code BigDecimal} value
2851      * (unscaled value and scale) has a unique string representation
2852      * as a result of using {@code toString}.  If that string
2853      * representation is converted back to a {@code BigDecimal} using
2854      * the {@link #BigDecimal(String)} constructor, then the original
2855      * value will be recovered.
2856      *
2857      * <li>The string produced for a given number is always the same;
2858      * it is not affected by locale.  This means that it can be used
2859      * as a canonical string representation for exchanging decimal
2860      * data, or as a key for a Hashtable, etc.  Locale-sensitive
2861      * number formatting and parsing is handled by the {@link
2862      * java.text.NumberFormat} class and its subclasses.
2863      *
2864      * <li>The {@link #toEngineeringString} method may be used for
2865      * presenting numbers with exponents in engineering notation, and the
2866      * {@link #setScale(int,RoundingMode) setScale} method may be used for
2867      * rounding a {@code BigDecimal} so it has a known number of digits after
2868      * the decimal point.
2869      *
2870      * <li>The digit-to-character mapping provided by
2871      * {@code Character.forDigit} is used.
2872      *
2873      * </ol>
2874      *
2875      * @return string representation of this {@code BigDecimal}.
2876      * @see    Character#forDigit
2877      * @see    #BigDecimal(java.lang.String)
2878      */
2879     @Override
2880     public String toString() {
2881         String sc = stringCache;
2882         if (sc == null)
2883             stringCache = sc = layoutChars(true);
2884         return sc;
2885     }
2886 
2887     /**
2888      * Returns a string representation of this {@code BigDecimal},
2889      * using engineering notation if an exponent is needed.
2890      *
2891      * <p>Returns a string that represents the {@code BigDecimal} as
2892      * described in the {@link #toString()} method, except that if
2893      * exponential notation is used, the power of ten is adjusted to
2894      * be a multiple of three (engineering notation) such that the
2895      * integer part of nonzero values will be in the range 1 through
2896      * 999.  If exponential notation is used for zero values, a
2897      * decimal point and one or two fractional zero digits are used so
2898      * that the scale of the zero value is preserved.  Note that
2899      * unlike the output of {@link #toString()}, the output of this
2900      * method is <em>not</em> guaranteed to recover the same [integer,
2901      * scale] pair of this {@code BigDecimal} if the output string is
2902      * converting back to a {@code BigDecimal} using the {@linkplain
2903      * #BigDecimal(String) string constructor}.  The result of this method meets
2904      * the weaker constraint of always producing a numerically equal
2905      * result from applying the string constructor to the method's output.
2906      *
2907      * @return string representation of this {@code BigDecimal}, using
2908      *         engineering notation if an exponent is needed.
2909      * @since  1.5
2910      */
2911     public String toEngineeringString() {
2912         return layoutChars(false);
2913     }
2914 
2915     /**
2916      * Returns a string representation of this {@code BigDecimal}
2917      * without an exponent field.  For values with a positive scale,
2918      * the number of digits to the right of the decimal point is used
2919      * to indicate scale.  For values with a zero or negative scale,
2920      * the resulting string is generated as if the value were
2921      * converted to a numerically equal value with zero scale and as
2922      * if all the trailing zeros of the zero scale value were present
2923      * in the result.
2924      *
2925      * The entire string is prefixed by a minus sign character '-'
2926      * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
2927      * zero. No sign character is prefixed if the unscaled value is
2928      * zero or positive.
2929      *
2930      * Note that if the result of this method is passed to the
2931      * {@linkplain #BigDecimal(String) string constructor}, only the
2932      * numerical value of this {@code BigDecimal} will necessarily be
2933      * recovered; the representation of the new {@code BigDecimal}
2934      * may have a different scale.  In particular, if this
2935      * {@code BigDecimal} has a negative scale, the string resulting
2936      * from this method will have a scale of zero when processed by
2937      * the string constructor.
2938      *
2939      * (This method behaves analogously to the {@code toString}
2940      * method in 1.4 and earlier releases.)
2941      *
2942      * @return a string representation of this {@code BigDecimal}
2943      * without an exponent field.
2944      * @since 1.5
2945      * @see #toString()
2946      * @see #toEngineeringString()
2947      */
2948     public String toPlainString() {
2949         if(scale==0) {
2950             if(intCompact!=INFLATED) {
2951                 return Long.toString(intCompact);
2952             } else {
2953                 return intVal.toString();
2954             }
2955         }
2956         if(this.scale<0) { // No decimal point
2957             if(signum()==0) {
2958                 return "0";
2959             }
2960             int tailingZeros = checkScaleNonZero((-(long)scale));
2961             StringBuilder buf;
2962             if(intCompact!=INFLATED) {
2963                 buf = new StringBuilder(20+tailingZeros);
2964                 buf.append(intCompact);
2965             } else {
2966                 String str = intVal.toString();
2967                 buf = new StringBuilder(str.length()+tailingZeros);
2968                 buf.append(str);
2969             }
2970             for (int i = 0; i < tailingZeros; i++)
2971                 buf.append('0');
2972             return buf.toString();
2973         }
2974         String str ;
2975         if(intCompact!=INFLATED) {
2976             str = Long.toString(Math.abs(intCompact));
2977         } else {
2978             str = intVal.abs().toString();
2979         }
2980         return getValueString(signum(), str, scale);
2981     }
2982 
2983     /* Returns a digit.digit string */
2984     private String getValueString(int signum, String intString, int scale) {
2985         /* Insert decimal point */
2986         StringBuilder buf;
2987         int insertionPoint = intString.length() - scale;
2988         if (insertionPoint == 0) {  /* Point goes right before intVal */
2989             return (signum<0 ? "-0." : "0.") + intString;
2990         } else if (insertionPoint > 0) { /* Point goes inside intVal */
2991             buf = new StringBuilder(intString);
2992             buf.insert(insertionPoint, '.');
2993             if (signum < 0)
2994                 buf.insert(0, '-');
2995         } else { /* We must insert zeros between point and intVal */
2996             buf = new StringBuilder(3-insertionPoint + intString.length());
2997             buf.append(signum<0 ? "-0." : "0.");
2998             for (int i=0; i<-insertionPoint; i++)
2999                 buf.append('0');
3000             buf.append(intString);
3001         }
3002         return buf.toString();
3003     }
3004 
3005     /**
3006      * Converts this {@code BigDecimal} to a {@code BigInteger}.
3007      * This conversion is analogous to the
3008      * <i>narrowing primitive conversion</i> from {@code double} to
3009      * {@code long} as defined in section 5.1.3 of
3010      * <cite>The Java&trade; Language Specification</cite>:
3011      * any fractional part of this
3012      * {@code BigDecimal} will be discarded.  Note that this
3013      * conversion can lose information about the precision of the
3014      * {@code BigDecimal} value.
3015      * <p>
3016      * To have an exception thrown if the conversion is inexact (in
3017      * other words if a nonzero fractional part is discarded), use the
3018      * {@link #toBigIntegerExact()} method.
3019      *
3020      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3021      */
3022     public BigInteger toBigInteger() {
3023         // force to an integer, quietly
3024         return this.setScale(0, ROUND_DOWN).inflated();
3025     }
3026 
3027     /**
3028      * Converts this {@code BigDecimal} to a {@code BigInteger},
3029      * checking for lost information.  An exception is thrown if this
3030      * {@code BigDecimal} has a nonzero fractional part.
3031      *
3032      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3033      * @throws ArithmeticException if {@code this} has a nonzero
3034      *         fractional part.
3035      * @since  1.5
3036      */
3037     public BigInteger toBigIntegerExact() {
3038         // round to an integer, with Exception if decimal part non-0
3039         return this.setScale(0, ROUND_UNNECESSARY).inflated();
3040     }
3041 
3042     /**
3043      * Converts this {@code BigDecimal} to a {@code long}.
3044      * This conversion is analogous to the
3045      * <i>narrowing primitive conversion</i> from {@code double} to
3046      * {@code short} as defined in section 5.1.3 of
3047      * <cite>The Java&trade; Language Specification</cite>:
3048      * any fractional part of this
3049      * {@code BigDecimal} will be discarded, and if the resulting
3050      * "{@code BigInteger}" is too big to fit in a
3051      * {@code long}, only the low-order 64 bits are returned.
3052      * Note that this conversion can lose information about the
3053      * overall magnitude and precision of this {@code BigDecimal} value as well
3054      * as return a result with the opposite sign.
3055      *
3056      * @return this {@code BigDecimal} converted to a {@code long}.
3057      */
3058     public long longValue(){
3059         return (intCompact != INFLATED && scale == 0) ?
3060             intCompact:
3061             toBigInteger().longValue();
3062     }
3063 
3064     /**
3065      * Converts this {@code BigDecimal} to a {@code long}, checking
3066      * for lost information.  If this {@code BigDecimal} has a
3067      * nonzero fractional part or is out of the possible range for a
3068      * {@code long} result then an {@code ArithmeticException} is
3069      * thrown.
3070      *
3071      * @return this {@code BigDecimal} converted to a {@code long}.
3072      * @throws ArithmeticException if {@code this} has a nonzero
3073      *         fractional part, or will not fit in a {@code long}.
3074      * @since  1.5
3075      */
3076     public long longValueExact() {
3077         if (intCompact != INFLATED && scale == 0)
3078             return intCompact;
3079         // If more than 19 digits in integer part it cannot possibly fit
3080         if ((precision() - scale) > 19) // [OK for negative scale too]
3081             throw new java.lang.ArithmeticException("Overflow");
3082         // Fastpath zero and < 1.0 numbers (the latter can be very slow
3083         // to round if very small)
3084         if (this.signum() == 0)
3085             return 0;
3086         if ((this.precision() - this.scale) <= 0)
3087             throw new ArithmeticException("Rounding necessary");
3088         // round to an integer, with Exception if decimal part non-0
3089         BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
3090         if (num.precision() >= 19) // need to check carefully
3091             LongOverflow.check(num);
3092         return num.inflated().longValue();
3093     }
3094 
3095     private static class LongOverflow {
3096         /** BigInteger equal to Long.MIN_VALUE. */
3097         private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3098 
3099         /** BigInteger equal to Long.MAX_VALUE. */
3100         private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3101 
3102         public static void check(BigDecimal num) {
3103             BigInteger intVal = num.inflated();
3104             if (intVal.compareTo(LONGMIN) < 0 ||
3105                 intVal.compareTo(LONGMAX) > 0)
3106                 throw new java.lang.ArithmeticException("Overflow");
3107         }
3108     }
3109 
3110     /**
3111      * Converts this {@code BigDecimal} to an {@code int}.
3112      * This conversion is analogous to the
3113      * <i>narrowing primitive conversion</i> from {@code double} to
3114      * {@code short} as defined in section 5.1.3 of
3115      * <cite>The Java&trade; Language Specification</cite>:
3116      * any fractional part of this
3117      * {@code BigDecimal} will be discarded, and if the resulting
3118      * "{@code BigInteger}" is too big to fit in an
3119      * {@code int}, only the low-order 32 bits are returned.
3120      * Note that this conversion can lose information about the
3121      * overall magnitude and precision of this {@code BigDecimal}
3122      * value as well as return a result with the opposite sign.
3123      *
3124      * @return this {@code BigDecimal} converted to an {@code int}.
3125      */
3126     public int intValue() {
3127         return  (intCompact != INFLATED && scale == 0) ?
3128             (int)intCompact :
3129             toBigInteger().intValue();
3130     }
3131 
3132     /**
3133      * Converts this {@code BigDecimal} to an {@code int}, checking
3134      * for lost information.  If this {@code BigDecimal} has a
3135      * nonzero fractional part or is out of the possible range for an
3136      * {@code int} result then an {@code ArithmeticException} is
3137      * thrown.
3138      *
3139      * @return this {@code BigDecimal} converted to an {@code int}.
3140      * @throws ArithmeticException if {@code this} has a nonzero
3141      *         fractional part, or will not fit in an {@code int}.
3142      * @since  1.5
3143      */
3144     public int intValueExact() {
3145        long num;
3146        num = this.longValueExact();     // will check decimal part
3147        if ((int)num != num)
3148            throw new java.lang.ArithmeticException("Overflow");
3149        return (int)num;
3150     }
3151 
3152     /**
3153      * Converts this {@code BigDecimal} to a {@code short}, checking
3154      * for lost information.  If this {@code BigDecimal} has a
3155      * nonzero fractional part or is out of the possible range for a
3156      * {@code short} result then an {@code ArithmeticException} is
3157      * thrown.
3158      *
3159      * @return this {@code BigDecimal} converted to a {@code short}.
3160      * @throws ArithmeticException if {@code this} has a nonzero
3161      *         fractional part, or will not fit in a {@code short}.
3162      * @since  1.5
3163      */
3164     public short shortValueExact() {
3165        long num;
3166        num = this.longValueExact();     // will check decimal part
3167        if ((short)num != num)
3168            throw new java.lang.ArithmeticException("Overflow");
3169        return (short)num;
3170     }
3171 
3172     /**
3173      * Converts this {@code BigDecimal} to a {@code byte}, checking
3174      * for lost information.  If this {@code BigDecimal} has a
3175      * nonzero fractional part or is out of the possible range for a
3176      * {@code byte} result then an {@code ArithmeticException} is
3177      * thrown.
3178      *
3179      * @return this {@code BigDecimal} converted to a {@code byte}.
3180      * @throws ArithmeticException if {@code this} has a nonzero
3181      *         fractional part, or will not fit in a {@code byte}.
3182      * @since  1.5
3183      */
3184     public byte byteValueExact() {
3185        long num;
3186        num = this.longValueExact();     // will check decimal part
3187        if ((byte)num != num)
3188            throw new java.lang.ArithmeticException("Overflow");
3189        return (byte)num;
3190     }
3191 
3192     /**
3193      * Converts this {@code BigDecimal} to a {@code float}.
3194      * This conversion is similar to the
3195      * <i>narrowing primitive conversion</i> from {@code double} to
3196      * {@code float} as defined in section 5.1.3 of
3197      * <cite>The Java&trade; Language Specification</cite>:
3198      * if this {@code BigDecimal} has too great a
3199      * magnitude to represent as a {@code float}, it will be
3200      * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3201      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3202      * the return value is finite, this conversion can lose
3203      * information about the precision of the {@code BigDecimal}
3204      * value.
3205      *
3206      * @return this {@code BigDecimal} converted to a {@code float}.
3207      */
3208     public float floatValue(){
3209         if(intCompact != INFLATED) {
3210             if (scale == 0) {
3211                 return (float)intCompact;
3212             } else {
3213                 /*
3214                  * If both intCompact and the scale can be exactly
3215                  * represented as float values, perform a single float
3216                  * multiply or divide to compute the (properly
3217                  * rounded) result.
3218                  */
3219                 if (Math.abs(intCompact) < 1L<<22 ) {
3220                     // Don't have too guard against
3221                     // Math.abs(MIN_VALUE) because of outer check
3222                     // against INFLATED.
3223                     if (scale > 0 && scale < float10pow.length) {
3224                         return (float)intCompact / float10pow[scale];
3225                     } else if (scale < 0 && scale > -float10pow.length) {
3226                         return (float)intCompact * float10pow[-scale];
3227                     }
3228                 }
3229             }
3230         }
3231         // Somewhat inefficient, but guaranteed to work.
3232         return Float.parseFloat(this.toString());
3233     }
3234 
3235     /**
3236      * Converts this {@code BigDecimal} to a {@code double}.
3237      * This conversion is similar to the
3238      * <i>narrowing primitive conversion</i> from {@code double} to
3239      * {@code float} as defined in section 5.1.3 of
3240      * <cite>The Java&trade; Language Specification</cite>:
3241      * if this {@code BigDecimal} has too great a
3242      * magnitude represent as a {@code double}, it will be
3243      * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3244      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3245      * the return value is finite, this conversion can lose
3246      * information about the precision of the {@code BigDecimal}
3247      * value.
3248      *
3249      * @return this {@code BigDecimal} converted to a {@code double}.
3250      */
3251     public double doubleValue(){
3252         if(intCompact != INFLATED) {
3253             if (scale == 0) {
3254                 return (double)intCompact;
3255             } else {
3256                 /*
3257                  * If both intCompact and the scale can be exactly
3258                  * represented as double values, perform a single
3259                  * double multiply or divide to compute the (properly
3260                  * rounded) result.
3261                  */
3262                 if (Math.abs(intCompact) < 1L<<52 ) {
3263                     // Don't have too guard against
3264                     // Math.abs(MIN_VALUE) because of outer check
3265                     // against INFLATED.
3266                     if (scale > 0 && scale < double10pow.length) {
3267                         return (double)intCompact / double10pow[scale];
3268                     } else if (scale < 0 && scale > -double10pow.length) {
3269                         return (double)intCompact * double10pow[-scale];
3270                     }
3271                 }
3272             }
3273         }
3274         // Somewhat inefficient, but guaranteed to work.
3275         return Double.parseDouble(this.toString());
3276     }
3277 
3278     /**
3279      * Powers of 10 which can be represented exactly in {@code
3280      * double}.
3281      */
3282     private static final double double10pow[] = {
3283         1.0e0,  1.0e1,  1.0e2,  1.0e3,  1.0e4,  1.0e5,
3284         1.0e6,  1.0e7,  1.0e8,  1.0e9,  1.0e10, 1.0e11,
3285         1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3286         1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3287     };
3288 
3289     /**
3290      * Powers of 10 which can be represented exactly in {@code
3291      * float}.
3292      */
3293     private static final float float10pow[] = {
3294         1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3295         1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3296     };
3297 
3298     /**
3299      * Returns the size of an ulp, a unit in the last place, of this
3300      * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3301      * value is the positive distance between this value and the
3302      * {@code BigDecimal} value next larger in magnitude with the
3303      * same number of digits.  An ulp of a zero value is numerically
3304      * equal to 1 with the scale of {@code this}.  The result is
3305      * stored with the same scale as {@code this} so the result
3306      * for zero and nonzero values is equal to {@code [1,
3307      * this.scale()]}.
3308      *
3309      * @return the size of an ulp of {@code this}
3310      * @since 1.5
3311      */
3312     public BigDecimal ulp() {
3313         return BigDecimal.valueOf(1, this.scale(), 1);
3314     }
3315 
3316     // Private class to build a string representation for BigDecimal object.
3317     // "StringBuilderHelper" is constructed as a thread local variable so it is
3318     // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3319     // representation of BigDecimal. The cmpCharArray holds all the characters for
3320     // the compact representation of BigDecimal (except for '-' sign' if it is
3321     // negative) if its intCompact field is not INFLATED. It is shared by all
3322     // calls to toString() and its variants in that particular thread.
3323     static class StringBuilderHelper {
3324         final StringBuilder sb;    // Placeholder for BigDecimal string
3325         final char[] cmpCharArray; // character array to place the intCompact
3326 
3327         StringBuilderHelper() {
3328             sb = new StringBuilder();
3329             // All non negative longs can be made to fit into 19 character array.
3330             cmpCharArray = new char[19];
3331         }
3332 
3333         // Accessors.
3334         StringBuilder getStringBuilder() {
3335             sb.setLength(0);
3336             return sb;
3337         }
3338 
3339         char[] getCompactCharArray() {
3340             return cmpCharArray;
3341         }
3342 
3343         /**
3344          * Places characters representing the intCompact in {@code long} into
3345          * cmpCharArray and returns the offset to the array where the
3346          * representation starts.
3347          *
3348          * @param intCompact the number to put into the cmpCharArray.
3349          * @return offset to the array where the representation starts.
3350          * Note: intCompact must be greater or equal to zero.
3351          */
3352         int putIntCompact(long intCompact) {
3353             assert intCompact >= 0;
3354 
3355             long q;
3356             int r;
3357             // since we start from the least significant digit, charPos points to
3358             // the last character in cmpCharArray.
3359             int charPos = cmpCharArray.length;
3360 
3361             // Get 2 digits/iteration using longs until quotient fits into an int
3362             while (intCompact > Integer.MAX_VALUE) {
3363                 q = intCompact / 100;
3364                 r = (int)(intCompact - q * 100);
3365                 intCompact = q;
3366                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3367                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3368             }
3369 
3370             // Get 2 digits/iteration using ints when i2 >= 100
3371             int q2;
3372             int i2 = (int)intCompact;
3373             while (i2 >= 100) {
3374                 q2 = i2 / 100;
3375                 r  = i2 - q2 * 100;
3376                 i2 = q2;
3377                 cmpCharArray[--charPos] = DIGIT_ONES[r];
3378                 cmpCharArray[--charPos] = DIGIT_TENS[r];
3379             }
3380 
3381             cmpCharArray[--charPos] = DIGIT_ONES[i2];
3382             if (i2 >= 10)
3383                 cmpCharArray[--charPos] = DIGIT_TENS[i2];
3384 
3385             return charPos;
3386         }
3387 
3388         final static char[] DIGIT_TENS = {
3389             '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
3390             '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
3391             '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
3392             '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
3393             '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
3394             '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
3395             '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
3396             '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
3397             '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
3398             '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
3399         };
3400 
3401         final static char[] DIGIT_ONES = {
3402             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3403             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3404             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3405             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3406             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3407             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3408             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3409             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3410             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3411             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3412         };
3413     }
3414 
3415     /**
3416      * Lay out this {@code BigDecimal} into a {@code char[]} array.
3417      * The Java 1.2 equivalent to this was called {@code getValueString}.
3418      *
3419      * @param  sci {@code true} for Scientific exponential notation;
3420      *          {@code false} for Engineering
3421      * @return string with canonical string representation of this
3422      *         {@code BigDecimal}
3423      */
3424     private String layoutChars(boolean sci) {
3425         if (scale == 0)                      // zero scale is trivial
3426             return (intCompact != INFLATED) ?
3427                 Long.toString(intCompact):
3428                 intVal.toString();
3429         if (scale == 2  &&
3430             intCompact >= 0 && intCompact < Integer.MAX_VALUE) {
3431             // currency fast path
3432             int lowInt = (int)intCompact % 100;
3433             int highInt = (int)intCompact / 100;
3434             return (Integer.toString(highInt) + '.' +
3435                     StringBuilderHelper.DIGIT_TENS[lowInt] +
3436                     StringBuilderHelper.DIGIT_ONES[lowInt]) ;
3437         }
3438 
3439         StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
3440         char[] coeff;
3441         int offset;  // offset is the starting index for coeff array
3442         // Get the significand as an absolute value
3443         if (intCompact != INFLATED) {
3444             offset = sbHelper.putIntCompact(Math.abs(intCompact));
3445             coeff  = sbHelper.getCompactCharArray();
3446         } else {
3447             offset = 0;
3448             coeff  = intVal.abs().toString().toCharArray();
3449         }
3450 
3451         // Construct a buffer, with sufficient capacity for all cases.
3452         // If E-notation is needed, length will be: +1 if negative, +1
3453         // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3454         // Otherwise it could have +1 if negative, plus leading "0.00000"
3455         StringBuilder buf = sbHelper.getStringBuilder();
3456         if (signum() < 0)             // prefix '-' if negative
3457             buf.append('-');
3458         int coeffLen = coeff.length - offset;
3459         long adjusted = -(long)scale + (coeffLen -1);
3460         if ((scale >= 0) && (adjusted >= -6)) { // plain number
3461             int pad = scale - coeffLen;         // count of padding zeros
3462             if (pad >= 0) {                     // 0.xxx form
3463                 buf.append('0');
3464                 buf.append('.');
3465                 for (; pad>0; pad--) {
3466                     buf.append('0');
3467                 }
3468                 buf.append(coeff, offset, coeffLen);
3469             } else {                         // xx.xx form
3470                 buf.append(coeff, offset, -pad);
3471                 buf.append('.');
3472                 buf.append(coeff, -pad + offset, scale);
3473             }
3474         } else { // E-notation is needed
3475             if (sci) {                       // Scientific notation
3476                 buf.append(coeff[offset]);   // first character
3477                 if (coeffLen > 1) {          // more to come
3478                     buf.append('.');
3479                     buf.append(coeff, offset + 1, coeffLen - 1);
3480                 }
3481             } else {                         // Engineering notation
3482                 int sig = (int)(adjusted % 3);
3483                 if (sig < 0)
3484                     sig += 3;                // [adjusted was negative]
3485                 adjusted -= sig;             // now a multiple of 3
3486                 sig++;
3487                 if (signum() == 0) {
3488                     switch (sig) {
3489                     case 1:
3490                         buf.append('0'); // exponent is a multiple of three
3491                         break;
3492                     case 2:
3493                         buf.append("0.00");
3494                         adjusted += 3;
3495                         break;
3496                     case 3:
3497                         buf.append("0.0");
3498                         adjusted += 3;
3499                         break;
3500                     default:
3501                         throw new AssertionError("Unexpected sig value " + sig);
3502                     }
3503                 } else if (sig >= coeffLen) {   // significand all in integer
3504                     buf.append(coeff, offset, coeffLen);
3505                     // may need some zeros, too
3506                     for (int i = sig - coeffLen; i > 0; i--)
3507                         buf.append('0');
3508                 } else {                     // xx.xxE form
3509                     buf.append(coeff, offset, sig);
3510                     buf.append('.');
3511                     buf.append(coeff, offset + sig, coeffLen - sig);
3512                 }
3513             }
3514             if (adjusted != 0) {             // [!sci could have made 0]
3515                 buf.append('E');
3516                 if (adjusted > 0)            // force sign for positive
3517                     buf.append('+');
3518                 buf.append(adjusted);
3519             }
3520         }
3521         return buf.toString();
3522     }
3523 
3524     /**
3525      * Return 10 to the power n, as a {@code BigInteger}.
3526      *
3527      * @param  n the power of ten to be returned (>=0)
3528      * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3529      */
3530     private static BigInteger bigTenToThe(int n) {
3531         if (n < 0)
3532             return BigInteger.ZERO;
3533 
3534         if (n < BIG_TEN_POWERS_TABLE_MAX) {
3535             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3536             if (n < pows.length)
3537                 return pows[n];
3538             else
3539                 return expandBigIntegerTenPowers(n);
3540         }
3541         // BigInteger.pow is slow, so make 10**n by constructing a
3542         // BigInteger from a character string (still not very fast)
3543         char tenpow[] = new char[n + 1];
3544         tenpow[0] = '1';
3545         for (int i = 1; i <= n; i++)
3546             tenpow[i] = '0';
3547         return new BigInteger(tenpow,1, tenpow.length);
3548     }
3549 
3550     /**
3551      * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3552      *
3553      * @param n the power of ten to be returned (>=0)
3554      * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3555      *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
3556      *         expanded to the size greater than n.
3557      */
3558     private static BigInteger expandBigIntegerTenPowers(int n) {
3559         synchronized(BigDecimal.class) {
3560             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3561             int curLen = pows.length;
3562             // The following comparison and the above synchronized statement is
3563             // to prevent multiple threads from expanding the same array.
3564             if (curLen <= n) {
3565                 int newLen = curLen << 1;
3566                 while (newLen <= n)
3567                     newLen <<= 1;
3568                 pows = Arrays.copyOf(pows, newLen);
3569                 for (int i = curLen; i < newLen; i++)
3570                     pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3571                 // Based on the following facts:
3572                 // 1. pows is a private local varible;
3573                 // 2. the following store is a volatile store.
3574                 // the newly created array elements can be safely published.
3575                 BIG_TEN_POWERS_TABLE = pows;
3576             }
3577             return pows[n];
3578         }
3579     }
3580 
3581     private static final long[] LONG_TEN_POWERS_TABLE = {
3582         1,                     // 0 / 10^0
3583         10,                    // 1 / 10^1
3584         100,                   // 2 / 10^2
3585         1000,                  // 3 / 10^3
3586         10000,                 // 4 / 10^4
3587         100000,                // 5 / 10^5
3588         1000000,               // 6 / 10^6
3589         10000000,              // 7 / 10^7
3590         100000000,             // 8 / 10^8
3591         1000000000,            // 9 / 10^9
3592         10000000000L,          // 10 / 10^10
3593         100000000000L,         // 11 / 10^11
3594         1000000000000L,        // 12 / 10^12
3595         10000000000000L,       // 13 / 10^13
3596         100000000000000L,      // 14 / 10^14
3597         1000000000000000L,     // 15 / 10^15
3598         10000000000000000L,    // 16 / 10^16
3599         100000000000000000L,   // 17 / 10^17
3600         1000000000000000000L   // 18 / 10^18
3601     };
3602 
3603     private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {
3604         BigInteger.ONE,
3605         BigInteger.valueOf(10),
3606         BigInteger.valueOf(100),
3607         BigInteger.valueOf(1000),
3608         BigInteger.valueOf(10000),
3609         BigInteger.valueOf(100000),
3610         BigInteger.valueOf(1000000),
3611         BigInteger.valueOf(10000000),
3612         BigInteger.valueOf(100000000),
3613         BigInteger.valueOf(1000000000),
3614         BigInteger.valueOf(10000000000L),
3615         BigInteger.valueOf(100000000000L),
3616         BigInteger.valueOf(1000000000000L),
3617         BigInteger.valueOf(10000000000000L),
3618         BigInteger.valueOf(100000000000000L),
3619         BigInteger.valueOf(1000000000000000L),
3620         BigInteger.valueOf(10000000000000000L),
3621         BigInteger.valueOf(100000000000000000L),
3622         BigInteger.valueOf(1000000000000000000L)
3623     };
3624 
3625     private static final int BIG_TEN_POWERS_TABLE_INITLEN =
3626         BIG_TEN_POWERS_TABLE.length;
3627     private static final int BIG_TEN_POWERS_TABLE_MAX =
3628         16 * BIG_TEN_POWERS_TABLE_INITLEN;
3629 
3630     private static final long THRESHOLDS_TABLE[] = {
3631         Long.MAX_VALUE,                     // 0
3632         Long.MAX_VALUE/10L,                 // 1
3633         Long.MAX_VALUE/100L,                // 2
3634         Long.MAX_VALUE/1000L,               // 3
3635         Long.MAX_VALUE/10000L,              // 4
3636         Long.MAX_VALUE/100000L,             // 5
3637         Long.MAX_VALUE/1000000L,            // 6
3638         Long.MAX_VALUE/10000000L,           // 7
3639         Long.MAX_VALUE/100000000L,          // 8
3640         Long.MAX_VALUE/1000000000L,         // 9
3641         Long.MAX_VALUE/10000000000L,        // 10
3642         Long.MAX_VALUE/100000000000L,       // 11
3643         Long.MAX_VALUE/1000000000000L,      // 12
3644         Long.MAX_VALUE/10000000000000L,     // 13
3645         Long.MAX_VALUE/100000000000000L,    // 14
3646         Long.MAX_VALUE/1000000000000000L,   // 15
3647         Long.MAX_VALUE/10000000000000000L,  // 16
3648         Long.MAX_VALUE/100000000000000000L, // 17
3649         Long.MAX_VALUE/1000000000000000000L // 18
3650     };
3651 
3652     /**
3653      * Compute val * 10 ^ n; return this product if it is
3654      * representable as a long, INFLATED otherwise.
3655      */
3656     private static long longMultiplyPowerTen(long val, int n) {
3657         if (val == 0 || n <= 0)
3658             return val;
3659         long[] tab = LONG_TEN_POWERS_TABLE;
3660         long[] bounds = THRESHOLDS_TABLE;
3661         if (n < tab.length && n < bounds.length) {
3662             long tenpower = tab[n];
3663             if (val == 1)
3664                 return tenpower;
3665             if (Math.abs(val) <= bounds[n])
3666                 return val * tenpower;
3667         }
3668         return INFLATED;
3669     }
3670 
3671     /**
3672      * Compute this * 10 ^ n.
3673      * Needed mainly to allow special casing to trap zero value
3674      */
3675     private BigInteger bigMultiplyPowerTen(int n) {
3676         if (n <= 0)
3677             return this.inflated();
3678 
3679         if (intCompact != INFLATED)
3680             return bigTenToThe(n).multiply(intCompact);
3681         else
3682             return intVal.multiply(bigTenToThe(n));
3683     }
3684 
3685     /**
3686      * Returns appropriate BigInteger from intVal field if intVal is
3687      * null, i.e. the compact representation is in use.
3688      */
3689     private BigInteger inflated() {
3690         if (intVal == null) {
3691             return BigInteger.valueOf(intCompact);
3692         }
3693         return intVal;
3694     }
3695 
3696     /**
3697      * Match the scales of two {@code BigDecimal}s to align their
3698      * least significant digits.
3699      *
3700      * <p>If the scales of val[0] and val[1] differ, rescale
3701      * (non-destructively) the lower-scaled {@code BigDecimal} so
3702      * they match.  That is, the lower-scaled reference will be
3703      * replaced by a reference to a new object with the same scale as
3704      * the other {@code BigDecimal}.
3705      *
3706      * @param  val array of two elements referring to the two
3707      *         {@code BigDecimal}s to be aligned.
3708      */
3709     private static void matchScale(BigDecimal[] val) {
3710         if (val[0].scale == val[1].scale) {
3711             return;
3712         } else if (val[0].scale < val[1].scale) {
3713             val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3714         } else if (val[1].scale < val[0].scale) {
3715             val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3716         }
3717     }
3718 
3719     private static class UnsafeHolder {
3720         private static final sun.misc.Unsafe unsafe;
3721         private static final long intCompactOffset;
3722         private static final long intValOffset;
3723         static {
3724             try {
3725                 unsafe = sun.misc.Unsafe.getUnsafe();
3726                 intCompactOffset = unsafe.objectFieldOffset
3727                     (BigDecimal.class.getDeclaredField("intCompact"));
3728                 intValOffset = unsafe.objectFieldOffset
3729                     (BigDecimal.class.getDeclaredField("intVal"));
3730             } catch (Exception ex) {
3731                 throw new ExceptionInInitializerError(ex);
3732             }
3733         }
3734         private static void setIntCompactVolatile(BigDecimal bd, long val) {
3735             unsafe.putLongVolatile(bd, intCompactOffset, val);
3736         }
3737         
3738         private static void setIntValVolatile(BigDecimal bd, BigInteger val) {
3739             unsafe.putObjectVolatile(bd, intValOffset, val);
3740         }
3741     }
3742 
3743     /**
3744      * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3745      * deserialize it).
3746      *
3747      * @param s the stream being read.
3748      */
3749     private void readObject(java.io.ObjectInputStream s)
3750         throws java.io.IOException, ClassNotFoundException {
3751         // Read in all fields
3752         s.defaultReadObject();
3753         // validate possibly bad fields
3754         if (intVal == null) {
3755             String message = "BigDecimal: null intVal in stream";
3756             throw new java.io.StreamCorruptedException(message);
3757         // [all values of scale are now allowed]
3758         }
3759         UnsafeHolder.setIntCompactVolatile(this, compactValFor(intVal));
3760     }
3761 
3762    /**
3763     * Serialize this {@code BigDecimal} to the stream in question
3764     *
3765     * @param s the stream to serialize to.
3766     */
3767    private void writeObject(java.io.ObjectOutputStream s)
3768        throws java.io.IOException {
3769        // Must inflate to maintain compatible serial form.
3770        if (this.intVal == null)
3771            UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact));
3772        // Could reset intVal back to null if it has to be set.
3773        s.defaultWriteObject();
3774    }
3775 
3776     /**
3777      * Returns the length of the absolute value of a {@code long}, in decimal
3778      * digits.
3779      *
3780      * @param x the {@code long}
3781      * @return the length of the unscaled value, in deciaml digits.
3782      */
3783     static int longDigitLength(long x) {
3784         /*
3785          * As described in "Bit Twiddling Hacks" by Sean Anderson,
3786          * (http://graphics.stanford.edu/~seander/bithacks.html)
3787          * integer log 10 of x is within 1 of (1233/4096)* (1 +
3788          * integer log 2 of x). The fraction 1233/4096 approximates
3789          * log10(2). So we first do a version of log2 (a variant of
3790          * Long class with pre-checks and opposite directionality) and
3791          * then scale and check against powers table. This is a little
3792          * simpler in present context than the version in Hacker's
3793          * Delight sec 11-4. Adding one to bit length allows comparing
3794          * downward from the LONG_TEN_POWERS_TABLE that we need
3795          * anyway.
3796          */
3797         assert x != BigDecimal.INFLATED;
3798         if (x < 0)
3799             x = -x;
3800         if (x < 10) // must screen for 0, might as well 10
3801             return 1;
3802         int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;
3803         long[] tab = LONG_TEN_POWERS_TABLE;
3804         // if r >= length, must have max possible digits for long
3805         return (r >= tab.length || x < tab[r]) ? r : r + 1;
3806     }
3807 
3808     /**
3809      * Returns the length of the absolute value of a BigInteger, in
3810      * decimal digits.
3811      *
3812      * @param b the BigInteger
3813      * @return the length of the unscaled value, in decimal digits
3814      */
3815     private static int bigDigitLength(BigInteger b) {
3816         /*
3817          * Same idea as the long version, but we need a better
3818          * approximation of log10(2). Using 646456993/2^31
3819          * is accurate up to max possible reported bitLength.
3820          */
3821         if (b.signum == 0)
3822             return 1;
3823         int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3824         return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3825     }
3826 
3827     /**
3828      * Check a scale for Underflow or Overflow.  If this BigDecimal is
3829      * nonzero, throw an exception if the scale is outof range. If this
3830      * is zero, saturate the scale to the extreme value of the right
3831      * sign if the scale is out of range.
3832      *
3833      * @param val The new scale.
3834      * @throws ArithmeticException (overflow or underflow) if the new
3835      *         scale is out of range.
3836      * @return validated scale as an int.
3837      */
3838     private int checkScale(long val) {
3839         int asInt = (int)val;
3840         if (asInt != val) {
3841             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3842             BigInteger b;
3843             if (intCompact != 0 &&
3844                 ((b = intVal) == null || b.signum() != 0))
3845                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3846         }
3847         return asInt;
3848     }
3849 
3850    /**
3851      * Returns the compact value for given {@code BigInteger}, or
3852      * INFLATED if too big. Relies on internal representation of
3853      * {@code BigInteger}.
3854      */
3855     private static long compactValFor(BigInteger b) {
3856         int[] m = b.mag;
3857         int len = m.length;
3858         if (len == 0)
3859             return 0;
3860         int d = m[0];
3861         if (len > 2 || (len == 2 && d < 0))
3862             return INFLATED;
3863 
3864         long u = (len == 2)?
3865             (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3866             (((long)d)   & LONG_MASK);
3867         return (b.signum < 0)? -u : u;
3868     }
3869 
3870     private static int longCompareMagnitude(long x, long y) {
3871         if (x < 0)
3872             x = -x;
3873         if (y < 0)
3874             y = -y;
3875         return (x < y) ? -1 : ((x == y) ? 0 : 1);
3876     }
3877 
3878     private static int saturateLong(long s) {
3879         int i = (int)s;
3880         return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
3881     }
3882 
3883     /*
3884      * Internal printing routine
3885      */
3886     private static void print(String name, BigDecimal bd) {
3887         System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
3888                           name,
3889                           bd.intCompact,
3890                           bd.intVal,
3891                           bd.scale,
3892                           bd.precision);
3893     }
3894 
3895     /**
3896      * Check internal invariants of this BigDecimal.  These invariants
3897      * include:
3898      *
3899      * <ul>
3900      *
3901      * <li>The object must be initialized; either intCompact must not be
3902      * INFLATED or intVal is non-null.  Both of these conditions may
3903      * be true.
3904      *
3905      * <li>If both intCompact and intVal and set, their values must be
3906      * consistent.
3907      *
3908      * <li>If precision is nonzero, it must have the right value.
3909      * </ul>
3910      *
3911      * Note: Since this is an audit method, we are not supposed to change the
3912      * state of this BigDecimal object.
3913      */
3914     private BigDecimal audit() {
3915         if (intCompact == INFLATED) {
3916             if (intVal == null) {
3917                 print("audit", this);
3918                 throw new AssertionError("null intVal");
3919             }
3920             // Check precision
3921             if (precision > 0 && precision != bigDigitLength(intVal)) {
3922                 print("audit", this);
3923                 throw new AssertionError("precision mismatch");
3924             }
3925         } else {
3926             if (intVal != null) {
3927                 long val = intVal.longValue();
3928                 if (val != intCompact) {
3929                     print("audit", this);
3930                     throw new AssertionError("Inconsistent state, intCompact=" +
3931                                              intCompact + "\t intVal=" + val);
3932                 }
3933             }
3934             // Check precision
3935             if (precision > 0 && precision != longDigitLength(intCompact)) {
3936                 print("audit", this);
3937                 throw new AssertionError("precision mismatch");
3938             }
3939         }
3940         return this;
3941     }
3942 
3943     /* the same as checkScale where value!=0 */
3944     private static int checkScaleNonZero(long val) {
3945         int asInt = (int)val;
3946         if (asInt != val) {
3947             throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3948         }
3949         return asInt;
3950     }
3951 
3952     private static int checkScale(long intCompact, long val) {
3953         int asInt = (int)val;
3954         if (asInt != val) {
3955             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3956             if (intCompact != 0)
3957                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3958         }
3959         return asInt;
3960     }
3961 
3962     private static int checkScale(BigInteger intVal, long val) {
3963         int asInt = (int)val;
3964         if (asInt != val) {
3965             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3966             if (intVal.signum() != 0)
3967                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3968         }
3969         return asInt;
3970     }
3971 
3972     /**
3973      * Returns a {@code BigDecimal} rounded according to the MathContext
3974      * settings;
3975      * If rounding is needed a new {@code BigDecimal} is created and returned.
3976      *
3977      * @param val the value to be rounded
3978      * @param mc the context to use.
3979      * @return a {@code BigDecimal} rounded according to the MathContext
3980      *         settings.  May return {@code value}, if no rounding needed.
3981      * @throws ArithmeticException if the rounding mode is
3982      *         {@code RoundingMode.UNNECESSARY} and the
3983      *         result is inexact.
3984      */
3985     private static BigDecimal doRound(BigDecimal val, MathContext mc) {
3986         int mcp = mc.precision;
3987         boolean wasDivided = false;
3988         if (mcp > 0) {
3989             BigInteger intVal = val.intVal;
3990             long compactVal = val.intCompact;
3991             int scale = val.scale;
3992             int prec = val.precision();
3993             int mode = mc.roundingMode.oldMode;
3994             int drop;
3995             if (compactVal == INFLATED) {
3996                 drop = prec - mcp;
3997                 while (drop > 0) {
3998                     scale = checkScaleNonZero((long) scale - drop);
3999                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
4000                     wasDivided = true;
4001                     compactVal = compactValFor(intVal);
4002                     if (compactVal != INFLATED) {
4003                         prec = longDigitLength(compactVal);
4004                         break;
4005                     }
4006                     prec = bigDigitLength(intVal);
4007                     drop = prec - mcp;
4008                 }
4009             }
4010             if (compactVal != INFLATED) {
4011                 drop = prec - mcp;  // drop can't be more than 18
4012                 while (drop > 0) {
4013                     scale = checkScaleNonZero((long) scale - drop);
4014                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4015                     wasDivided = true;
4016                     prec = longDigitLength(compactVal);
4017                     drop = prec - mcp;
4018                     intVal = null;
4019                 }
4020             }
4021             return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;
4022         }
4023         return val;
4024     }
4025 
4026     /*
4027      * Returns a {@code BigDecimal} created from {@code long} value with
4028      * given scale rounded according to the MathContext settings
4029      */
4030     private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {
4031         int mcp = mc.precision;
4032         if (mcp > 0 && mcp < 19) {
4033             int prec = longDigitLength(compactVal);
4034             int drop = prec - mcp;  // drop can't be more than 18
4035             while (drop > 0) {
4036                 scale = checkScaleNonZero((long) scale - drop);
4037                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4038                 prec = longDigitLength(compactVal);
4039                 drop = prec - mcp;
4040             }
4041             return valueOf(compactVal, scale, prec);
4042         }
4043         return valueOf(compactVal, scale);
4044     }
4045 
4046     /*
4047      * Returns a {@code BigDecimal} created from {@code BigInteger} value with
4048      * given scale rounded according to the MathContext settings
4049      */
4050     private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {
4051         int mcp = mc.precision;
4052         int prec = 0;
4053         if (mcp > 0) {
4054             long compactVal = compactValFor(intVal);
4055             int mode = mc.roundingMode.oldMode;
4056             int drop;
4057             if (compactVal == INFLATED) {
4058                 prec = bigDigitLength(intVal);
4059                 drop = prec - mcp;
4060                 while (drop > 0) {
4061                     scale = checkScaleNonZero((long) scale - drop);
4062                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
4063                     compactVal = compactValFor(intVal);
4064                     if (compactVal != INFLATED) {
4065                         break;
4066                     }
4067                     prec = bigDigitLength(intVal);
4068                     drop = prec - mcp;
4069                 }
4070             }
4071             if (compactVal != INFLATED) {
4072                 prec = longDigitLength(compactVal);
4073                 drop = prec - mcp;     // drop can't be more than 18
4074                 while (drop > 0) {
4075                     scale = checkScaleNonZero((long) scale - drop);
4076                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4077                     prec = longDigitLength(compactVal);
4078                     drop = prec - mcp;
4079                 }
4080                 return valueOf(compactVal,scale,prec);
4081             }
4082         }
4083         return new BigDecimal(intVal,INFLATED,scale,prec);
4084     }
4085 
4086     /*
4087      * Divides {@code BigInteger} value by ten power.
4088      */
4089     private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {
4090         if (tenPow < LONG_TEN_POWERS_TABLE.length)
4091             intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);
4092         else
4093             intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);
4094         return intVal;
4095     }
4096 
4097     /**
4098      * Internally used for division operation for division {@code long} by
4099      * {@code long}.
4100      * The returned {@code BigDecimal} object is the quotient whose scale is set
4101      * to the passed in scale. If the remainder is not zero, it will be rounded
4102      * based on the passed in roundingMode. Also, if the remainder is zero and
4103      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4104      * trailing zeros of the result is stripped to match the preferredScale.
4105      */
4106     private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
4107                                              int preferredScale) {
4108 
4109         int qsign; // quotient sign
4110         long q = ldividend / ldivisor; // store quotient in long
4111         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4112             return valueOf(q, scale);
4113         long r = ldividend % ldivisor; // store remainder in long
4114         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4115         if (r != 0) {
4116             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
4117             return valueOf((increment ? q + qsign : q), scale);
4118         } else {
4119             if (preferredScale != scale)
4120                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4121             else
4122                 return valueOf(q, scale);
4123         }
4124     }
4125 
4126     /**
4127      * Divides {@code long} by {@code long} and do rounding based on the
4128      * passed in roundingMode.
4129      */
4130     private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {
4131         int qsign; // quotient sign
4132         long q = ldividend / ldivisor; // store quotient in long
4133         if (roundingMode == ROUND_DOWN)
4134             return q;
4135         long r = ldividend % ldivisor; // store remainder in long
4136         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4137         if (r != 0) {
4138             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q,     r);
4139             return increment ? q + qsign : q;
4140         } else {
4141             return q;
4142         }
4143     }
4144 
4145     /**
4146      * Shared logic of need increment computation.
4147      */
4148     private static boolean commonNeedIncrement(int roundingMode, int qsign,
4149                                         int cmpFracHalf, boolean oddQuot) {
4150         switch(roundingMode) {
4151         case ROUND_UNNECESSARY:
4152             throw new ArithmeticException("Rounding necessary");
4153 
4154         case ROUND_UP: // Away from zero
4155             return true;
4156 
4157         case ROUND_DOWN: // Towards zero
4158             return false;
4159 
4160         case ROUND_CEILING: // Towards +infinity
4161             return qsign > 0;
4162 
4163         case ROUND_FLOOR: // Towards -infinity
4164             return qsign < 0;
4165 
4166         default: // Some kind of half-way rounding
4167             if (roundingMode == ROUND_HALF_DOWN ||
4168                 cmpFracHalf < 0 ) // We're closer to higher digit
4169                 return false;
4170             else if (roundingMode == ROUND_HALF_UP ||
4171                      cmpFracHalf > 0 ) // We're closer to lower digit
4172                 return true;
4173             else
4174                 // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
4175                 return oddQuot;
4176         }
4177     }
4178 
4179     /**
4180      * Tests if quotient has to be incremented according the roundingMode
4181      */
4182     private static boolean needIncrement(long ldivisor, int roundingMode,
4183                                          int qsign, long q, long r) {
4184         assert r != 0L;
4185 
4186         int cmpFracHalf;
4187         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4188             cmpFracHalf = 1; // 2 * r can't fit into long
4189         } else {
4190             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4191         }
4192 
4193         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4194     }
4195 
4196     /**
4197      * Divides {@code BigInteger} value by {@code long} value and
4198      * do rounding based on the passed in roundingMode.
4199      */
4200     private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4201         boolean isRemainderZero; // record remainder is zero or not
4202         int qsign; // quotient sign
4203         long r = 0; // store quotient & remainder in long
4204         MutableBigInteger mq = null; // store quotient
4205         // Descend into mutables for faster remainder checks
4206         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4207         mq = new MutableBigInteger();
4208         r = mdividend.divide(ldivisor, mq);
4209         isRemainderZero = (r == 0);
4210         qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4211         if (!isRemainderZero) {
4212             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4213                 mq.add(MutableBigInteger.ONE);
4214             }
4215         }
4216         return mq.toBigInteger(qsign);
4217     }
4218 
4219     /**
4220      * Internally used for division operation for division {@code BigInteger}
4221      * by {@code long}.
4222      * The returned {@code BigDecimal} object is the quotient whose scale is set
4223      * to the passed in scale. If the remainder is not zero, it will be rounded
4224      * based on the passed in roundingMode. Also, if the remainder is zero and
4225      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4226      * trailing zeros of the result is stripped to match the preferredScale.
4227      */
4228     private static BigDecimal divideAndRound(BigInteger bdividend,
4229                                              long ldivisor, int scale, int roundingMode, int preferredScale) {
4230         boolean isRemainderZero; // record remainder is zero or not
4231         int qsign; // quotient sign
4232         long r = 0; // store quotient & remainder in long
4233         MutableBigInteger mq = null; // store quotient
4234         // Descend into mutables for faster remainder checks
4235         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4236         mq = new MutableBigInteger();
4237         r = mdividend.divide(ldivisor, mq);
4238         isRemainderZero = (r == 0);
4239         qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4240         if (!isRemainderZero) {
4241             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4242                 mq.add(MutableBigInteger.ONE);
4243             }
4244             return mq.toBigDecimal(qsign, scale);
4245         } else {
4246             if (preferredScale != scale) {
4247                 long compactVal = mq.toCompactValue(qsign);
4248                 if(compactVal!=INFLATED) {
4249                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4250                 }
4251                 BigInteger intVal =  mq.toBigInteger(qsign);
4252                 return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4253             } else {
4254                 return mq.toBigDecimal(qsign, scale);
4255             }
4256         }
4257     }
4258 
4259     /**
4260      * Tests if quotient has to be incremented according the roundingMode
4261      */
4262     private static boolean needIncrement(long ldivisor, int roundingMode,
4263                                          int qsign, MutableBigInteger mq, long r) {
4264         assert r != 0L;
4265 
4266         int cmpFracHalf;
4267         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4268             cmpFracHalf = 1; // 2 * r can't fit into long
4269         } else {
4270             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4271         }
4272 
4273         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4274     }
4275 
4276     /**
4277      * Divides {@code BigInteger} value by {@code BigInteger} value and
4278      * do rounding based on the passed in roundingMode.
4279      */
4280     private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {
4281         boolean isRemainderZero; // record remainder is zero or not
4282         int qsign; // quotient sign
4283         // Descend into mutables for faster remainder checks
4284         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4285         MutableBigInteger mq = new MutableBigInteger();
4286         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4287         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4288         isRemainderZero = mr.isZero();
4289         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4290         if (!isRemainderZero) {
4291             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4292                 mq.add(MutableBigInteger.ONE);
4293             }
4294         }
4295         return mq.toBigInteger(qsign);
4296     }
4297 
4298     /**
4299      * Internally used for division operation for division {@code BigInteger}
4300      * by {@code BigInteger}.
4301      * The returned {@code BigDecimal} object is the quotient whose scale is set
4302      * to the passed in scale. If the remainder is not zero, it will be rounded
4303      * based on the passed in roundingMode. Also, if the remainder is zero and
4304      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4305      * trailing zeros of the result is stripped to match the preferredScale.
4306      */
4307     private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,
4308                                              int preferredScale) {
4309         boolean isRemainderZero; // record remainder is zero or not
4310         int qsign; // quotient sign
4311         // Descend into mutables for faster remainder checks
4312         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4313         MutableBigInteger mq = new MutableBigInteger();
4314         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4315         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4316         isRemainderZero = mr.isZero();
4317         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4318         if (!isRemainderZero) {
4319             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4320                 mq.add(MutableBigInteger.ONE);
4321             }
4322             return mq.toBigDecimal(qsign, scale);
4323         } else {
4324             if (preferredScale != scale) {
4325                 long compactVal = mq.toCompactValue(qsign);
4326                 if (compactVal != INFLATED) {
4327                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4328                 }
4329                 BigInteger intVal = mq.toBigInteger(qsign);
4330                 return createAndStripZerosToMatchScale(intVal, scale, preferredScale);
4331             } else {
4332                 return mq.toBigDecimal(qsign, scale);
4333             }
4334         }
4335     }
4336 
4337     /**
4338      * Tests if quotient has to be incremented according the roundingMode
4339      */
4340     private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,
4341                                          int qsign, MutableBigInteger mq, MutableBigInteger mr) {
4342         assert !mr.isZero();
4343         int cmpFracHalf = mr.compareHalf(mdivisor);
4344         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4345     }
4346 
4347     /**
4348      * Remove insignificant trailing zeros from this
4349      * {@code BigInteger} value until the preferred scale is reached or no
4350      * more zeros can be removed.  If the preferred scale is less than
4351      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4352      *
4353      * @return new {@code BigDecimal} with a scale possibly reduced
4354      * to be closed to the preferred scale.
4355      */
4356     private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {
4357         BigInteger qr[]; // quotient-remainder pair
4358         while (intVal.compareMagnitude(BigInteger.TEN) >= 0
4359                && scale > preferredScale) {
4360             if (intVal.testBit(0))
4361                 break; // odd number cannot end in 0
4362             qr = intVal.divideAndRemainder(BigInteger.TEN);
4363             if (qr[1].signum() != 0)
4364                 break; // non-0 remainder
4365             intVal = qr[0];
4366             scale = checkScale(intVal,(long) scale - 1); // could Overflow
4367         }
4368         return valueOf(intVal, scale, 0);
4369     }
4370 
4371     /**
4372      * Remove insignificant trailing zeros from this
4373      * {@code long} value until the preferred scale is reached or no
4374      * more zeros can be removed.  If the preferred scale is less than
4375      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4376      *
4377      * @return new {@code BigDecimal} with a scale possibly reduced
4378      * to be closed to the preferred scale.
4379      */
4380     private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {
4381         while (Math.abs(compactVal) >= 10L && scale > preferredScale) {
4382             if ((compactVal & 1L) != 0L)
4383                 break; // odd number cannot end in 0
4384             long r = compactVal % 10L;
4385             if (r != 0L)
4386                 break; // non-0 remainder
4387             compactVal /= 10;
4388             scale = checkScale(compactVal, (long) scale - 1); // could Overflow
4389         }
4390         return valueOf(compactVal, scale);
4391     }
4392 
4393     private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {
4394         if(intCompact!=INFLATED) {
4395             return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);
4396         } else {
4397             return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,
4398                                                    scale, preferredScale);
4399         }
4400     }
4401 
4402     /*
4403      * returns INFLATED if oveflow
4404      */
4405     private static long add(long xs, long ys){
4406         long sum = xs + ys;
4407         // See "Hacker's Delight" section 2-12 for explanation of
4408         // the overflow test.
4409         if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed
4410             return sum;
4411         }
4412         return INFLATED;
4413     }
4414 
4415     private static BigDecimal add(long xs, long ys, int scale){
4416         long sum = add(xs, ys);
4417         if (sum!=INFLATED)
4418             return BigDecimal.valueOf(sum, scale);
4419         return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
4420     }
4421 
4422     private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
4423         long sdiff = (long) scale1 - scale2;
4424         if (sdiff == 0) {
4425             return add(xs, ys, scale1);
4426         } else if (sdiff < 0) {
4427             int raise = checkScale(xs,-sdiff);
4428             long scaledX = longMultiplyPowerTen(xs, raise);
4429             if (scaledX != INFLATED) {
4430                 return add(scaledX, ys, scale2);
4431             } else {
4432                 BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
4433                 return ((xs^ys)>=0) ? // same sign test
4434                     new BigDecimal(bigsum, INFLATED, scale2, 0)
4435                     : valueOf(bigsum, scale2, 0);
4436             }
4437         } else {
4438             int raise = checkScale(ys,sdiff);
4439             long scaledY = longMultiplyPowerTen(ys, raise);
4440             if (scaledY != INFLATED) {
4441                 return add(xs, scaledY, scale1);
4442             } else {
4443                 BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
4444                 return ((xs^ys)>=0) ?
4445                     new BigDecimal(bigsum, INFLATED, scale1, 0)
4446                     : valueOf(bigsum, scale1, 0);
4447             }
4448         }
4449     }
4450 
4451     private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {
4452         int rscale = scale1;
4453         long sdiff = (long)rscale - scale2;
4454         boolean sameSigns =  (Long.signum(xs) == snd.signum);
4455         BigInteger sum;
4456         if (sdiff < 0) {
4457             int raise = checkScale(xs,-sdiff);
4458             rscale = scale2;
4459             long scaledX = longMultiplyPowerTen(xs, raise);
4460             if (scaledX == INFLATED) {
4461                 sum = snd.add(bigMultiplyPowerTen(xs,raise));
4462             } else {
4463                 sum = snd.add(scaledX);
4464             }
4465         } else { //if (sdiff > 0) {
4466             int raise = checkScale(snd,sdiff);
4467             snd = bigMultiplyPowerTen(snd,raise);
4468             sum = snd.add(xs);
4469         }
4470         return (sameSigns) ?
4471             new BigDecimal(sum, INFLATED, rscale, 0) :
4472             valueOf(sum, rscale, 0);
4473     }
4474 
4475     private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {
4476         int rscale = scale1;
4477         long sdiff = (long)rscale - scale2;
4478         if (sdiff != 0) {
4479             if (sdiff < 0) {
4480                 int raise = checkScale(fst,-sdiff);
4481                 rscale = scale2;
4482                 fst = bigMultiplyPowerTen(fst,raise);
4483             } else {
4484                 int raise = checkScale(snd,sdiff);
4485                 snd = bigMultiplyPowerTen(snd,raise);
4486             }
4487         }
4488         BigInteger sum = fst.add(snd);
4489         return (fst.signum == snd.signum) ?
4490                 new BigDecimal(sum, INFLATED, rscale, 0) :
4491                 valueOf(sum, rscale, 0);
4492     }
4493 
4494     private static BigInteger bigMultiplyPowerTen(long value, int n) {
4495         if (n <= 0)
4496             return BigInteger.valueOf(value);
4497         return bigTenToThe(n).multiply(value);
4498     }
4499 
4500     private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {
4501         if (n <= 0)
4502             return value;
4503         if(n<LONG_TEN_POWERS_TABLE.length) {
4504                 return value.multiply(LONG_TEN_POWERS_TABLE[n]);
4505         }
4506         return value.multiply(bigTenToThe(n));
4507     }
4508 
4509     /**
4510      * Returns a {@code BigDecimal} whose value is {@code (xs /
4511      * ys)}, with rounding according to the context settings.
4512      *
4513      * Fast path - used only when (xscale <= yscale && yscale < 18
4514      *  && mc.presision<18) {
4515      */
4516     private static BigDecimal divideSmallFastPath(final long xs, int xscale,
4517                                                   final long ys, int yscale,
4518                                                   long preferredScale, MathContext mc) {
4519         int mcp = mc.precision;
4520         int roundingMode = mc.roundingMode.oldMode;
4521 
4522         assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);
4523         int xraise = yscale - xscale; // xraise >=0
4524         long scaledX = (xraise==0) ? xs :
4525             longMultiplyPowerTen(xs, xraise); // can't overflow here!
4526         BigDecimal quotient;
4527 
4528         int cmp = longCompareMagnitude(scaledX, ys);
4529         if(cmp > 0) { // satisfy constraint (b)
4530             yscale -= 1; // [that is, divisor *= 10]
4531             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4532             if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4533                 // assert newScale >= xscale
4534                 int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4535                 long scaledXs;
4536                 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4537                     quotient = null;
4538                     if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {
4539                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4540                     }
4541                     if(quotient==null) {
4542                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);
4543                         quotient = divideAndRound(rb, ys,
4544                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4545                     }
4546                 } else {
4547                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4548                 }
4549             } else {
4550                 int newScale = checkScaleNonZero((long) xscale - mcp);
4551                 // assert newScale >= yscale
4552                 if (newScale == yscale) { // easy case
4553                     quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4554                 } else {
4555                     int raise = checkScaleNonZero((long) newScale - yscale);
4556                     long scaledYs;
4557                     if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4558                         BigInteger rb = bigMultiplyPowerTen(ys,raise);
4559                         quotient = divideAndRound(BigInteger.valueOf(xs),
4560                                                   rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4561                     } else {
4562                         quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4563                     }
4564                 }
4565             }
4566         } else {
4567             // abs(scaledX) <= abs(ys)
4568             // result is "scaledX * 10^msp / ys"
4569             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4570             if(cmp==0) {
4571                 // abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign
4572                 quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));
4573             } else {
4574                 // abs(scaledX) < abs(ys)
4575                 long scaledXs;
4576                 if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {
4577                     quotient = null;
4578                     if(mcp<LONG_TEN_POWERS_TABLE.length) {
4579                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4580                     }
4581                     if(quotient==null) {
4582                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);
4583                         quotient = divideAndRound(rb, ys,
4584                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4585                     }
4586                 } else {
4587                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4588                 }
4589             }
4590         }
4591         // doRound, here, only affects 1000000000 case.
4592         return doRound(quotient,mc);
4593     }
4594 
4595     /**
4596      * Returns a {@code BigDecimal} whose value is {@code (xs /
4597      * ys)}, with rounding according to the context settings.
4598      */
4599     private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
4600         int mcp = mc.precision;
4601         if(xscale <= yscale && yscale < 18 && mcp<18) {
4602             return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);
4603         }
4604         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4605             yscale -= 1; // [that is, divisor *= 10]
4606         }
4607         int roundingMode = mc.roundingMode.oldMode;
4608         // In order to find out whether the divide generates the exact result,
4609         // we avoid calling the above divide method. 'quotient' holds the
4610         // return BigDecimal object whose scale will be set to 'scl'.
4611         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4612         BigDecimal quotient;
4613         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4614             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4615             long scaledXs;
4616             if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4617                 BigInteger rb = bigMultiplyPowerTen(xs,raise);
4618                 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4619             } else {
4620                 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4621             }
4622         } else {
4623             int newScale = checkScaleNonZero((long) xscale - mcp);
4624             // assert newScale >= yscale
4625             if (newScale == yscale) { // easy case
4626                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4627             } else {
4628                 int raise = checkScaleNonZero((long) newScale - yscale);
4629                 long scaledYs;
4630                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4631                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4632                     quotient = divideAndRound(BigInteger.valueOf(xs),
4633                                               rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4634                 } else {
4635                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4636                 }
4637             }
4638         }
4639         // doRound, here, only affects 1000000000 case.
4640         return doRound(quotient,mc);
4641     }
4642 
4643     /**
4644      * Returns a {@code BigDecimal} whose value is {@code (xs /
4645      * ys)}, with rounding according to the context settings.
4646      */
4647     private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {
4648         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4649         if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)
4650             yscale -= 1; // [that is, divisor *= 10]
4651         }
4652         int mcp = mc.precision;
4653         int roundingMode = mc.roundingMode.oldMode;
4654 
4655         // In order to find out whether the divide generates the exact result,
4656         // we avoid calling the above divide method. 'quotient' holds the
4657         // return BigDecimal object whose scale will be set to 'scl'.
4658         BigDecimal quotient;
4659         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4660         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4661             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4662             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4663             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4664         } else {
4665             int newScale = checkScaleNonZero((long) xscale - mcp);
4666             // assert newScale >= yscale
4667             if (newScale == yscale) { // easy case
4668                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4669             } else {
4670                 int raise = checkScaleNonZero((long) newScale - yscale);
4671                 long scaledYs;
4672                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4673                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4674                     quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4675                 } else {
4676                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4677                 }
4678             }
4679         }
4680         // doRound, here, only affects 1000000000 case.
4681         return doRound(quotient, mc);
4682     }
4683 
4684     /**
4685      * Returns a {@code BigDecimal} whose value is {@code (xs /
4686      * ys)}, with rounding according to the context settings.
4687      */
4688     private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4689         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4690         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4691             yscale -= 1; // [that is, divisor *= 10]
4692         }
4693         int mcp = mc.precision;
4694         int roundingMode = mc.roundingMode.oldMode;
4695 
4696         // In order to find out whether the divide generates the exact result,
4697         // we avoid calling the above divide method. 'quotient' holds the
4698         // return BigDecimal object whose scale will be set to 'scl'.
4699         BigDecimal quotient;
4700         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4701         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4702             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4703             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4704             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4705         } else {
4706             int newScale = checkScaleNonZero((long) xscale - mcp);
4707             int raise = checkScaleNonZero((long) newScale - yscale);
4708             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4709             quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4710         }
4711         // doRound, here, only affects 1000000000 case.
4712         return doRound(quotient, mc);
4713     }
4714 
4715     /**
4716      * Returns a {@code BigDecimal} whose value is {@code (xs /
4717      * ys)}, with rounding according to the context settings.
4718      */
4719     private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4720         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4721         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4722             yscale -= 1; // [that is, divisor *= 10]
4723         }
4724         int mcp = mc.precision;
4725         int roundingMode = mc.roundingMode.oldMode;
4726 
4727         // In order to find out whether the divide generates the exact result,
4728         // we avoid calling the above divide method. 'quotient' holds the
4729         // return BigDecimal object whose scale will be set to 'scl'.
4730         BigDecimal quotient;
4731         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4732         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4733             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4734             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4735             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4736         } else {
4737             int newScale = checkScaleNonZero((long) xscale - mcp);
4738             int raise = checkScaleNonZero((long) newScale - yscale);
4739             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4740             quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4741         }
4742         // doRound, here, only affects 1000000000 case.
4743         return doRound(quotient, mc);
4744     }
4745 
4746     /*
4747      * performs divideAndRound for (dividend0*dividend1, divisor)
4748      * returns null if quotient can't fit into long value;
4749      */
4750     private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,
4751                                                      int preferredScale) {
4752         int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);
4753         dividend0 = Math.abs(dividend0);
4754         dividend1 = Math.abs(dividend1);
4755         divisor = Math.abs(divisor);
4756         // multiply dividend0 * dividend1
4757         long d0_hi = dividend0 >>> 32;
4758         long d0_lo = dividend0 & LONG_MASK;
4759         long d1_hi = dividend1 >>> 32;
4760         long d1_lo = dividend1 & LONG_MASK;
4761         long product = d0_lo * d1_lo;
4762         long d0 = product & LONG_MASK;
4763         long d1 = product >>> 32;
4764         product = d0_hi * d1_lo + d1;
4765         d1 = product & LONG_MASK;
4766         long d2 = product >>> 32;
4767         product = d0_lo * d1_hi + d1;
4768         d1 = product & LONG_MASK;
4769         d2 += product >>> 32;
4770         long d3 = d2>>>32;
4771         d2 &= LONG_MASK;
4772         product = d0_hi*d1_hi + d2;
4773         d2 = product & LONG_MASK;
4774         d3 = ((product>>>32) + d3) & LONG_MASK;
4775         final long dividendHi = make64(d3,d2);
4776         final long dividendLo = make64(d1,d0);
4777         // divide
4778         return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);
4779     }
4780 
4781     private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).
4782 
4783     /*
4784      * divideAndRound 128-bit value by long divisor.
4785      * returns null if quotient can't fit into long value;
4786      * Specialized version of Knuth's division
4787      */
4788     private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,
4789                                                 int scale, int roundingMode, int preferredScale) {
4790         if (dividendHi >= divisor) {
4791             return null;
4792         }
4793         final int shift = Long.numberOfLeadingZeros(divisor);
4794         divisor <<= shift;
4795 
4796         final long v1 = divisor >>> 32;
4797         final long v0 = divisor & LONG_MASK;
4798 
4799         long q1, q0;
4800         long r_tmp;
4801 
4802         long tmp = dividendLo << shift;
4803         long u1 = tmp >>> 32;
4804         long u0 = tmp & LONG_MASK;
4805 
4806         tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);
4807         long u2 = tmp & LONG_MASK;
4808         tmp = divWord(tmp,v1);
4809         q1 = tmp & LONG_MASK;
4810         r_tmp = tmp >>> 32;
4811         while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {
4812             q1--;
4813             r_tmp += v1;
4814             if (r_tmp >= DIV_NUM_BASE)
4815                 break;
4816         }
4817         tmp = mulsub(u2,u1,v1,v0,q1);
4818         u1 = tmp & LONG_MASK;
4819         tmp = divWord(tmp,v1);
4820         q0 = tmp & LONG_MASK;
4821         r_tmp = tmp >>> 32;
4822         while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {
4823             q0--;
4824             r_tmp += v1;
4825             if (r_tmp >= DIV_NUM_BASE)
4826                 break;
4827         }
4828         if((int)q1 < 0) {
4829             // result (which is positive and unsigned here)
4830             // can't fit into long due to sign bit is used for value
4831             MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});
4832             if (roundingMode == ROUND_DOWN && scale == preferredScale) {
4833                 return mq.toBigDecimal(sign, scale);
4834             }
4835             long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4836             if (r != 0) {
4837                 if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){
4838                     mq.add(MutableBigInteger.ONE);
4839                 }
4840                 return mq.toBigDecimal(sign, scale);
4841             } else {
4842                 if (preferredScale != scale) {
4843                     BigInteger intVal =  mq.toBigInteger(sign);
4844                     return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4845                 } else {
4846                     return mq.toBigDecimal(sign, scale);
4847                 }
4848             }
4849         }
4850         long q = make64(q1,q0);
4851         q*=sign;
4852         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4853             return valueOf(q, scale);
4854         long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4855         if (r != 0) {
4856             boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);
4857             return valueOf((increment ? q + sign : q), scale);
4858         } else {
4859             if (preferredScale != scale) {
4860                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4861             } else {
4862                 return valueOf(q, scale);
4863             }
4864         }
4865     }
4866 
4867     /*
4868      * calculate divideAndRound for ldividend*10^raise / divisor
4869      * when abs(dividend)==abs(divisor);
4870      */
4871     private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {
4872         if (scale > preferredScale) {
4873             int diff = scale - preferredScale;
4874             if(diff < raise) {
4875                 return scaledTenPow(raise - diff, qsign, preferredScale);
4876             } else {
4877                 return valueOf(qsign,scale-raise);
4878             }
4879         } else {
4880             return scaledTenPow(raise, qsign, scale);
4881         }
4882     }
4883 
4884     static BigDecimal scaledTenPow(int n, int sign, int scale) {
4885         if (n < LONG_TEN_POWERS_TABLE.length)
4886             return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);
4887         else {
4888             BigInteger unscaledVal = bigTenToThe(n);
4889             if(sign==-1) {
4890                 unscaledVal = unscaledVal.negate();
4891             }
4892             return new BigDecimal(unscaledVal, INFLATED, scale, n+1);
4893         }
4894     }
4895 
4896     private static long divWord(long n, long dLong) {
4897         long r;
4898         long q;
4899         if (dLong == 1) {
4900             q = (int)n;
4901             return (q & LONG_MASK);
4902         }
4903         // Approximate the quotient and remainder
4904         q = (n >>> 1) / (dLong >>> 1);
4905         r = n - q*dLong;
4906 
4907         // Correct the approximation
4908         while (r < 0) {
4909             r += dLong;
4910             q--;
4911         }
4912         while (r >= dLong) {
4913             r -= dLong;
4914             q++;
4915         }
4916         // n - q*dlong == r && 0 <= r <dLong, hence we're done.
4917         return (r << 32) | (q & LONG_MASK);
4918     }
4919 
4920     private static long make64(long hi, long lo) {
4921         return hi<<32 | lo;
4922     }
4923 
4924     private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {
4925         long tmp = u0 - q0*v0;
4926         return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);
4927     }
4928 
4929     private static boolean unsignedLongCompare(long one, long two) {
4930         return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
4931     }
4932 
4933     private static boolean unsignedLongCompareEq(long one, long two) {
4934         return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);
4935     }
4936 
4937 
4938     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4939     private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {
4940         // assert xs!=0 && ys!=0
4941         int sdiff = xscale - yscale;
4942         if (sdiff != 0) {
4943             if (sdiff < 0) {
4944                 xs = longMultiplyPowerTen(xs, -sdiff);
4945             } else { // sdiff > 0
4946                 ys = longMultiplyPowerTen(ys, sdiff);
4947             }
4948         }
4949         if (xs != INFLATED)
4950             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
4951         else
4952             return 1;
4953     }
4954 
4955     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4956     private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
4957         // assert "ys can't be represented as long"
4958         if (xs == 0)
4959             return -1;
4960         int sdiff = xscale - yscale;
4961         if (sdiff < 0) {
4962             if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
4963                 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
4964             }
4965         }
4966         return -1;
4967     }
4968 
4969     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4970     private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {
4971         int sdiff = xscale - yscale;
4972         if (sdiff < 0) {
4973             return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
4974         } else { // sdiff >= 0
4975             return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));
4976         }
4977     }
4978 
4979     private static long multiply(long x, long y){
4980                 long product = x * y;
4981         long ax = Math.abs(x);
4982         long ay = Math.abs(y);
4983         if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){
4984                         return product;
4985                 }
4986         return INFLATED;
4987     }
4988 
4989     private static BigDecimal multiply(long x, long y, int scale) {
4990         long product = multiply(x, y);
4991         if(product!=INFLATED) {
4992             return valueOf(product,scale);
4993         }
4994         return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);
4995     }
4996 
4997     private static BigDecimal multiply(long x, BigInteger y, int scale) {
4998         if(x==0) {
4999             return zeroValueOf(scale);
5000         }
5001         return new BigDecimal(y.multiply(x),INFLATED,scale,0);
5002     }
5003 
5004     private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {
5005         return new BigDecimal(x.multiply(y),INFLATED,scale,0);
5006     }
5007 
5008     /**
5009      * Multiplies two long values and rounds according {@code MathContext}
5010      */
5011     private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {
5012         long product = multiply(x, y);
5013         if(product!=INFLATED) {
5014             return doRound(product, scale, mc);
5015         }
5016         // attempt to do it in 128 bits
5017         int rsign = 1;
5018         if(x < 0) {
5019             x = -x;
5020             rsign = -1;
5021         }
5022         if(y < 0) {
5023             y = -y;
5024             rsign *= -1;
5025         }
5026         // multiply dividend0 * dividend1
5027         long m0_hi = x >>> 32;
5028         long m0_lo = x & LONG_MASK;
5029         long m1_hi = y >>> 32;
5030         long m1_lo = y & LONG_MASK;
5031         product = m0_lo * m1_lo;
5032         long m0 = product & LONG_MASK;
5033         long m1 = product >>> 32;
5034         product = m0_hi * m1_lo + m1;
5035         m1 = product & LONG_MASK;
5036         long m2 = product >>> 32;
5037         product = m0_lo * m1_hi + m1;
5038         m1 = product & LONG_MASK;
5039         m2 += product >>> 32;
5040         long m3 = m2>>>32;
5041         m2 &= LONG_MASK;
5042         product = m0_hi*m1_hi + m2;
5043         m2 = product & LONG_MASK;
5044         m3 = ((product>>>32) + m3) & LONG_MASK;
5045         final long mHi = make64(m3,m2);
5046         final long mLo = make64(m1,m0);
5047         BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);
5048         if(res!=null) {
5049             return res;
5050         }
5051         res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);
5052         return doRound(res,mc);
5053     }
5054 
5055     private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {
5056         if(x==0) {
5057             return zeroValueOf(scale);
5058         }
5059         return doRound(y.multiply(x), scale, mc);
5060     }
5061 
5062     private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {
5063         return doRound(x.multiply(y), scale, mc);
5064     }
5065 
5066     /**
5067      * rounds 128-bit value according {@code MathContext}
5068      * returns null if result can't be repsented as compact BigDecimal.
5069      */
5070     private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
5071         int mcp = mc.precision;
5072         int drop;
5073         BigDecimal res = null;
5074         if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
5075             scale = checkScaleNonZero((long)scale - drop);
5076             res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
5077         }
5078         if(res!=null) {
5079             return doRound(res,mc);
5080         }
5081         return null;
5082     }
5083 
5084     private static final long[][] LONGLONG_TEN_POWERS_TABLE = {
5085         {   0L, 0x8AC7230489E80000L },  //10^19
5086         {       0x5L, 0x6bc75e2d63100000L },  //10^20
5087         {       0x36L, 0x35c9adc5dea00000L },  //10^21
5088         {       0x21eL, 0x19e0c9bab2400000L  },  //10^22
5089         {       0x152dL, 0x02c7e14af6800000L  },  //10^23
5090         {       0xd3c2L, 0x1bcecceda1000000L  },  //10^24
5091         {       0x84595L, 0x161401484a000000L  },  //10^25
5092         {       0x52b7d2L, 0xdcc80cd2e4000000L  },  //10^26
5093         {       0x33b2e3cL, 0x9fd0803ce8000000L  },  //10^27
5094         {       0x204fce5eL, 0x3e25026110000000L  },  //10^28
5095         {       0x1431e0faeL, 0x6d7217caa0000000L  },  //10^29
5096         {       0xc9f2c9cd0L, 0x4674edea40000000L  },  //10^30
5097         {       0x7e37be2022L, 0xc0914b2680000000L  },  //10^31
5098         {       0x4ee2d6d415bL, 0x85acef8100000000L  },  //10^32
5099         {       0x314dc6448d93L, 0x38c15b0a00000000L  },  //10^33
5100         {       0x1ed09bead87c0L, 0x378d8e6400000000L  },  //10^34
5101         {       0x13426172c74d82L, 0x2b878fe800000000L  },  //10^35
5102         {       0xc097ce7bc90715L, 0xb34b9f1000000000L  },  //10^36
5103         {       0x785ee10d5da46d9L, 0x00f436a000000000L  },  //10^37
5104         {       0x4b3b4ca85a86c47aL, 0x098a224000000000L  },  //10^38
5105     };
5106 
5107     /*
5108      * returns precision of 128-bit value
5109      */
5110     private static int precision(long hi, long lo){
5111         if(hi==0) {
5112             if(lo>=0) {
5113                 return longDigitLength(lo);
5114             }
5115             return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;
5116             // 0x8AC7230489E80000L  = unsigned 2^19
5117         }
5118         int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;
5119         int idx = r-19;
5120         return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,
5121                                                                                     LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;
5122     }
5123 
5124     /*
5125      * returns true if 128 bit number <hi0,lo0> is less then <hi1,lo1>
5126      * hi0 & hi1 should be non-negative
5127      */
5128     private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {
5129         if(hi0!=hi1) {
5130             return hi0<hi1;
5131         }
5132         return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);
5133     }
5134 
5135     private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5136         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5137             int newScale = scale + divisorScale;
5138             int raise = newScale - dividendScale;
5139             if(raise<LONG_TEN_POWERS_TABLE.length) {
5140                 long xs = dividend;
5141                 if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {
5142                     return divideAndRound(xs, divisor, scale, roundingMode, scale);
5143                 }
5144                 BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);
5145                 if(q!=null) {
5146                     return q;
5147                 }
5148             }
5149             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5150             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5151         } else {
5152             int newScale = checkScale(divisor,(long)dividendScale - scale);
5153             int raise = newScale - divisorScale;
5154             if(raise<LONG_TEN_POWERS_TABLE.length) {
5155                 long ys = divisor;
5156                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5157                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5158                 }
5159             }
5160             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5161             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5162         }
5163     }
5164 
5165     private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5166         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5167             int newScale = scale + divisorScale;
5168             int raise = newScale - dividendScale;
5169             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5170             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5171         } else {
5172             int newScale = checkScale(divisor,(long)dividendScale - scale);
5173             int raise = newScale - divisorScale;
5174             if(raise<LONG_TEN_POWERS_TABLE.length) {
5175                 long ys = divisor;
5176                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5177                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5178                 }
5179             }
5180             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5181             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5182         }
5183     }
5184 
5185     private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5186         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5187             int newScale = scale + divisorScale;
5188             int raise = newScale - dividendScale;
5189             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5190             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5191         } else {
5192             int newScale = checkScale(divisor,(long)dividendScale - scale);
5193             int raise = newScale - divisorScale;
5194             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5195             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5196         }
5197     }
5198 
5199     private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5200         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5201             int newScale = scale + divisorScale;
5202             int raise = newScale - dividendScale;
5203             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5204             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5205         } else {
5206             int newScale = checkScale(divisor,(long)dividendScale - scale);
5207             int raise = newScale - divisorScale;
5208             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5209             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5210         }
5211     }
5212 
5213 }