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