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