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