src/share/classes/java/math/BigDecimal.java

Print this page




 198  * <p>Note: care should be exercised if {@code BigDecimal} objects
 199  * are used as keys in a {@link java.util.SortedMap SortedMap} or
 200  * elements in a {@link java.util.SortedSet SortedSet} since
 201  * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
 202  * with equals</i>.  See {@link Comparable}, {@link
 203  * java.util.SortedMap} or {@link java.util.SortedSet} for more
 204  * information.
 205  *
 206  * <p>All methods and constructors for this class throw
 207  * {@code NullPointerException} when passed a {@code null} object
 208  * reference for any input parameter.
 209  *
 210  * @see     BigInteger
 211  * @see     MathContext
 212  * @see     RoundingMode
 213  * @see     java.util.SortedMap
 214  * @see     java.util.SortedSet
 215  * @author  Josh Bloch
 216  * @author  Mike Cowlishaw
 217  * @author  Joseph D. Darcy

 218  */
 219 public class BigDecimal extends Number implements Comparable<BigDecimal> {
 220     /**
 221      * The unscaled value of this BigDecimal, as returned by {@link
 222      * #unscaledValue}.
 223      *
 224      * @serial
 225      * @see #unscaledValue
 226      */
 227     private volatile BigInteger intVal;
 228 
 229     /**
 230      * The scale of this BigDecimal, as returned by {@link #scale}.
 231      *
 232      * @serial
 233      * @see #scale
 234      */
 235     private int scale;  // Note: this may have any value, so
 236                         // calculations must be done in longs

 237     /**
 238      * The number of decimal digits in this BigDecimal, or 0 if the
 239      * number of digits are not known (lookaside information).  If
 240      * nonzero, the value is guaranteed correct.  Use the precision()
 241      * method to obtain and set the value if it might be 0.  This
 242      * field is mutable until set nonzero.
 243      *
 244      * @since  1.5
 245      */
 246     private transient int precision;
 247 
 248     /**
 249      * Used to store the canonical string representation, if computed.
 250      */
 251     private transient String stringCache;
 252 
 253     /**
 254      * Sentinel value for {@link #intCompact} indicating the
 255      * significand information is only available from {@code intVal}.
 256      */
 257     static final long INFLATED = Long.MIN_VALUE;
 258 


 259     /**
 260      * If the absolute value of the significand of this BigDecimal is
 261      * less than or equal to {@code Long.MAX_VALUE}, the value can be
 262      * compactly stored in this field and used in computations.
 263      */
 264     private transient long intCompact;
 265 
 266     // All 18-digit base ten strings fit into a long; not all 19-digit
 267     // strings will
 268     private static final int MAX_COMPACT_DIGITS = 18;
 269 
 270     private static final int MAX_BIGINT_BITS = 62;
 271 
 272     /* Appease the serialization gods */
 273     private static final long serialVersionUID = 6108874887143696463L;
 274 
 275     private static final ThreadLocal<StringBuilderHelper>
 276         threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
 277         @Override
 278         protected StringBuilderHelper initialValue() {
 279             return new StringBuilderHelper();
 280         }
 281     };
 282 
 283     // Cache of common small BigDecimal values.
 284     private static final BigDecimal zeroThroughTen[] = {
 285         new BigDecimal(BigInteger.ZERO,         0,  0, 1),
 286         new BigDecimal(BigInteger.ONE,          1,  0, 1),
 287         new BigDecimal(BigInteger.valueOf(2),   2,  0, 1),
 288         new BigDecimal(BigInteger.valueOf(3),   3,  0, 1),
 289         new BigDecimal(BigInteger.valueOf(4),   4,  0, 1),
 290         new BigDecimal(BigInteger.valueOf(5),   5,  0, 1),
 291         new BigDecimal(BigInteger.valueOf(6),   6,  0, 1),


 361     /**
 362      * Translates a character array representation of a
 363      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 364      * same sequence of characters as the {@link #BigDecimal(String)}
 365      * constructor, while allowing a sub-array to be specified.
 366      *
 367      * <p>Note that if the sequence of characters is already available
 368      * within a character array, using this constructor is faster than
 369      * converting the {@code char} array to string and using the
 370      * {@code BigDecimal(String)} constructor .
 371      *
 372      * @param  in {@code char} array that is the source of characters.
 373      * @param  offset first character in the array to inspect.
 374      * @param  len number of characters to consider.
 375      * @throws NumberFormatException if {@code in} is not a valid
 376      *         representation of a {@code BigDecimal} or the defined subarray
 377      *         is not wholly within {@code in}.
 378      * @since  1.5
 379      */
 380     public BigDecimal(char[] in, int offset, int len) {



























 381         // protect against huge length.
 382         if (offset+len > in.length || offset < 0)
 383             throw new NumberFormatException();
 384         // This is the primary string to BigDecimal constructor; all
 385         // incoming strings end up here; it uses explicit (inline)
 386         // parsing for speed and generates at most one intermediate
 387         // (temporary) object (a char[] array) for non-compact case.
 388 
 389         // Use locals for all fields values until completion
 390         int prec = 0;                 // record precision value
 391         int scl = 0;                  // record scale value
 392         long rs = 0;                  // the compact value in long
 393         BigInteger rb = null;         // the inflated value in BigInteger
 394 
 395         // use array bounds checking to handle too-long, len == 0,
 396         // bad offset, etc.
 397         try {
 398             // handle the sign
 399             boolean isneg = false;          // assume positive
 400             if (in[offset] == '-') {
 401                 isneg = true;               // leading minus means negative
 402                 offset++;
 403                 len--;
 404             } else if (in[offset] == '+') { // leading + allowed
 405                 offset++;
 406                 len--;
 407             }
 408 
 409             // should now be at numeric part of the significand
 410             boolean dot = false;             // true when there is a '.'
 411             int cfirst = offset;             // record start of integer
 412             long exp = 0;                    // exponent
 413             char c;                          // current character
 414 
 415             boolean isCompact = (len <= MAX_COMPACT_DIGITS);
 416             // integer significand array & idx is the index to it. The array
 417             // is ONLY used when we can't use a compact representation.
 418             char coeff[] = isCompact ? null : new char[len];
 419             int idx = 0;
 420 
 421             for (; len > 0; offset++, len--) {
 422                 c = in[offset];
 423                 // have digit
 424                 if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
 425                     // First compact case, we need not to preserve the character
 426                     // and we can just compute the value in place.
 427                     if (isCompact) {























 428                         int digit = Character.digit(c, 10);
 429                         if (digit == 0) {
 430                             if (prec == 0)
 431                                 prec = 1;
 432                             else if (rs != 0) {
 433                                 rs *= 10;
 434                                 ++prec;
 435                             } // else digit is a redundant leading zero
 436                         } else {
 437                             if (prec != 1 || rs != 0)
 438                                 ++prec; // prec unchanged if preceded by 0s
 439                             rs = rs * 10 + digit;
 440                         }
 441                     } else { // the unscaled value is likely a BigInteger object.





































 442                         if (c == '0' || Character.digit(c, 10) == 0) {
 443                             if (prec == 0) {
 444                                 coeff[idx] = c;
 445                                 prec = 1;
 446                             } else if (idx != 0) {
 447                                 coeff[idx++] = c;
 448                                 ++prec;
 449                             } // else c must be a redundant leading zero
 450                         } else {
 451                             if (prec != 1 || idx != 0)
 452                                 ++prec; // prec unchanged if preceded by 0s
 453                             coeff[idx++] = c;
 454                         }
 455                     }
 456                     if (dot)
 457                         ++scl;
 458                     continue;
 459                 }
 460                 // have dot
 461                 if (c == '.') {
 462                     // have dot
 463                     if (dot)         // two dots
 464                         throw new NumberFormatException();
 465                     dot = true;
 466                     continue;
 467                 }
 468                 // exponent expected
 469                 if ((c != 'e') && (c != 'E'))
 470                     throw new NumberFormatException();




































































 471                 offset++;
 472                 c = in[offset];
 473                 len--;
 474                 boolean negexp = (c == '-');
 475                 // optional sign
 476                 if (negexp || c == '+') {
 477                     offset++;
 478                     c = in[offset];
 479                     len--;
 480                 }
 481                 if (len <= 0)    // no exponent digits
 482                     throw new NumberFormatException();
 483                 // skip leading zeros in the exponent
 484                 while (len > 10 && Character.digit(c, 10) == 0) {
 485                     offset++;
 486                     c = in[offset];
 487                     len--;
 488                 }
 489                 if (len > 10)  // too many nonzero exponent digits
 490                     throw new NumberFormatException();
 491                 // c now holds first digit of exponent
 492                 for (;; len--) {
 493                     int v;
 494                     if (c >= '0' && c <= '9') {
 495                         v = c - '0';
 496                     } else {
 497                         v = Character.digit(c, 10);
 498                         if (v < 0)            // not a digit
 499                             throw new NumberFormatException();
 500                     }
 501                     exp = exp * 10 + v;
 502                     if (len == 1)
 503                         break;               // that was final character
 504                     offset++;
 505                     c = in[offset];
 506                 }
 507                 if (negexp)                  // apply sign
 508                     exp = -exp;
 509                 // Next test is required for backwards compatibility
 510                 if ((int)exp != exp)         // overflow
 511                     throw new NumberFormatException();
 512                 break;                       // [saves a test]
 513             }
 514             // here when no characters left
 515             if (prec == 0)              // no digits found
 516                 throw new NumberFormatException();
 517 
 518             // Adjust scale if exp is not zero.
 519             if (exp != 0) {                  // had significant exponent
 520                 // Can't call checkScale which relies on proper fields value
 521                 long adjustedScale = scl - exp;
 522                 if (adjustedScale > Integer.MAX_VALUE ||
 523                     adjustedScale < Integer.MIN_VALUE)
 524                     throw new NumberFormatException("Scale out of range.");
 525                 scl = (int)adjustedScale;
 526             }
 527 
 528             // Remove leading zeros from precision (digits count)
 529             if (isCompact) {
 530                 rs = isneg ? -rs : rs;
 531             } else {
 532                 char quick[];
 533                 if (!isneg) {
 534                     quick = (coeff.length != prec) ?
 535                         Arrays.copyOf(coeff, prec) : coeff;
 536                 } else {
 537                     quick = new char[prec + 1];
 538                     quick[0] = '-';
 539                     System.arraycopy(coeff, 0, quick, 1, prec);
 540                 }
 541                 rb = new BigInteger(quick);
 542                 rs = compactValFor(rb);
 543             }
 544         } catch (ArrayIndexOutOfBoundsException e) {
 545             throw new NumberFormatException();
 546         } catch (NegativeArraySizeException e) {
 547             throw new NumberFormatException();
 548         }
 549         this.scale = scl;
 550         this.precision = prec;
 551         this.intCompact = rs;
 552         this.intVal = (rs != INFLATED) ? null : rb;
 553     }
 554 
 555     /**
 556      * Translates a character array representation of a
 557      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 558      * same sequence of characters as the {@link #BigDecimal(String)}
 559      * constructor, while allowing a sub-array to be specified and
 560      * with rounding according to the context settings.
 561      *
 562      * <p>Note that if the sequence of characters is already available
 563      * within a character array, using this constructor is faster than
 564      * converting the {@code char} array to string and using the
 565      * {@code BigDecimal(String)} constructor .
 566      *
 567      * @param  in {@code char} array that is the source of characters.
 568      * @param  offset first character in the array to inspect.
 569      * @param  len number of characters to consider..
 570      * @param  mc the context to use.
 571      * @throws ArithmeticException if the result is inexact but the
 572      *         rounding mode is {@code UNNECESSARY}.
 573      * @throws NumberFormatException if {@code in} is not a valid
 574      *         representation of a {@code BigDecimal} or the defined subarray
 575      *         is not wholly within {@code in}.
 576      * @since  1.5
 577      */
 578     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
 579         this(in, offset, len);
 580         if (mc.precision > 0)
 581             roundThis(mc);
 582     }
 583 
 584     /**
 585      * Translates a character array representation of a
 586      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 587      * same sequence of characters as the {@link #BigDecimal(String)}
 588      * constructor.
 589      *
 590      * <p>Note that if the sequence of characters is already available
 591      * as a character array, using this constructor is faster than
 592      * converting the {@code char} array to string and using the
 593      * {@code BigDecimal(String)} constructor .
 594      *
 595      * @param in {@code char} array that is the source of characters.
 596      * @throws NumberFormatException if {@code in} is not a valid
 597      *         representation of a {@code BigDecimal}.
 598      * @since  1.5
 599      */
 600     public BigDecimal(char[] in) {
 601         this(in, 0, in.length);


 737      */
 738     public BigDecimal(String val) {
 739         this(val.toCharArray(), 0, val.length());
 740     }
 741 
 742     /**
 743      * Translates the string representation of a {@code BigDecimal}
 744      * into a {@code BigDecimal}, accepting the same strings as the
 745      * {@link #BigDecimal(String)} constructor, with rounding
 746      * according to the context settings.
 747      *
 748      * @param  val string representation of a {@code BigDecimal}.
 749      * @param  mc the context to use.
 750      * @throws ArithmeticException if the result is inexact but the
 751      *         rounding mode is {@code UNNECESSARY}.
 752      * @throws NumberFormatException if {@code val} is not a valid
 753      *         representation of a BigDecimal.
 754      * @since  1.5
 755      */
 756     public BigDecimal(String val, MathContext mc) {
 757         this(val.toCharArray(), 0, val.length());
 758         if (mc.precision > 0)
 759             roundThis(mc);
 760     }
 761 
 762     /**
 763      * Translates a {@code double} into a {@code BigDecimal} which
 764      * is the exact decimal representation of the {@code double}'s
 765      * binary floating-point value.  The scale of the returned
 766      * {@code BigDecimal} is the smallest value such that
 767      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 768      * <p>
 769      * <b>Notes:</b>
 770      * <ol>
 771      * <li>
 772      * The results of this constructor can be somewhat unpredictable.
 773      * One might assume that writing {@code new BigDecimal(0.1)} in
 774      * Java creates a {@code BigDecimal} which is exactly equal to
 775      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
 776      * actually equal to
 777      * 0.1000000000000000055511151231257827021181583404541015625.
 778      * This is because 0.1 cannot be represented exactly as a
 779      * {@code double} (or, for that matter, as a binary fraction of


 787      * creates a {@code BigDecimal} which is <i>exactly</i> equal to
 788      * 0.1, as one would expect.  Therefore, it is generally
 789      * recommended that the {@linkplain #BigDecimal(String)
 790      * <tt>String</tt> constructor} be used in preference to this one.
 791      *
 792      * <li>
 793      * When a {@code double} must be used as a source for a
 794      * {@code BigDecimal}, note that this constructor provides an
 795      * exact conversion; it does not give the same result as
 796      * converting the {@code double} to a {@code String} using the
 797      * {@link Double#toString(double)} method and then using the
 798      * {@link #BigDecimal(String)} constructor.  To get that result,
 799      * use the {@code static} {@link #valueOf(double)} method.
 800      * </ol>
 801      *
 802      * @param val {@code double} value to be converted to
 803      *        {@code BigDecimal}.
 804      * @throws NumberFormatException if {@code val} is infinite or NaN.
 805      */
 806     public BigDecimal(double val) {
 807         if (Double.isInfinite(val) || Double.isNaN(val))
 808             throw new NumberFormatException("Infinite or NaN");
 809 
 810         // Translate the double into sign, exponent and significand, according
 811         // to the formulae in JLS, Section 20.10.22.
 812         long valBits = Double.doubleToLongBits(val);
 813         int sign = ((valBits >> 63)==0 ? 1 : -1);
 814         int exponent = (int) ((valBits >> 52) & 0x7ffL);
 815         long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
 816                             : (valBits & ((1L<<52) - 1)) | (1L<<52));
 817         exponent -= 1075;
 818         // At this point, val == sign * significand * 2**exponent.
 819 
 820         /*
 821          * Special case zero to supress nonterminating normalization
 822          * and bogus scale calculation.
 823          */
 824         if (significand == 0) {
 825             intVal = BigInteger.ZERO;
 826             intCompact = 0;
 827             precision = 1;
 828             return;
 829         }
 830 
 831         // Normalize
 832         while((significand & 1) == 0) {    //  i.e., significand is even
 833             significand >>= 1;
 834             exponent++;
 835         }
 836 
 837         // Calculate intVal and scale
 838         long s = sign * significand;
 839         BigInteger b;
 840         if (exponent < 0) {
 841             b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
 842             scale = -exponent;
 843         } else if (exponent > 0) {
 844             b = BigInteger.valueOf(2).pow(exponent).multiply(s);
 845         } else {
 846             b = BigInteger.valueOf(s);
 847         }
 848         intCompact = compactValFor(b);
 849         intVal = (intCompact != INFLATED) ? null : b;
 850     }
 851 
 852     /**
 853      * Translates a {@code double} into a {@code BigDecimal}, with
 854      * rounding according to the context settings.  The scale of the
 855      * {@code BigDecimal} is the smallest value such that
 856      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 857      *
 858      * <p>The results of this constructor can be somewhat unpredictable
 859      * and its use is generally not recommended; see the notes under
 860      * the {@link #BigDecimal(double)} constructor.
 861      *
 862      * @param  val {@code double} value to be converted to
 863      *         {@code BigDecimal}.
 864      * @param  mc the context to use.
 865      * @throws ArithmeticException if the result is inexact but the
 866      *         RoundingMode is UNNECESSARY.
 867      * @throws NumberFormatException if {@code val} is infinite or NaN.
 868      * @since  1.5
 869      */
 870     public BigDecimal(double val, MathContext mc) {
 871         this(val);
 872         if (mc.precision > 0)
 873             roundThis(mc);













































































 874     }
 875 
 876     /**
 877      * Translates a {@code BigInteger} into a {@code BigDecimal}.
 878      * The scale of the {@code BigDecimal} is zero.
 879      *
 880      * @param val {@code BigInteger} value to be converted to
 881      *            {@code BigDecimal}.
 882      */
 883     public BigDecimal(BigInteger val) {


 884         intCompact = compactValFor(val);
 885         intVal = (intCompact != INFLATED) ? null : val;
 886     }
 887 
 888     /**
 889      * Translates a {@code BigInteger} into a {@code BigDecimal}
 890      * rounding according to the context settings.  The scale of the
 891      * {@code BigDecimal} is zero.
 892      *
 893      * @param val {@code BigInteger} value to be converted to
 894      *            {@code BigDecimal}.
 895      * @param  mc the context to use.
 896      * @throws ArithmeticException if the result is inexact but the
 897      *         rounding mode is {@code UNNECESSARY}.
 898      * @since  1.5
 899      */
 900     public BigDecimal(BigInteger val, MathContext mc) {
 901         this(val);
 902         if (mc.precision > 0)
 903             roundThis(mc);
 904     }
 905 
 906     /**
 907      * Translates a {@code BigInteger} unscaled value and an
 908      * {@code int} scale into a {@code BigDecimal}.  The value of
 909      * the {@code BigDecimal} is
 910      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
 911      *
 912      * @param unscaledVal unscaled value of the {@code BigDecimal}.
 913      * @param scale scale of the {@code BigDecimal}.
 914      */
 915     public BigDecimal(BigInteger unscaledVal, int scale) {
 916         // Negative scales are now allowed
 917         this(unscaledVal);

 918         this.scale = scale;
 919     }
 920 
 921     /**
 922      * Translates a {@code BigInteger} unscaled value and an
 923      * {@code int} scale into a {@code BigDecimal}, with rounding
 924      * according to the context settings.  The value of the
 925      * {@code BigDecimal} is <tt>(unscaledVal &times;
 926      * 10<sup>-scale</sup>)</tt>, rounded according to the
 927      * {@code precision} and rounding mode settings.
 928      *
 929      * @param  unscaledVal unscaled value of the {@code BigDecimal}.
 930      * @param  scale scale of the {@code BigDecimal}.
 931      * @param  mc the context to use.
 932      * @throws ArithmeticException if the result is inexact but the
 933      *         rounding mode is {@code UNNECESSARY}.
 934      * @since  1.5
 935      */
 936     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
 937         this(unscaledVal);
































 938         this.scale = scale;
 939         if (mc.precision > 0)
 940             roundThis(mc);
 941     }
 942 
 943     /**
 944      * Translates an {@code int} into a {@code BigDecimal}.  The
 945      * scale of the {@code BigDecimal} is zero.
 946      *
 947      * @param val {@code int} value to be converted to
 948      *            {@code BigDecimal}.
 949      * @since  1.5
 950      */
 951     public BigDecimal(int val) {
 952         intCompact = val;


 953     }
 954 
 955     /**
 956      * Translates an {@code int} into a {@code BigDecimal}, with
 957      * rounding according to the context settings.  The scale of the
 958      * {@code BigDecimal}, before any rounding, is zero.
 959      *
 960      * @param  val {@code int} value to be converted to {@code BigDecimal}.
 961      * @param  mc the context to use.
 962      * @throws ArithmeticException if the result is inexact but the
 963      *         rounding mode is {@code UNNECESSARY}.
 964      * @since  1.5
 965      */
 966     public BigDecimal(int val, MathContext mc) {
 967         intCompact = val;
 968         if (mc.precision > 0)
 969             roundThis(mc);















 970     }
 971 
 972     /**
 973      * Translates a {@code long} into a {@code BigDecimal}.  The
 974      * scale of the {@code BigDecimal} is zero.
 975      *
 976      * @param val {@code long} value to be converted to {@code BigDecimal}.
 977      * @since  1.5
 978      */
 979     public BigDecimal(long val) {
 980         this.intCompact = val;
 981         this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;

 982     }
 983 
 984     /**
 985      * Translates a {@code long} into a {@code BigDecimal}, with
 986      * rounding according to the context settings.  The scale of the
 987      * {@code BigDecimal}, before any rounding, is zero.
 988      *
 989      * @param  val {@code long} value to be converted to {@code BigDecimal}.
 990      * @param  mc the context to use.
 991      * @throws ArithmeticException if the result is inexact but the
 992      *         rounding mode is {@code UNNECESSARY}.
 993      * @since  1.5
 994      */
 995     public BigDecimal(long val, MathContext mc) {
 996         this(val);
 997         if (mc.precision > 0)
 998             roundThis(mc);
 999     }

































1000 
1001     // Static Factory Methods
1002 
1003     /**
1004      * Translates a {@code long} unscaled value and an
1005      * {@code int} scale into a {@code BigDecimal}.  This
1006      * {@literal "static factory method"} is provided in preference to
1007      * a ({@code long}, {@code int}) constructor because it
1008      * allows for reuse of frequently used {@code BigDecimal} values..
1009      *
1010      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1011      * @param scale scale of the {@code BigDecimal}.
1012      * @return a {@code BigDecimal} whose value is
1013      *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1014      */
1015     public static BigDecimal valueOf(long unscaledVal, int scale) {
1016         if (scale == 0)
1017             return valueOf(unscaledVal);
1018         else if (unscaledVal == 0) {
1019             if (scale > 0 && scale < ZERO_SCALED_BY.length)
1020                 return ZERO_SCALED_BY[scale];
1021             else
1022                 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1023         }
1024         return new BigDecimal(unscaledVal == INFLATED ?
1025                               BigInteger.valueOf(unscaledVal) : null,
1026                               unscaledVal, scale, 0);
1027     }
1028 
1029     /**
1030      * Translates a {@code long} value into a {@code BigDecimal}
1031      * with a scale of zero.  This {@literal "static factory method"}
1032      * is provided in preference to a ({@code long}) constructor
1033      * because it allows for reuse of frequently used
1034      * {@code BigDecimal} values.
1035      *
1036      * @param val value of the {@code BigDecimal}.
1037      * @return a {@code BigDecimal} whose value is {@code val}.
1038      */
1039     public static BigDecimal valueOf(long val) {
1040         if (val >= 0 && val < zeroThroughTen.length)
1041             return zeroThroughTen[(int)val];
1042         else if (val != INFLATED)
1043             return new BigDecimal(null, val, 0, 0);
1044         return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);



























1045     }
1046 
1047     /**
1048      * Translates a {@code double} into a {@code BigDecimal}, using
1049      * the {@code double}'s canonical string representation provided
1050      * by the {@link Double#toString(double)} method.
1051      *
1052      * <p><b>Note:</b> This is generally the preferred way to convert
1053      * a {@code double} (or {@code float}) into a
1054      * {@code BigDecimal}, as the value returned is equal to that
1055      * resulting from constructing a {@code BigDecimal} from the
1056      * result of using {@link Double#toString(double)}.
1057      *
1058      * @param  val {@code double} to convert to a {@code BigDecimal}.
1059      * @return a {@code BigDecimal} whose value is equal to or approximately
1060      *         equal to the value of {@code val}.
1061      * @throws NumberFormatException if {@code val} is infinite or NaN.
1062      * @since  1.5
1063      */
1064     public static BigDecimal valueOf(double val) {
1065         // Reminder: a zero double returns '0.0', so we cannot fastpath
1066         // to use the constant ZERO.  This might be important enough to
1067         // justify a factory approach, a cache, or a few private
1068         // constants, later.
1069         return new BigDecimal(Double.toString(val));
1070     }
1071 
1072     // Arithmetic Operations
1073     /**
1074      * Returns a {@code BigDecimal} whose value is {@code (this +
1075      * augend)}, and whose scale is {@code max(this.scale(),
1076      * augend.scale())}.
1077      *
1078      * @param  augend value to be added to this {@code BigDecimal}.
1079      * @return {@code this + augend}
1080      */
1081     public BigDecimal add(BigDecimal augend) {
1082         long xs = this.intCompact;
1083         long ys = augend.intCompact;
1084         BigInteger fst = (xs != INFLATED) ? null : this.intVal;
1085         BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
1086         int rscale = this.scale;
1087 
1088         long sdiff = (long)rscale - augend.scale;
1089         if (sdiff != 0) {
1090             if (sdiff < 0) {
1091                 int raise = checkScale(-sdiff);
1092                 rscale = augend.scale;
1093                 if (xs == INFLATED ||
1094                     (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
1095                     fst = bigMultiplyPowerTen(raise);
1096             } else {
1097                 int raise = augend.checkScale(sdiff);
1098                 if (ys == INFLATED ||
1099                     (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
1100                     snd = augend.bigMultiplyPowerTen(raise);
1101             }





1102         }
1103         if (xs != INFLATED && ys != INFLATED) {
1104             long sum = xs + ys;
1105             // See "Hacker's Delight" section 2-12 for explanation of
1106             // the overflow test.
1107             if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
1108                 return BigDecimal.valueOf(sum, rscale);
1109         }
1110         if (fst == null)
1111             fst = BigInteger.valueOf(xs);
1112         if (snd == null)
1113             snd = BigInteger.valueOf(ys);
1114         BigInteger sum = fst.add(snd);
1115         return (fst.signum == snd.signum) ?
1116             new BigDecimal(sum, INFLATED, rscale, 0) :
1117             new BigDecimal(sum, rscale);
1118     }
1119 
1120     /**
1121      * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1122      * with rounding according to the context settings.
1123      *
1124      * If either number is zero and the precision setting is nonzero then
1125      * the other number, rounded if necessary, is used as the result.
1126      *
1127      * @param  augend value to be added to this {@code BigDecimal}.
1128      * @param  mc the context to use.
1129      * @return {@code this + augend}, rounded as necessary.
1130      * @throws ArithmeticException if the result is inexact but the
1131      *         rounding mode is {@code UNNECESSARY}.
1132      * @since  1.5
1133      */
1134     public BigDecimal add(BigDecimal augend, MathContext mc) {
1135         if (mc.precision == 0)
1136             return add(augend);
1137         BigDecimal lhs = this;
1138 
1139         // Could optimize if values are compact
1140         this.inflate();
1141         augend.inflate();
1142 
1143         // If either number is zero then the other number, rounded and
1144         // scaled if necessary, is used as the result.
1145         {
1146             boolean lhsIsZero = lhs.signum() == 0;
1147             boolean augendIsZero = augend.signum() == 0;
1148 
1149             if (lhsIsZero || augendIsZero) {
1150                 int preferredScale = Math.max(lhs.scale(), augend.scale());
1151                 BigDecimal result;
1152 
1153                 // Could use a factory for zero instead of a new object
1154                 if (lhsIsZero && augendIsZero)
1155                     return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
1156 
1157                 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1158 
1159                 if (result.scale() == preferredScale)
1160                     return result;
1161                 else if (result.scale() > preferredScale) {
1162                     BigDecimal scaledResult =
1163                         new BigDecimal(result.intVal, result.intCompact,
1164                                        result.scale, 0);
1165                     scaledResult.stripZerosToMatchScale(preferredScale);
1166                     return scaledResult;
1167                 } else { // result.scale < preferredScale
1168                     int precisionDiff = mc.precision - result.precision();
1169                     int scaleDiff     = preferredScale - result.scale();
1170 
1171                     if (precisionDiff >= scaleDiff)
1172                         return result.setScale(preferredScale); // can achieve target scale
1173                     else
1174                         return result.setScale(result.scale() + precisionDiff);
1175                 }
1176             }
1177         }
1178 
1179         long padding = (long)lhs.scale - augend.scale;
1180         if (padding != 0) {        // scales differ; alignment needed
1181             BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1182             matchScale(arg);
1183             lhs    = arg[0];
1184             augend = arg[1];
1185         }
1186 
1187         BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
1188                                       lhs.scale);
1189         return doRound(d, mc);
1190     }
1191 
1192     /**
1193      * Returns an array of length two, the sum of whose entries is
1194      * equal to the rounded sum of the {@code BigDecimal} arguments.
1195      *
1196      * <p>If the digit positions of the arguments have a sufficient
1197      * gap between them, the value smaller in magnitude can be
1198      * condensed into a {@literal "sticky bit"} and the end result will
1199      * round the same way <em>if</em> the precision of the final
1200      * result does not include the high order digit of the small
1201      * magnitude operand.
1202      *
1203      * <p>Note that while strictly speaking this is an optimization,
1204      * it makes a much wider range of additions practical.
1205      *
1206      * <p>This corresponds to a pre-shift operation in a fixed
1207      * precision floating-point adder; this method is complicated by
1208      * variable precision of the result as determined by the
1209      * MathContext.  A more nuanced operation could implement a
1210      * {@literal "right shift"} on the smaller magnitude operand so
1211      * that the number of digits of the smaller operand could be
1212      * reduced even though the significands partially overlapped.
1213      */
1214     private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
1215                                   long padding, MathContext mc) {
1216         assert padding != 0;
1217         BigDecimal big;
1218         BigDecimal small;
1219 
1220         if (padding < 0) {     // lhs is big;   augend is small
1221             big   = lhs;
1222             small = augend;
1223         } else {               // lhs is small; augend is big
1224             big   = augend;
1225             small = lhs;
1226         }
1227 
1228         /*
1229          * This is the estimated scale of an ulp of the result; it
1230          * assumes that the result doesn't have a carry-out on a true
1231          * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1232          * on borrowing (e.g. 100 - 1.2 => 98.8)
1233          */
1234         long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
1235 
1236         /*
1237          * The low-order digit position of big is big.scale().  This
1238          * is true regardless of whether big has a positive or
1239          * negative scale.  The high-order digit position of small is
1240          * small.scale - (small.precision() - 1).  To do the full
1241          * condensation, the digit positions of big and small must be
1242          * disjoint *and* the digit positions of small should not be
1243          * directly visible in the result.
1244          */
1245         long smallHighDigitPos = (long)small.scale - small.precision() + 1;
1246         if (smallHighDigitPos > big.scale + 2 &&         // big and small disjoint
1247             smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1248             small = BigDecimal.valueOf(small.signum(),
1249                                        this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1250         }
1251 
1252         // Since addition is symmetric, preserving input order in
1253         // returned operands doesn't matter
1254         BigDecimal[] result = {big, small};
1255         return result;
1256     }
1257 
1258     /**
1259      * Returns a {@code BigDecimal} whose value is {@code (this -
1260      * subtrahend)}, and whose scale is {@code max(this.scale(),
1261      * subtrahend.scale())}.
1262      *
1263      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1264      * @return {@code this - subtrahend}
1265      */
1266     public BigDecimal subtract(BigDecimal subtrahend) {
1267         return add(subtrahend.negate());















1268     }
1269 
1270     /**
1271      * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1272      * with rounding according to the context settings.
1273      *
1274      * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1275      * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1276      *
1277      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1278      * @param  mc the context to use.
1279      * @return {@code this - subtrahend}, rounded as necessary.
1280      * @throws ArithmeticException if the result is inexact but the
1281      *         rounding mode is {@code UNNECESSARY}.
1282      * @since  1.5
1283      */
1284     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1285         BigDecimal nsubtrahend = subtrahend.negate();
1286         if (mc.precision == 0)
1287             return add(nsubtrahend);
1288         // share the special rounding code in add()
1289         return add(nsubtrahend, mc);
1290     }
1291 
1292     /**
1293      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1294      * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1295      * multiplicand.scale())}.
1296      *
1297      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1298      * @return {@code this * multiplicand}
1299      */
1300     public BigDecimal multiply(BigDecimal multiplicand) {
1301         long x = this.intCompact;
1302         long y = multiplicand.intCompact;
1303         int productScale = checkScale((long)scale + multiplicand.scale);
1304 
1305         // Might be able to do a more clever check incorporating the
1306         // inflated check into the overflow computation.
1307         if (x != INFLATED && y != INFLATED) {
1308             /*
1309              * If the product is not an overflowed value, continue
1310              * to use the compact representation.  if either of x or y
1311              * is INFLATED, the product should also be regarded as
1312              * an overflow. Before using the overflow test suggested in
1313              * "Hacker's Delight" section 2-12, we perform quick checks
1314              * using the precision information to see whether the overflow
1315              * would occur since division is expensive on most CPUs.
1316              */
1317             long product = x * y;
1318             long prec = this.precision() + multiplicand.precision();
1319             if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
1320                 return BigDecimal.valueOf(product, productScale);
1321             return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
1322                                   productScale, 0);
1323         }
1324         BigInteger rb;
1325         if (x == INFLATED && y == INFLATED)
1326             rb = this.intVal.multiply(multiplicand.intVal);
1327         else if (x != INFLATED)
1328             rb = multiplicand.intVal.multiply(x);
1329         else
1330             rb = this.intVal.multiply(y);
1331         return new BigDecimal(rb, INFLATED, productScale, 0);
1332     }
1333 
1334     /**
1335      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1336      * multiplicand)</tt>, with rounding according to the context settings.
1337      *
1338      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1339      * @param  mc the context to use.
1340      * @return {@code this * multiplicand}, rounded as necessary.
1341      * @throws ArithmeticException if the result is inexact but the
1342      *         rounding mode is {@code UNNECESSARY}.
1343      * @since  1.5
1344      */
1345     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1346         if (mc.precision == 0)
1347             return multiply(multiplicand);
1348         return doRound(this.multiply(multiplicand), mc);













1349     }
1350 
1351     /**
1352      * Returns a {@code BigDecimal} whose value is {@code (this /
1353      * divisor)}, and whose scale is as specified.  If rounding must
1354      * be performed to generate a result with the specified scale, the
1355      * specified rounding mode is applied.
1356      *
1357      * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1358      * should be used in preference to this legacy method.
1359      *
1360      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1361      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1362      * @param  roundingMode rounding mode to apply.
1363      * @return {@code this / divisor}
1364      * @throws ArithmeticException if {@code divisor} is zero,
1365      *         {@code roundingMode==ROUND_UNNECESSARY} and
1366      *         the specified scale is insufficient to represent the result
1367      *         of the division exactly.
1368      * @throws IllegalArgumentException if {@code roundingMode} does not
1369      *         represent a valid rounding mode.
1370      * @see    #ROUND_UP
1371      * @see    #ROUND_DOWN
1372      * @see    #ROUND_CEILING
1373      * @see    #ROUND_FLOOR
1374      * @see    #ROUND_HALF_UP
1375      * @see    #ROUND_HALF_DOWN
1376      * @see    #ROUND_HALF_EVEN
1377      * @see    #ROUND_UNNECESSARY
1378      */
1379     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1380         /*
1381          * IMPLEMENTATION NOTE: This method *must* return a new object
1382          * since divideAndRound uses divide to generate a value whose
1383          * scale is then modified.
1384          */
1385         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1386             throw new IllegalArgumentException("Invalid rounding mode");
1387         /*
1388          * Rescale dividend or divisor (whichever can be "upscaled" to
1389          * produce correctly scaled quotient).
1390          * Take care to detect out-of-range scales
1391          */
1392         BigDecimal dividend = this;
1393         if (checkScale((long)scale + divisor.scale) > this.scale)
1394             dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
1395         else
1396             divisor = divisor.setScale(checkScale((long)this.scale - scale),
1397                                        ROUND_UNNECESSARY);
1398         return divideAndRound(dividend.intCompact, dividend.intVal,
1399                               divisor.intCompact, divisor.intVal,
1400                               scale, roundingMode, scale);
1401     }
1402 
1403     /**
1404      * Internally used for division operation. The dividend and divisor are
1405      * passed both in {@code long} format and {@code BigInteger} format. The
1406      * returned {@code BigDecimal} object is the quotient whose scale is set to
1407      * the passed in scale. If the remainder is not zero, it will be rounded
1408      * based on the passed in roundingMode. Also, if the remainder is zero and
1409      * the last parameter, i.e. preferredScale is NOT equal to scale, the
1410      * trailing zeros of the result is stripped to match the preferredScale.
1411      */
1412     private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend,
1413                                              long ldivisor,  BigInteger bdivisor,
1414                                              int scale, int roundingMode,
1415                                              int preferredScale) {
1416         boolean isRemainderZero;       // record remainder is zero or not
1417         int qsign;                     // quotient sign
1418         long q = 0, r = 0;             // store quotient & remainder in long
1419         MutableBigInteger mq = null;   // store quotient
1420         MutableBigInteger mr = null;   // store remainder
1421         MutableBigInteger mdivisor = null;
1422         boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
1423         if (isLongDivision) {
1424             q = ldividend / ldivisor;
1425             if (roundingMode == ROUND_DOWN && scale == preferredScale)
1426                 return new BigDecimal(null, q, scale, 0);
1427             r = ldividend % ldivisor;
1428             isRemainderZero = (r == 0);
1429             qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
1430         } else {
1431             if (bdividend == null)
1432                 bdividend = BigInteger.valueOf(ldividend);
1433             // Descend into mutables for faster remainder checks
1434             MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
1435             mq = new MutableBigInteger();
1436             if (ldivisor != INFLATED) {
1437                 r = mdividend.divide(ldivisor, mq);
1438                 isRemainderZero = (r == 0);
1439                 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
1440             } else {
1441                 mdivisor = new MutableBigInteger(bdivisor.mag);
1442                 mr = mdividend.divide(mdivisor, mq);
1443                 isRemainderZero = mr.isZero();
1444                 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
1445             }
1446         }
1447         boolean increment = false;
1448         if (!isRemainderZero) {
1449             int cmpFracHalf;
1450             /* Round as appropriate */
1451             if (roundingMode == ROUND_UNNECESSARY) {  // Rounding prohibited
1452                 throw new ArithmeticException("Rounding necessary");
1453             } else if (roundingMode == ROUND_UP) {      // Away from zero
1454                 increment = true;
1455             } else if (roundingMode == ROUND_DOWN) {    // Towards zero
1456                 increment = false;
1457             } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1458                 increment = (qsign > 0);
1459             } else if (roundingMode == ROUND_FLOOR) {   // Towards -infinity
1460                 increment = (qsign < 0);
1461             } else {
1462                 if (isLongDivision || ldivisor != INFLATED) {
1463                     if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
1464                         cmpFracHalf = 1;    // 2 * r can't fit into long
1465                     } else {
1466                         cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
1467                     }
1468                 } else {
1469                     cmpFracHalf = mr.compareHalf(mdivisor);
1470                 }
1471                 if (cmpFracHalf < 0)
1472                     increment = false;     // We're closer to higher digit
1473                 else if (cmpFracHalf > 0)  // We're closer to lower digit
1474                     increment = true;
1475                 else if (roundingMode == ROUND_HALF_UP)
1476                     increment = true;
1477                 else if (roundingMode == ROUND_HALF_DOWN)
1478                     increment = false;
1479                 else  // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
1480                     increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
1481             }
1482         }
1483         BigDecimal res;
1484         if (isLongDivision)
1485             res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
1486         else {
1487             if (increment)
1488                 mq.add(MutableBigInteger.ONE);
1489             res = mq.toBigDecimal(qsign, scale);
1490         }
1491         if (isRemainderZero && preferredScale != scale)
1492             res.stripZerosToMatchScale(preferredScale);
1493         return res;
1494     }
1495 
1496     /**
1497      * Returns a {@code BigDecimal} whose value is {@code (this /
1498      * divisor)}, and whose scale is as specified.  If rounding must
1499      * be performed to generate a result with the specified scale, the
1500      * specified rounding mode is applied.
1501      *
1502      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1503      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1504      * @param  roundingMode rounding mode to apply.
1505      * @return {@code this / divisor}
1506      * @throws ArithmeticException if {@code divisor} is zero,
1507      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1508      *         the specified scale is insufficient to represent the result
1509      *         of the division exactly.
1510      * @since 1.5
1511      */
1512     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1513         return divide(divisor, scale, roundingMode.oldMode);


1571      * expansion) an {@code ArithmeticException} is thrown.
1572      *
1573      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1574      * @throws ArithmeticException if the exact quotient does not have a
1575      *         terminating decimal expansion
1576      * @return {@code this / divisor}
1577      * @since 1.5
1578      * @author Joseph D. Darcy
1579      */
1580     public BigDecimal divide(BigDecimal divisor) {
1581         /*
1582          * Handle zero cases first.
1583          */
1584         if (divisor.signum() == 0) {   // x/0
1585             if (this.signum() == 0)    // 0/0
1586                 throw new ArithmeticException("Division undefined");  // NaN
1587             throw new ArithmeticException("Division by zero");
1588         }
1589 
1590         // Calculate preferred scale
1591         int preferredScale = saturateLong((long)this.scale - divisor.scale);

1592         if (this.signum() == 0)        // 0/y
1593             return (preferredScale >= 0 &&
1594                     preferredScale < ZERO_SCALED_BY.length) ?
1595                 ZERO_SCALED_BY[preferredScale] :
1596                 BigDecimal.valueOf(0, preferredScale);
1597         else {
1598             this.inflate();
1599             divisor.inflate();
1600             /*
1601              * If the quotient this/divisor has a terminating decimal
1602              * expansion, the expansion can have no more than
1603              * (a.precision() + ceil(10*b.precision)/3) digits.
1604              * Therefore, create a MathContext object with this
1605              * precision and do a divide with the UNNECESSARY rounding
1606              * mode.
1607              */
1608             MathContext mc = new MathContext( (int)Math.min(this.precision() +
1609                                                             (long)Math.ceil(10.0*divisor.precision()/3.0),
1610                                                             Integer.MAX_VALUE),
1611                                               RoundingMode.UNNECESSARY);
1612             BigDecimal quotient;
1613             try {
1614                 quotient = this.divide(divisor, mc);
1615             } catch (ArithmeticException e) {
1616                 throw new ArithmeticException("Non-terminating decimal expansion; " +
1617                                               "no exact representable decimal result.");
1618             }
1619 
1620             int quotientScale = quotient.scale();
1621 
1622             // divide(BigDecimal, mc) tries to adjust the quotient to
1623             // the desired one by removing trailing zeros; since the
1624             // exact divide method does not have an explicit digit
1625             // limit, we can add zeros too.
1626 
1627             if (preferredScale > quotientScale)
1628                 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1629 
1630             return quotient;
1631         }
1632     }
1633 
1634     /**
1635      * Returns a {@code BigDecimal} whose value is {@code (this /
1636      * divisor)}, with rounding according to the context settings.
1637      *
1638      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1639      * @param  mc the context to use.
1640      * @return {@code this / divisor}, rounded as necessary.
1641      * @throws ArithmeticException if the result is inexact but the
1642      *         rounding mode is {@code UNNECESSARY} or
1643      *         {@code mc.precision == 0} and the quotient has a
1644      *         non-terminating decimal expansion.
1645      * @since  1.5
1646      */


1652         BigDecimal dividend = this;
1653         long preferredScale = (long)dividend.scale - divisor.scale;
1654         // Now calculate the answer.  We use the existing
1655         // divide-and-round method, but as this rounds to scale we have
1656         // to normalize the values here to achieve the desired result.
1657         // For x/y we first handle y=0 and x=0, and then normalize x and
1658         // y to give x' and y' with the following constraints:
1659         //   (a) 0.1 <= x' < 1
1660         //   (b)  x' <= y' < 10*x'
1661         // Dividing x'/y' with the required scale set to mc.precision then
1662         // will give a result in the range 0.1 to 1 rounded to exactly
1663         // the right number of digits (except in the case of a result of
1664         // 1.000... which can arise when x=y, or when rounding overflows
1665         // The 1.000... case will reduce properly to 1.
1666         if (divisor.signum() == 0) {      // x/0
1667             if (dividend.signum() == 0)    // 0/0
1668                 throw new ArithmeticException("Division undefined");  // NaN
1669             throw new ArithmeticException("Division by zero");
1670         }
1671         if (dividend.signum() == 0)        // 0/y
1672             return new BigDecimal(BigInteger.ZERO, 0,
1673                                   saturateLong(preferredScale), 1);
1674 
1675         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
1676         int xscale = dividend.precision();
1677         int yscale = divisor.precision();
1678         dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
1679                                   xscale, xscale);
1680         divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
1681                                  yscale, yscale);
1682         if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
1683             yscale = divisor.scale -= 1;            // [that is, divisor *= 10]
1684 
1685         // In order to find out whether the divide generates the exact result,
1686         // we avoid calling the above divide method. 'quotient' holds the
1687         // return BigDecimal object whose scale will be set to 'scl'.
1688         BigDecimal quotient;
1689         int scl = checkScale(preferredScale + yscale - xscale + mcp);
1690         if (checkScale((long)mcp + yscale) > xscale)
1691             dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
1692         else
1693             divisor = divisor.setScale(checkScale((long)xscale - mcp),
1694                                        ROUND_UNNECESSARY);
1695         quotient = divideAndRound(dividend.intCompact, dividend.intVal,
1696                                   divisor.intCompact, divisor.intVal,
1697                                   scl, mc.roundingMode.oldMode,
1698                                   checkScale(preferredScale));
1699         // doRound, here, only affects 1000000000 case.
1700         quotient = doRound(quotient, mc);
1701 
1702         return quotient;
1703     }
1704 
1705     /**
1706      * Returns a {@code BigDecimal} whose value is the integer part
1707      * of the quotient {@code (this / divisor)} rounded down.  The
1708      * preferred scale of the result is {@code (this.scale() -
1709      * divisor.scale())}.
1710      *
1711      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1712      * @return The integer part of {@code this / divisor}.
1713      * @throws ArithmeticException if {@code divisor==0}
1714      * @since  1.5
1715      */
1716     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1717         // Calculate preferred scale
1718         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1719         if (this.compareMagnitude(divisor) < 0) {
1720             // much faster when this << divisor
1721             return BigDecimal.valueOf(0, preferredScale);
1722         }
1723 
1724         if(this.signum() == 0 && divisor.signum() != 0)
1725             return this.setScale(preferredScale, ROUND_UNNECESSARY);
1726 
1727         // Perform a divide with enough digits to round to a correct
1728         // integer value; then remove any fractional digits
1729 
1730         int maxDigits = (int)Math.min(this.precision() +
1731                                       (long)Math.ceil(10.0*divisor.precision()/3.0) +
1732                                       Math.abs((long)this.scale() - divisor.scale()) + 2,
1733                                       Integer.MAX_VALUE);
1734         BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1735                                                                    RoundingMode.DOWN));
1736         if (quotient.scale > 0) {
1737             quotient = quotient.setScale(0, RoundingMode.DOWN);
1738             quotient.stripZerosToMatchScale(preferredScale);
1739         }
1740 
1741         if (quotient.scale < preferredScale) {
1742             // pad with zeros if necessary
1743             quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1744         }

1745         return quotient;
1746     }
1747 
1748     /**
1749      * Returns a {@code BigDecimal} whose value is the integer part
1750      * of {@code (this / divisor)}.  Since the integer part of the
1751      * exact quotient does not depend on the rounding mode, the
1752      * rounding mode does not affect the values returned by this
1753      * method.  The preferred scale of the result is
1754      * {@code (this.scale() - divisor.scale())}.  An
1755      * {@code ArithmeticException} is thrown if the integer part of
1756      * the exact quotient needs more than {@code mc.precision}
1757      * digits.
1758      *
1759      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1760      * @param  mc the context to use.
1761      * @return The integer part of {@code this / divisor}.
1762      * @throws ArithmeticException if {@code divisor==0}
1763      * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1764      *         requires a precision of more than {@code mc.precision} digits.
1765      * @since  1.5
1766      * @author Joseph D. Darcy
1767      */
1768     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1769         if (mc.precision == 0 ||                        // exact result
1770             (this.compareMagnitude(divisor) < 0) )      // zero result
1771             return divideToIntegralValue(divisor);
1772 
1773         // Calculate preferred scale
1774         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1775 
1776         /*
1777          * Perform a normal divide to mc.precision digits.  If the
1778          * remainder has absolute value less than the divisor, the
1779          * integer portion of the quotient fits into mc.precision
1780          * digits.  Next, remove any fractional digits from the
1781          * quotient and adjust the scale to the preferred value.
1782          */
1783         BigDecimal result = this.
1784             divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1785 
1786         if (result.scale() < 0) {
1787             /*
1788              * Result is an integer. See if quotient represents the
1789              * full integer portion of the exact quotient; if it does,
1790              * the computed remainder will be less than the divisor.
1791              */
1792             BigDecimal product = result.multiply(divisor);
1793             // If the quotient is the full integer value,
1794             // |dividend-product| < |divisor|.
1795             if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1796                 throw new ArithmeticException("Division impossible");
1797             }
1798         } else if (result.scale() > 0) {
1799             /*
1800              * Integer portion of quotient will fit into precision
1801              * digits; recompute quotient to scale 0 to avoid double
1802              * rounding and then try to adjust, if necessary.
1803              */
1804             result = result.setScale(0, RoundingMode.DOWN);
1805         }
1806         // else result.scale() == 0;
1807 
1808         int precisionDiff;
1809         if ((preferredScale > result.scale()) &&
1810             (precisionDiff = mc.precision - result.precision()) > 0) {
1811             return result.setScale(result.scale() +
1812                                    Math.min(precisionDiff, preferredScale - result.scale) );
1813         } else {
1814             result.stripZerosToMatchScale(preferredScale);
1815             return result;
1816         }
1817     }
1818 
1819     /**
1820      * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1821      *
1822      * <p>The remainder is given by
1823      * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1824      * Note that this is not the modulo operation (the result can be
1825      * negative).
1826      *
1827      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1828      * @return {@code this % divisor}.
1829      * @throws ArithmeticException if {@code divisor==0}
1830      * @since  1.5
1831      */
1832     public BigDecimal remainder(BigDecimal divisor) {
1833         BigDecimal divrem[] = this.divideAndRemainder(divisor);
1834         return divrem[1];
1835     }


1937      * unlimited precision.
1938      *
1939      * <p>The parameter {@code n} must be in the range 0 through
1940      * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
1941      * #ONE}.
1942      *
1943      * Note that future releases may expand the allowable exponent
1944      * range of this method.
1945      *
1946      * @param  n power to raise this {@code BigDecimal} to.
1947      * @return <tt>this<sup>n</sup></tt>
1948      * @throws ArithmeticException if {@code n} is out of range.
1949      * @since  1.5
1950      */
1951     public BigDecimal pow(int n) {
1952         if (n < 0 || n > 999999999)
1953             throw new ArithmeticException("Invalid operation");
1954         // No need to calculate pow(n) if result will over/underflow.
1955         // Don't attempt to support "supernormal" numbers.
1956         int newScale = checkScale((long)scale * n);
1957         this.inflate();
1958         return new BigDecimal(intVal.pow(n), newScale);
1959     }
1960 
1961 
1962     /**
1963      * Returns a {@code BigDecimal} whose value is
1964      * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
1965      * the core algorithm defined in ANSI standard X3.274-1996 with
1966      * rounding according to the context settings.  In general, the
1967      * returned numerical value is within two ulps of the exact
1968      * numerical value for the chosen precision.  Note that future
1969      * releases may use a different algorithm with a decreased
1970      * allowable error bound and increased allowable exponent range.
1971      *
1972      * <p>The X3.274-1996 algorithm is:
1973      *
1974      * <ul>
1975      * <li> An {@code ArithmeticException} exception is thrown if
1976      *  <ul>
1977      *    <li>{@code abs(n) > 999999999}
1978      *    <li>{@code mc.precision == 0} and {@code n < 0}


1999      *   is then rounded to the destination precision.
2000      *   </ul>
2001      * </ul>
2002      *
2003      * @param  n power to raise this {@code BigDecimal} to.
2004      * @param  mc the context to use.
2005      * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
2006      *         algorithm
2007      * @throws ArithmeticException if the result is inexact but the
2008      *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
2009      *         of range.
2010      * @since  1.5
2011      */
2012     public BigDecimal pow(int n, MathContext mc) {
2013         if (mc.precision == 0)
2014             return pow(n);
2015         if (n < -999999999 || n > 999999999)
2016             throw new ArithmeticException("Invalid operation");
2017         if (n == 0)
2018             return ONE;                      // x**0 == 1 in X3.274
2019         this.inflate();
2020         BigDecimal lhs = this;
2021         MathContext workmc = mc;           // working settings
2022         int mag = Math.abs(n);               // magnitude of n
2023         if (mc.precision > 0) {
2024 
2025             int elength = longDigitLength(mag); // length of n in digits
2026             if (elength > mc.precision)        // X3.274 rule
2027                 throw new ArithmeticException("Invalid operation");
2028             workmc = new MathContext(mc.precision + elength + 1,
2029                                       mc.roundingMode);
2030         }
2031         // ready to carry out power calculation...
2032         BigDecimal acc = ONE;           // accumulator
2033         boolean seenbit = false;        // set once we've seen a 1-bit
2034         for (int i=1;;i++) {            // for each bit [top bit ignored]
2035             mag += mag;                 // shift left 1 bit
2036             if (mag < 0) {              // top bit is set
2037                 seenbit = true;         // OK, we're off
2038                 acc = acc.multiply(lhs, workmc); // acc=acc*x
2039             }
2040             if (i == 31)
2041                 break;                  // that was the last bit
2042             if (seenbit)
2043                 acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
2044                 // else (!seenbit) no point in squaring ONE
2045         }
2046         // if negative n, calculate the reciprocal using working precision
2047         if (n<0)                          // [hence mc.precision>0]
2048             acc=ONE.divide(acc, workmc);
2049         // round to final precision and strip zeros
2050         return doRound(acc, mc);
2051     }
2052 
2053     /**
2054      * Returns a {@code BigDecimal} whose value is the absolute value
2055      * of this {@code BigDecimal}, and whose scale is
2056      * {@code this.scale()}.
2057      *
2058      * @return {@code abs(this)}
2059      */
2060     public BigDecimal abs() {
2061         return (signum() < 0 ? negate() : this);
2062     }
2063 
2064     /**
2065      * Returns a {@code BigDecimal} whose value is the absolute value
2066      * of this {@code BigDecimal}, with rounding according to the
2067      * context settings.
2068      *
2069      * @param mc the context to use.
2070      * @return {@code abs(this)}, rounded as necessary.
2071      * @throws ArithmeticException if the result is inexact but the
2072      *         rounding mode is {@code UNNECESSARY}.
2073      * @since 1.5
2074      */
2075     public BigDecimal abs(MathContext mc) {
2076         return (signum() < 0 ? negate(mc) : plus(mc));
2077     }
2078 
2079     /**
2080      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2081      * and whose scale is {@code this.scale()}.
2082      *
2083      * @return {@code -this}.
2084      */
2085     public BigDecimal negate() {
2086         BigDecimal result;
2087         if (intCompact != INFLATED)
2088             result = BigDecimal.valueOf(-intCompact, scale);
2089         else {
2090             result = new BigDecimal(intVal.negate(), scale);
2091             result.precision = precision;
2092         }
2093         return result;
2094     }
2095 
2096     /**
2097      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2098      * with rounding according to the context settings.
2099      *
2100      * @param mc the context to use.
2101      * @return {@code -this}, rounded as necessary.
2102      * @throws ArithmeticException if the result is inexact but the
2103      *         rounding mode is {@code UNNECESSARY}.
2104      * @since  1.5
2105      */
2106     public BigDecimal negate(MathContext mc) {
2107         return negate().plus(mc);
2108     }
2109 
2110     /**
2111      * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2112      * scale is {@code this.scale()}.
2113      *


2169     public int scale() {
2170         return scale;
2171     }
2172 
2173     /**
2174      * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2175      * precision is the number of digits in the unscaled value.)
2176      *
2177      * <p>The precision of a zero value is 1.
2178      *
2179      * @return the precision of this {@code BigDecimal}.
2180      * @since  1.5
2181      */
2182     public int precision() {
2183         int result = precision;
2184         if (result == 0) {
2185             long s = intCompact;
2186             if (s != INFLATED)
2187                 result = longDigitLength(s);
2188             else
2189                 result = bigDigitLength(inflate());
2190             precision = result;
2191         }
2192         return result;
2193     }
2194 
2195 
2196     /**
2197      * Returns a {@code BigInteger} whose value is the <i>unscaled
2198      * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
2199      * 10<sup>this.scale()</sup>)</tt>.)
2200      *
2201      * @return the unscaled value of this {@code BigDecimal}.
2202      * @since  1.2
2203      */
2204     public BigInteger unscaledValue() {
2205         return this.inflate();
2206     }
2207 
2208     // Rounding Modes
2209 
2210     /**
2211      * Rounding mode to round away from zero.  Always increments the
2212      * digit prior to a nonzero discarded fraction.  Note that this rounding
2213      * mode never decreases the magnitude of the calculated value.
2214      */
2215     public final static int ROUND_UP =           0;
2216 
2217     /**
2218      * Rounding mode to round towards zero.  Never increments the digit
2219      * prior to a discarded fraction (i.e., truncates).  Note that this
2220      * rounding mode never increases the magnitude of the calculated value.
2221      */
2222     public final static int ROUND_DOWN =         1;
2223 
2224     /**
2225      * Rounding mode to round towards positive infinity.  If the


2366      *         rounding.
2367      * @throws IllegalArgumentException if {@code roundingMode} does not
2368      *         represent a valid rounding mode.
2369      * @see    #ROUND_UP
2370      * @see    #ROUND_DOWN
2371      * @see    #ROUND_CEILING
2372      * @see    #ROUND_FLOOR
2373      * @see    #ROUND_HALF_UP
2374      * @see    #ROUND_HALF_DOWN
2375      * @see    #ROUND_HALF_EVEN
2376      * @see    #ROUND_UNNECESSARY
2377      */
2378     public BigDecimal setScale(int newScale, int roundingMode) {
2379         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2380             throw new IllegalArgumentException("Invalid rounding mode");
2381 
2382         int oldScale = this.scale;
2383         if (newScale == oldScale)        // easy case
2384             return this;
2385         if (this.signum() == 0)            // zero can have any scale
2386             return BigDecimal.valueOf(0, newScale);
2387 
2388         long rs = this.intCompact;
2389         if (newScale > oldScale) {
2390             int raise = checkScale((long)newScale - oldScale);
2391             BigInteger rb = null;
2392             if (rs == INFLATED ||
2393                 (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
2394                 rb = bigMultiplyPowerTen(raise);
2395             return new BigDecimal(rb, rs, newScale,
2396                                   (precision > 0) ? precision + raise : 0);














2397         } else {
2398             // newScale < oldScale -- drop some digits
2399             // Can't predict the precision due to the effect of rounding.
2400             int drop = checkScale((long)oldScale - newScale);
2401             if (drop < LONG_TEN_POWERS_TABLE.length)
2402                 return divideAndRound(rs, this.intVal,
2403                                       LONG_TEN_POWERS_TABLE[drop], null,
2404                                       newScale, roundingMode, newScale);
2405             else
2406                 return divideAndRound(rs, this.intVal,
2407                                       INFLATED, bigTenToThe(drop),
2408                                       newScale, roundingMode, newScale);
2409         }
2410     }
2411 
2412     /**
2413      * Returns a {@code BigDecimal} whose scale is the specified
2414      * value, and whose value is numerically equal to this
2415      * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2416      * if this is not possible.
2417      *
2418      * <p>This call is typically used to increase the scale, in which
2419      * case it is guaranteed that there exists a {@code BigDecimal}
2420      * of the specified scale and the correct value.  The call can
2421      * also be used to reduce the scale if the caller knows that the
2422      * {@code BigDecimal} has sufficiently many zeros at the end of
2423      * its fractional part (i.e., factors of ten in its integer value)
2424      * to allow for the rescaling without changing its value.
2425      *
2426      * <p>This method returns the same result as the two-argument
2427      * versions of {@code setScale}, but saves the caller the trouble
2428      * of specifying a rounding mode in cases where it is irrelevant.


2507      */
2508     public BigDecimal scaleByPowerOfTen(int n) {
2509         return new BigDecimal(intVal, intCompact,
2510                               checkScale((long)scale - n), precision);
2511     }
2512 
2513     /**
2514      * Returns a {@code BigDecimal} which is numerically equal to
2515      * this one but with any trailing zeros removed from the
2516      * representation.  For example, stripping the trailing zeros from
2517      * the {@code BigDecimal} value {@code 600.0}, which has
2518      * [{@code BigInteger}, {@code scale}] components equals to
2519      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2520      * {@code scale}] components equals to [6, -2]
2521      *
2522      * @return a numerically equal {@code BigDecimal} with any
2523      * trailing zeros removed.
2524      * @since 1.5
2525      */
2526     public BigDecimal stripTrailingZeros() {
2527         this.inflate();
2528         BigDecimal result = new BigDecimal(intVal, scale);
2529         result.stripZerosToMatchScale(Long.MIN_VALUE);
2530         return result;

2531     }
2532 
2533     // Comparison Operations
2534 
2535     /**
2536      * Compares this {@code BigDecimal} with the specified
2537      * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2538      * equal in value but have a different scale (like 2.0 and 2.00)
2539      * are considered equal by this method.  This method is provided
2540      * in preference to individual methods for each of the six boolean
2541      * comparison operators ({@literal <}, ==,
2542      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2543      * suggested idiom for performing these comparisons is:
2544      * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2545      * &lt;<i>op</i>&gt; is one of the six comparison operators.
2546      *
2547      * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
2548      *         to be compared.
2549      * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2550      *          less than, equal to, or greater than {@code val}.


2630      * @see    #hashCode
2631      */
2632     @Override
2633     public boolean equals(Object x) {
2634         if (!(x instanceof BigDecimal))
2635             return false;
2636         BigDecimal xDec = (BigDecimal) x;
2637         if (x == this)
2638             return true;
2639         if (scale != xDec.scale)
2640             return false;
2641         long s = this.intCompact;
2642         long xs = xDec.intCompact;
2643         if (s != INFLATED) {
2644             if (xs == INFLATED)
2645                 xs = compactValFor(xDec.intVal);
2646             return xs == s;
2647         } else if (xs != INFLATED)
2648             return xs == compactValFor(this.intVal);
2649 
2650         return this.inflate().equals(xDec.inflate());
2651     }
2652 
2653     /**
2654      * Returns the minimum of this {@code BigDecimal} and
2655      * {@code val}.
2656      *
2657      * @param  val value with which the minimum is to be computed.
2658      * @return the {@code BigDecimal} whose value is the lesser of this
2659      *         {@code BigDecimal} and {@code val}.  If they are equal,
2660      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2661      *         method, {@code this} is returned.
2662      * @see    #compareTo(java.math.BigDecimal)
2663      */
2664     public BigDecimal min(BigDecimal val) {
2665         return (compareTo(val) <= 0 ? this : val);
2666     }
2667 
2668     /**
2669      * Returns the maximum of this {@code BigDecimal} and {@code val}.
2670      *


2855      *
2856      * Note that if the result of this method is passed to the
2857      * {@linkplain #BigDecimal(String) string constructor}, only the
2858      * numerical value of this {@code BigDecimal} will necessarily be
2859      * recovered; the representation of the new {@code BigDecimal}
2860      * may have a different scale.  In particular, if this
2861      * {@code BigDecimal} has a negative scale, the string resulting
2862      * from this method will have a scale of zero when processed by
2863      * the string constructor.
2864      *
2865      * (This method behaves analogously to the {@code toString}
2866      * method in 1.4 and earlier releases.)
2867      *
2868      * @return a string representation of this {@code BigDecimal}
2869      * without an exponent field.
2870      * @since 1.5
2871      * @see #toString()
2872      * @see #toEngineeringString()
2873      */
2874     public String toPlainString() {
2875         BigDecimal bd = this;
2876         if (bd.scale < 0)
2877             bd = bd.setScale(0);
2878         bd.inflate();
2879         if (bd.scale == 0)      // No decimal point
2880             return bd.intVal.toString();
2881         return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);

























2882     }
2883 
2884     /* Returns a digit.digit string */
2885     private String getValueString(int signum, String intString, int scale) {
2886         /* Insert decimal point */
2887         StringBuilder buf;
2888         int insertionPoint = intString.length() - scale;
2889         if (insertionPoint == 0) {  /* Point goes right before intVal */
2890             return (signum<0 ? "-0." : "0.") + intString;
2891         } else if (insertionPoint > 0) { /* Point goes inside intVal */
2892             buf = new StringBuilder(intString);
2893             buf.insert(insertionPoint, '.');
2894             if (signum < 0)
2895                 buf.insert(0, '-');
2896         } else { /* We must insert zeros between point and intVal */
2897             buf = new StringBuilder(3-insertionPoint + intString.length());
2898             buf.append(signum<0 ? "-0." : "0.");
2899             for (int i=0; i<-insertionPoint; i++)
2900                 buf.append('0');
2901             buf.append(intString);


2905 
2906     /**
2907      * Converts this {@code BigDecimal} to a {@code BigInteger}.
2908      * This conversion is analogous to the
2909      * <i>narrowing primitive conversion</i> from {@code double} to
2910      * {@code long} as defined in section 5.1.3 of
2911      * <cite>The Java&trade; Language Specification</cite>:
2912      * any fractional part of this
2913      * {@code BigDecimal} will be discarded.  Note that this
2914      * conversion can lose information about the precision of the
2915      * {@code BigDecimal} value.
2916      * <p>
2917      * To have an exception thrown if the conversion is inexact (in
2918      * other words if a nonzero fractional part is discarded), use the
2919      * {@link #toBigIntegerExact()} method.
2920      *
2921      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2922      */
2923     public BigInteger toBigInteger() {
2924         // force to an integer, quietly
2925         return this.setScale(0, ROUND_DOWN).inflate();
2926     }
2927 
2928     /**
2929      * Converts this {@code BigDecimal} to a {@code BigInteger},
2930      * checking for lost information.  An exception is thrown if this
2931      * {@code BigDecimal} has a nonzero fractional part.
2932      *
2933      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2934      * @throws ArithmeticException if {@code this} has a nonzero
2935      *         fractional part.
2936      * @since  1.5
2937      */
2938     public BigInteger toBigIntegerExact() {
2939         // round to an integer, with Exception if decimal part non-0
2940         return this.setScale(0, ROUND_UNNECESSARY).inflate();
2941     }
2942 
2943     /**
2944      * Converts this {@code BigDecimal} to a {@code long}.
2945      * This conversion is analogous to the
2946      * <i>narrowing primitive conversion</i> from {@code double} to
2947      * {@code short} as defined in section 5.1.3 of
2948      * <cite>The Java&trade; Language Specification</cite>:
2949      * any fractional part of this
2950      * {@code BigDecimal} will be discarded, and if the resulting
2951      * "{@code BigInteger}" is too big to fit in a
2952      * {@code long}, only the low-order 64 bits are returned.
2953      * Note that this conversion can lose information about the
2954      * overall magnitude and precision of this {@code BigDecimal} value as well
2955      * as return a result with the opposite sign.
2956      *
2957      * @return this {@code BigDecimal} converted to a {@code long}.
2958      */
2959     public long longValue(){
2960         return (intCompact != INFLATED && scale == 0) ?


2973      * @throws ArithmeticException if {@code this} has a nonzero
2974      *         fractional part, or will not fit in a {@code long}.
2975      * @since  1.5
2976      */
2977     public long longValueExact() {
2978         if (intCompact != INFLATED && scale == 0)
2979             return intCompact;
2980         // If more than 19 digits in integer part it cannot possibly fit
2981         if ((precision() - scale) > 19) // [OK for negative scale too]
2982             throw new java.lang.ArithmeticException("Overflow");
2983         // Fastpath zero and < 1.0 numbers (the latter can be very slow
2984         // to round if very small)
2985         if (this.signum() == 0)
2986             return 0;
2987         if ((this.precision() - this.scale) <= 0)
2988             throw new ArithmeticException("Rounding necessary");
2989         // round to an integer, with Exception if decimal part non-0
2990         BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
2991         if (num.precision() >= 19) // need to check carefully
2992             LongOverflow.check(num);
2993         return num.inflate().longValue();
2994     }
2995 
2996     private static class LongOverflow {
2997         /** BigInteger equal to Long.MIN_VALUE. */
2998         private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
2999 
3000         /** BigInteger equal to Long.MAX_VALUE. */
3001         private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3002 
3003         public static void check(BigDecimal num) {
3004             num.inflate();
3005             if ((num.intVal.compareTo(LONGMIN) < 0) ||
3006                 (num.intVal.compareTo(LONGMAX) > 0))
3007                 throw new java.lang.ArithmeticException("Overflow");
3008         }
3009     }
3010 
3011     /**
3012      * Converts this {@code BigDecimal} to an {@code int}.
3013      * This conversion is analogous to the
3014      * <i>narrowing primitive conversion</i> from {@code double} to
3015      * {@code short} as defined in section 5.1.3 of
3016      * <cite>The Java&trade; Language Specification</cite>:
3017      * any fractional part of this
3018      * {@code BigDecimal} will be discarded, and if the resulting
3019      * "{@code BigInteger}" is too big to fit in an
3020      * {@code int}, only the low-order 32 bits are returned.
3021      * Note that this conversion can lose information about the
3022      * overall magnitude and precision of this {@code BigDecimal}
3023      * value as well as return a result with the opposite sign.
3024      *
3025      * @return this {@code BigDecimal} converted to an {@code int}.
3026      */


3090        return (byte)num;
3091     }
3092 
3093     /**
3094      * Converts this {@code BigDecimal} to a {@code float}.
3095      * This conversion is similar to the
3096      * <i>narrowing primitive conversion</i> from {@code double} to
3097      * {@code float} as defined in section 5.1.3 of
3098      * <cite>The Java&trade; Language Specification</cite>:
3099      * if this {@code BigDecimal} has too great a
3100      * magnitude to represent as a {@code float}, it will be
3101      * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3102      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3103      * the return value is finite, this conversion can lose
3104      * information about the precision of the {@code BigDecimal}
3105      * value.
3106      *
3107      * @return this {@code BigDecimal} converted to a {@code float}.
3108      */
3109     public float floatValue(){
3110         if (scale == 0 && intCompact != INFLATED)

3111                 return (float)intCompact;



















3112         // Somewhat inefficient, but guaranteed to work.
3113         return Float.parseFloat(this.toString());
3114     }
3115 
3116     /**
3117      * Converts this {@code BigDecimal} to a {@code double}.
3118      * This conversion is similar to the
3119      * <i>narrowing primitive conversion</i> from {@code double} to
3120      * {@code float} as defined in section 5.1.3 of
3121      * <cite>The Java&trade; Language Specification</cite>:
3122      * if this {@code BigDecimal} has too great a
3123      * magnitude represent as a {@code double}, it will be
3124      * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3125      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3126      * the return value is finite, this conversion can lose
3127      * information about the precision of the {@code BigDecimal}
3128      * value.
3129      *
3130      * @return this {@code BigDecimal} converted to a {@code double}.
3131      */
3132     public double doubleValue(){
3133         if (scale == 0 && intCompact != INFLATED)

3134             return (double)intCompact;



















3135         // Somewhat inefficient, but guaranteed to work.
3136         return Double.parseDouble(this.toString());
3137     }
3138 
3139     /**




















3140      * Returns the size of an ulp, a unit in the last place, of this
3141      * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3142      * value is the positive distance between this value and the
3143      * {@code BigDecimal} value next larger in magnitude with the
3144      * same number of digits.  An ulp of a zero value is numerically
3145      * equal to 1 with the scale of {@code this}.  The result is
3146      * stored with the same scale as {@code this} so the result
3147      * for zero and nonzero values is equal to {@code [1,
3148      * this.scale()]}.
3149      *
3150      * @return the size of an ulp of {@code this}
3151      * @since 1.5
3152      */
3153     public BigDecimal ulp() {
3154         return BigDecimal.valueOf(1, this.scale());
3155     }
3156 
3157 
3158     // Private class to build a string representation for BigDecimal object.
3159     // "StringBuilderHelper" is constructed as a thread local variable so it is
3160     // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3161     // representation of BigDecimal. The cmpCharArray holds all the characters for
3162     // the compact representation of BigDecimal (except for '-' sign' if it is
3163     // negative) if its intCompact field is not INFLATED. It is shared by all
3164     // calls to toString() and its variants in that particular thread.
3165     static class StringBuilderHelper {
3166         final StringBuilder sb;    // Placeholder for BigDecimal string
3167         final char[] cmpCharArray; // character array to place the intCompact
3168 
3169         StringBuilderHelper() {
3170             sb = new StringBuilder();
3171             // All non negative longs can be made to fit into 19 character array.
3172             cmpCharArray = new char[19];
3173         }
3174 
3175         // Accessors.
3176         StringBuilder getStringBuilder() {
3177             sb.setLength(0);


3251             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3252             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3253             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3254         };
3255     }
3256 
3257     /**
3258      * Lay out this {@code BigDecimal} into a {@code char[]} array.
3259      * The Java 1.2 equivalent to this was called {@code getValueString}.
3260      *
3261      * @param  sci {@code true} for Scientific exponential notation;
3262      *          {@code false} for Engineering
3263      * @return string with canonical string representation of this
3264      *         {@code BigDecimal}
3265      */
3266     private String layoutChars(boolean sci) {
3267         if (scale == 0)                      // zero scale is trivial
3268             return (intCompact != INFLATED) ?
3269                 Long.toString(intCompact):
3270                 intVal.toString();









3271 
3272         StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
3273         char[] coeff;
3274         int offset;  // offset is the starting index for coeff array
3275         // Get the significand as an absolute value
3276         if (intCompact != INFLATED) {
3277             offset = sbHelper.putIntCompact(Math.abs(intCompact));
3278             coeff  = sbHelper.getCompactCharArray();
3279         } else {
3280             offset = 0;
3281             coeff  = intVal.abs().toString().toCharArray();
3282         }
3283 
3284         // Construct a buffer, with sufficient capacity for all cases.
3285         // If E-notation is needed, length will be: +1 if negative, +1
3286         // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3287         // Otherwise it could have +1 if negative, plus leading "0.00000"
3288         StringBuilder buf = sbHelper.getStringBuilder();
3289         if (signum() < 0)             // prefix '-' if negative
3290             buf.append('-');


3360      * @param  n the power of ten to be returned (>=0)
3361      * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3362      */
3363     private static BigInteger bigTenToThe(int n) {
3364         if (n < 0)
3365             return BigInteger.ZERO;
3366 
3367         if (n < BIG_TEN_POWERS_TABLE_MAX) {
3368             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3369             if (n < pows.length)
3370                 return pows[n];
3371             else
3372                 return expandBigIntegerTenPowers(n);
3373         }
3374         // BigInteger.pow is slow, so make 10**n by constructing a
3375         // BigInteger from a character string (still not very fast)
3376         char tenpow[] = new char[n + 1];
3377         tenpow[0] = '1';
3378         for (int i = 1; i <= n; i++)
3379             tenpow[i] = '0';
3380         return new BigInteger(tenpow);
3381     }
3382 
3383     /**
3384      * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3385      *
3386      * @param n the power of ten to be returned (>=0)
3387      * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3388      *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
3389      *         expanded to the size greater than n.
3390      */
3391     private static BigInteger expandBigIntegerTenPowers(int n) {
3392         synchronized(BigDecimal.class) {
3393             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3394             int curLen = pows.length;
3395             // The following comparison and the above synchronized statement is
3396             // to prevent multiple threads from expanding the same array.
3397             if (curLen <= n) {
3398                 int newLen = curLen << 1;
3399                 while (newLen <= n)
3400                     newLen <<= 1;


3416         10,                    // 1 / 10^1
3417         100,                   // 2 / 10^2
3418         1000,                  // 3 / 10^3
3419         10000,                 // 4 / 10^4
3420         100000,                // 5 / 10^5
3421         1000000,               // 6 / 10^6
3422         10000000,              // 7 / 10^7
3423         100000000,             // 8 / 10^8
3424         1000000000,            // 9 / 10^9
3425         10000000000L,          // 10 / 10^10
3426         100000000000L,         // 11 / 10^11
3427         1000000000000L,        // 12 / 10^12
3428         10000000000000L,       // 13 / 10^13
3429         100000000000000L,      // 14 / 10^14
3430         1000000000000000L,     // 15 / 10^15
3431         10000000000000000L,    // 16 / 10^16
3432         100000000000000000L,   // 17 / 10^17
3433         1000000000000000000L   // 18 / 10^18
3434     };
3435 
3436     private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
3437         BigInteger.valueOf(10),       BigInteger.valueOf(100),
3438         BigInteger.valueOf(1000),     BigInteger.valueOf(10000),
3439         BigInteger.valueOf(100000),   BigInteger.valueOf(1000000),
3440         BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),





3441         BigInteger.valueOf(1000000000),
3442         BigInteger.valueOf(10000000000L),
3443         BigInteger.valueOf(100000000000L),
3444         BigInteger.valueOf(1000000000000L),
3445         BigInteger.valueOf(10000000000000L),
3446         BigInteger.valueOf(100000000000000L),
3447         BigInteger.valueOf(1000000000000000L),
3448         BigInteger.valueOf(10000000000000000L),
3449         BigInteger.valueOf(100000000000000000L),
3450         BigInteger.valueOf(1000000000000000000L)
3451     };
3452 
3453     private static final int BIG_TEN_POWERS_TABLE_INITLEN =
3454         BIG_TEN_POWERS_TABLE.length;
3455     private static final int BIG_TEN_POWERS_TABLE_MAX =
3456         16 * BIG_TEN_POWERS_TABLE_INITLEN;
3457 
3458     private static final long THRESHOLDS_TABLE[] = {
3459         Long.MAX_VALUE,                     // 0
3460         Long.MAX_VALUE/10L,                 // 1


3485         if (val == 0 || n <= 0)
3486             return val;
3487         long[] tab = LONG_TEN_POWERS_TABLE;
3488         long[] bounds = THRESHOLDS_TABLE;
3489         if (n < tab.length && n < bounds.length) {
3490             long tenpower = tab[n];
3491             if (val == 1)
3492                 return tenpower;
3493             if (Math.abs(val) <= bounds[n])
3494                 return val * tenpower;
3495         }
3496         return INFLATED;
3497     }
3498 
3499     /**
3500      * Compute this * 10 ^ n.
3501      * Needed mainly to allow special casing to trap zero value
3502      */
3503     private BigInteger bigMultiplyPowerTen(int n) {
3504         if (n <= 0)
3505             return this.inflate();
3506 
3507         if (intCompact != INFLATED)
3508             return bigTenToThe(n).multiply(intCompact);
3509         else
3510             return intVal.multiply(bigTenToThe(n));
3511     }
3512 
3513     /**
3514      * Assign appropriate BigInteger to intVal field if intVal is
3515      * null, i.e. the compact representation is in use.
3516      */
3517     private BigInteger inflate() {
3518         if (intVal == null)
3519             intVal = BigInteger.valueOf(intCompact);

3520         return intVal;
3521     }
3522 
3523     /**
3524      * Match the scales of two {@code BigDecimal}s to align their
3525      * least significant digits.
3526      *
3527      * <p>If the scales of val[0] and val[1] differ, rescale
3528      * (non-destructively) the lower-scaled {@code BigDecimal} so
3529      * they match.  That is, the lower-scaled reference will be
3530      * replaced by a reference to a new object with the same scale as
3531      * the other {@code BigDecimal}.
3532      *
3533      * @param  val array of two elements referring to the two
3534      *         {@code BigDecimal}s to be aligned.
3535      */
3536     private static void matchScale(BigDecimal[] val) {
3537         if (val[0].scale == val[1].scale) {
3538             return;
3539         } else if (val[0].scale < val[1].scale) {
3540             val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3541         } else if (val[1].scale < val[0].scale) {
3542             val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3543         }
3544     }
3545 






















3546     /**
3547      * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3548      * deserialize it).
3549      *
3550      * @param s the stream being read.
3551      */
3552     private void readObject(java.io.ObjectInputStream s)
3553         throws java.io.IOException, ClassNotFoundException {
3554         // Read in all fields
3555         s.defaultReadObject();
3556         // validate possibly bad fields
3557         if (intVal == null) {
3558             String message = "BigDecimal: null intVal in stream";
3559             throw new java.io.StreamCorruptedException(message);
3560         // [all values of scale are now allowed]
3561         }
3562         intCompact = compactValFor(intVal);
3563     }
3564 
3565    /**
3566     * Serialize this {@code BigDecimal} to the stream in question
3567     *
3568     * @param s the stream to serialize to.
3569     */
3570    private void writeObject(java.io.ObjectOutputStream s)
3571        throws java.io.IOException {
3572        // Must inflate to maintain compatible serial form.
3573        this.inflate();
3574 
3575        // Write proper fields
3576        s.defaultWriteObject();
3577    }
3578 
3579 
3580     /**
3581      * Returns the length of the absolute value of a {@code long}, in decimal
3582      * digits.
3583      *
3584      * @param x the {@code long}
3585      * @return the length of the unscaled value, in deciaml digits.
3586      */
3587     private static int longDigitLength(long x) {
3588         /*
3589          * As described in "Bit Twiddling Hacks" by Sean Anderson,
3590          * (http://graphics.stanford.edu/~seander/bithacks.html)
3591          * integer log 10 of x is within 1 of
3592          * (1233/4096)* (1 + integer log 2 of x).
3593          * The fraction 1233/4096 approximates log10(2). So we first
3594          * do a version of log2 (a variant of Long class with
3595          * pre-checks and opposite directionality) and then scale and
3596          * check against powers table. This is a little simpler in
3597          * present context than the version in Hacker's Delight sec
3598          * 11-4.  Adding one to bit length allows comparing downward
3599          * from the LONG_TEN_POWERS_TABLE that we need anyway.
3600          */
3601         assert x != INFLATED;
3602         if (x < 0)
3603             x = -x;
3604         if (x < 10) // must screen for 0, might as well 10
3605             return 1;
3606         int n = 64; // not 63, to avoid needing to add 1 later
3607         int y = (int)(x >>> 32);
3608         if (y == 0) { n -= 32; y = (int)x; }
3609         if (y >>> 16 == 0) { n -= 16; y <<= 16; }
3610         if (y >>> 24 == 0) { n -=  8; y <<=  8; }
3611         if (y >>> 28 == 0) { n -=  4; y <<=  4; }
3612         if (y >>> 30 == 0) { n -=  2; y <<=  2; }
3613         int r = (((y >>> 31) + n) * 1233) >>> 12;
3614         long[] tab = LONG_TEN_POWERS_TABLE;
3615         // if r >= length, must have max possible digits for long
3616         return (r >= tab.length || x < tab[r])? r : r+1;
3617     }
3618 
3619     /**
3620      * Returns the length of the absolute value of a BigInteger, in
3621      * decimal digits.
3622      *
3623      * @param b the BigInteger
3624      * @return the length of the unscaled value, in decimal digits
3625      */
3626     private static int bigDigitLength(BigInteger b) {
3627         /*
3628          * Same idea as the long version, but we need a better
3629          * approximation of log10(2). Using 646456993/2^31
3630          * is accurate up to max possible reported bitLength.
3631          */
3632         if (b.signum == 0)
3633             return 1;
3634         int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3635         return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3636     }
3637 
3638 
3639     /**
3640      * Remove insignificant trailing zeros from this
3641      * {@code BigDecimal} until the preferred scale is reached or no
3642      * more zeros can be removed.  If the preferred scale is less than
3643      * Integer.MIN_VALUE, all the trailing zeros will be removed.
3644      *
3645      * {@code BigInteger} assistance could help, here?
3646      *
3647      * <p>WARNING: This method should only be called on new objects as
3648      * it mutates the value fields.
3649      *
3650      * @return this {@code BigDecimal} with a scale possibly reduced
3651      * to be closed to the preferred scale.
3652      */
3653     private BigDecimal stripZerosToMatchScale(long preferredScale) {
3654         this.inflate();
3655         BigInteger qr[];                // quotient-remainder pair
3656         while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
3657                 scale > preferredScale) {
3658             if (intVal.testBit(0))
3659                 break;                  // odd number cannot end in 0
3660             qr = intVal.divideAndRemainder(BigInteger.TEN);
3661             if (qr[1].signum() != 0)
3662                 break;                  // non-0 remainder
3663             intVal=qr[0];
3664             scale = checkScale((long)scale-1);  // could Overflow
3665             if (precision > 0)          // adjust precision if known
3666               precision--;
3667         }
3668         if (intVal != null)
3669             intCompact = compactValFor(intVal);
3670         return this;
3671     }
3672 
3673     /**
3674      * Check a scale for Underflow or Overflow.  If this BigDecimal is
3675      * nonzero, throw an exception if the scale is outof range. If this
3676      * is zero, saturate the scale to the extreme value of the right
3677      * sign if the scale is out of range.
3678      *
3679      * @param val The new scale.
3680      * @throws ArithmeticException (overflow or underflow) if the new
3681      *         scale is out of range.
3682      * @return validated scale as an int.
3683      */
3684     private int checkScale(long val) {
3685         int asInt = (int)val;
3686         if (asInt != val) {
3687             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3688             BigInteger b;
3689             if (intCompact != 0 &&
3690                 ((b = intVal) == null || b.signum() != 0))
3691                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3692         }
3693         return asInt;
3694     }
3695 
3696     /**
3697      * Round an operand; used only if digits &gt; 0.  Does not change
3698      * {@code this}; if rounding is needed a new {@code BigDecimal}
3699      * is created and returned.
3700      *
3701      * @param mc the context to use.
3702      * @throws ArithmeticException if the result is inexact but the
3703      *         rounding mode is {@code UNNECESSARY}.
3704      */
3705     private BigDecimal roundOp(MathContext mc) {
3706         BigDecimal rounded = doRound(this, mc);
3707         return rounded;
3708     }
3709 
3710     /** Round this BigDecimal according to the MathContext settings;
3711      *  used only if precision {@literal >} 0.
3712      *
3713      * <p>WARNING: This method should only be called on new objects as
3714      * it mutates the value fields.
3715      *
3716      * @param mc the context to use.
3717      * @throws ArithmeticException if the rounding mode is
3718      *         {@code RoundingMode.UNNECESSARY} and the
3719      *         {@code BigDecimal} operation would require rounding.
3720      */
3721     private void roundThis(MathContext mc) {
3722         BigDecimal rounded = doRound(this, mc);
3723         if (rounded == this)                 // wasn't rounded
3724             return;
3725         this.intVal     = rounded.intVal;
3726         this.intCompact = rounded.intCompact;
3727         this.scale      = rounded.scale;
3728         this.precision  = rounded.precision;
3729     }
3730 
3731     /**
3732      * Returns a {@code BigDecimal} rounded according to the
3733      * MathContext settings; used only if {@code mc.precision > 0}.
3734      * Does not change {@code this}; if rounding is needed a new
3735      * {@code BigDecimal} is created and returned.
3736      *
3737      * @param mc the context to use.
3738      * @return a {@code BigDecimal} rounded according to the MathContext
3739      *         settings.  May return this, if no rounding needed.
3740      * @throws ArithmeticException if the rounding mode is
3741      *         {@code RoundingMode.UNNECESSARY} and the
3742      *         result is inexact.
3743      */
3744     private static BigDecimal doRound(BigDecimal d, MathContext mc) {
3745         int mcp = mc.precision;
3746         int drop;
3747         // This might (rarely) iterate to cover the 999=>1000 case
3748         while ((drop = d.precision() - mcp) > 0) {
3749             int newScale = d.checkScale((long)d.scale - drop);
3750             int mode = mc.roundingMode.oldMode;
3751             if (drop < LONG_TEN_POWERS_TABLE.length)
3752                 d = divideAndRound(d.intCompact, d.intVal,
3753                                    LONG_TEN_POWERS_TABLE[drop], null,
3754                                    newScale, mode, newScale);
3755             else
3756                 d = divideAndRound(d.intCompact, d.intVal,
3757                                    INFLATED, bigTenToThe(drop),
3758                                    newScale, mode, newScale);
3759         }
3760         return d;
3761     }
3762 
3763     /**
3764      * Returns the compact value for given {@code BigInteger}, or
3765      * INFLATED if too big. Relies on internal representation of
3766      * {@code BigInteger}.
3767      */
3768     private static long compactValFor(BigInteger b) {
3769         int[] m = b.mag;
3770         int len = m.length;
3771         if (len == 0)
3772             return 0;
3773         int d = m[0];
3774         if (len > 2 || (len == 2 && d < 0))
3775             return INFLATED;
3776 
3777         long u = (len == 2)?
3778             (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3779             (((long)d)   & LONG_MASK);
3780         return (b.signum < 0)? -u : u;
3781     }
3782 
3783     private static int longCompareMagnitude(long x, long y) {


3835                 print("audit", this);
3836                 throw new AssertionError("precision mismatch");
3837             }
3838         } else {
3839             if (intVal != null) {
3840                 long val = intVal.longValue();
3841                 if (val != intCompact) {
3842                     print("audit", this);
3843                     throw new AssertionError("Inconsistent state, intCompact=" +
3844                                              intCompact + "\t intVal=" + val);
3845                 }
3846             }
3847             // Check precision
3848             if (precision > 0 && precision != longDigitLength(intCompact)) {
3849                 print("audit", this);
3850                 throw new AssertionError("precision mismatch");
3851             }
3852         }
3853         return this;
3854     }























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































3855 }


 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),


 363     /**
 364      * Translates a character array representation of a
 365      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 366      * same sequence of characters as the {@link #BigDecimal(String)}
 367      * constructor, while allowing a sub-array to be specified.
 368      *
 369      * <p>Note that if the sequence of characters is already available
 370      * within a character array, using this constructor is faster than
 371      * converting the {@code char} array to string and using the
 372      * {@code BigDecimal(String)} constructor .
 373      *
 374      * @param  in {@code char} array that is the source of characters.
 375      * @param  offset first character in the array to inspect.
 376      * @param  len number of characters to consider.
 377      * @throws NumberFormatException if {@code in} is not a valid
 378      *         representation of a {@code BigDecimal} or the defined subarray
 379      *         is not wholly within {@code in}.
 380      * @since  1.5
 381      */
 382     public BigDecimal(char[] in, int offset, int len) {
 383         this(in,offset,len,MathContext.UNLIMITED);
 384     }
 385 
 386     /**
 387      * Translates a character array representation of a
 388      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 389      * same sequence of characters as the {@link #BigDecimal(String)}
 390      * constructor, while allowing a sub-array to be specified and
 391      * with rounding according to the context settings.
 392      *
 393      * <p>Note that if the sequence of characters is already available
 394      * within a character array, using this constructor is faster than
 395      * converting the {@code char} array to string and using the
 396      * {@code BigDecimal(String)} constructor .
 397      *
 398      * @param  in {@code char} array that is the source of characters.
 399      * @param  offset first character in the array to inspect.
 400      * @param  len number of characters to consider..
 401      * @param  mc the context to use.
 402      * @throws ArithmeticException if the result is inexact but the
 403      *         rounding mode is {@code UNNECESSARY}.
 404      * @throws NumberFormatException if {@code in} is not a valid
 405      *         representation of a {@code BigDecimal} or the defined subarray
 406      *         is not wholly within {@code in}.
 407      * @since  1.5
 408      */
 409     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
 410         // protect against huge length.
 411         if (offset + len > in.length || offset < 0)
 412             throw new NumberFormatException("Bad offset or len arguments for char[] input.");
 413         // This is the primary string to BigDecimal constructor; all
 414         // incoming strings end up here; it uses explicit (inline)
 415         // parsing for speed and generates at most one intermediate
 416         // (temporary) object (a char[] array) for non-compact case.
 417 
 418         // Use locals for all fields values until completion
 419         int prec = 0;                 // record precision value
 420         int scl = 0;                  // record scale value
 421         long rs = 0;                  // the compact value in long
 422         BigInteger rb = null;         // the inflated value in BigInteger

 423         // use array bounds checking to handle too-long, len == 0,
 424         // bad offset, etc.
 425         try {
 426             // handle the sign
 427             boolean isneg = false;          // assume positive
 428             if (in[offset] == '-') {
 429                 isneg = true;               // leading minus means negative
 430                 offset++;
 431                 len--;
 432             } else if (in[offset] == '+') { // leading + allowed
 433                 offset++;
 434                 len--;
 435             }
 436 
 437             // should now be at numeric part of the significand
 438             boolean dot = false;             // true when there is a '.'

 439             long exp = 0;                    // exponent
 440             char c;                          // current character

 441             boolean isCompact = (len <= MAX_COMPACT_DIGITS);
 442             // integer significand array & idx is the index to it. The array
 443             // is ONLY used when we can't use a compact representation.

 444             int idx = 0;
 445             if (isCompact) {




 446                 // First compact case, we need not to preserve the character
 447                 // and we can just compute the value in place.
 448                 for (; len > 0; offset++, len--) {
 449                     c = in[offset];
 450                     if ((c == '0')) { // have zero
 451                         if (prec == 0)
 452                             prec = 1;
 453                         else if (rs != 0) {
 454                             rs *= 10;
 455                             ++prec;
 456                         } // else digit is a redundant leading zero
 457                         if (dot)
 458                             ++scl;
 459                     } else if ((c >= '1' && c <= '9')) { // have digit
 460                         int digit = c - '0';
 461                         if (prec != 1 || rs != 0)
 462                             ++prec; // prec unchanged if preceded by 0s
 463                         rs = rs * 10 + digit;
 464                         if (dot)
 465                             ++scl;
 466                     } else if (c == '.') {   // have dot
 467                         // have dot
 468                         if (dot) // two dots
 469                             throw new NumberFormatException();
 470                         dot = true;
 471                     } else if (Character.isDigit(c)) { // slow path
 472                         int digit = Character.digit(c, 10);
 473                         if (digit == 0) {
 474                             if (prec == 0)
 475                                 prec = 1;
 476                             else if (rs != 0) {
 477                                 rs *= 10;
 478                                 ++prec;
 479                             } // else digit is a redundant leading zero
 480                         } else {
 481                             if (prec != 1 || rs != 0)
 482                                 ++prec; // prec unchanged if preceded by 0s
 483                             rs = rs * 10 + digit;
 484                         }
 485                         if (dot)
 486                             ++scl;
 487                     } else if ((c == 'e') || (c == 'E')) {
 488                         exp = parseExp(in, offset, len);
 489                         // Next test is required for backwards compatibility
 490                         if ((int) exp != exp) // overflow
 491                             throw new NumberFormatException();
 492                         break; // [saves a test]
 493                     } else {
 494                         throw new NumberFormatException();
 495                     }
 496                 }
 497                 if (prec == 0) // no digits found
 498                     throw new NumberFormatException();
 499                 // Adjust scale if exp is not zero.
 500                 if (exp != 0) { // had significant exponent
 501                     scl = adjustScale(scl, exp);
 502                 }
 503                 rs = isneg ? -rs : rs;
 504                 int mcp = mc.precision;
 505                 int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];
 506                                        // therefore, this subtract cannot overflow
 507                 if (mcp > 0 && drop > 0) {  // do rounding
 508                     while (drop > 0) {
 509                         scl = checkScaleNonZero((long) scl - drop);
 510                         rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 511                         prec = longDigitLength(rs);
 512                         drop = prec - mcp;
 513                     }
 514                 }
 515             } else {
 516                 char coeff[] = new char[len];
 517                 for (; len > 0; offset++, len--) {
 518                     c = in[offset];
 519                     // have digit
 520                     if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
 521                         // First compact case, we need not to preserve the character
 522                         // and we can just compute the value in place.
 523                         if (c == '0' || Character.digit(c, 10) == 0) {
 524                             if (prec == 0) {
 525                                 coeff[idx] = c;
 526                                 prec = 1;
 527                             } else if (idx != 0) {
 528                                 coeff[idx++] = c;
 529                                 ++prec;
 530                             } // else c must be a redundant leading zero
 531                         } else {
 532                             if (prec != 1 || idx != 0)
 533                                 ++prec; // prec unchanged if preceded by 0s
 534                             coeff[idx++] = c;
 535                         }

 536                         if (dot)
 537                             ++scl;
 538                         continue;
 539                     }
 540                     // have dot
 541                     if (c == '.') {
 542                         // have dot
 543                         if (dot) // two dots
 544                             throw new NumberFormatException();
 545                         dot = true;
 546                         continue;
 547                     }
 548                     // exponent expected
 549                     if ((c != 'e') && (c != 'E'))
 550                         throw new NumberFormatException();
 551                     exp = parseExp(in, offset, len);
 552                     // Next test is required for backwards compatibility
 553                     if ((int) exp != exp) // overflow
 554                         throw new NumberFormatException();
 555                     break; // [saves a test]
 556                 }
 557                 // here when no characters left
 558                 if (prec == 0) // no digits found
 559                     throw new NumberFormatException();
 560                 // Adjust scale if exp is not zero.
 561                 if (exp != 0) { // had significant exponent
 562                     scl = adjustScale(scl, exp);
 563                 }
 564                 // Remove leading zeros from precision (digits count)
 565                 rb = new BigInteger(coeff, isneg ? -1 : 1, prec);
 566                 rs = compactValFor(rb);
 567                 int mcp = mc.precision;
 568                 if (mcp > 0 && (prec > mcp)) {
 569                     if (rs == INFLATED) {
 570                         int drop = prec - mcp;
 571                         while (drop > 0) {
 572                             scl = checkScaleNonZero((long) scl - drop);
 573                             rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);
 574                             rs = compactValFor(rb);
 575                             if (rs != INFLATED) {
 576                                 prec = longDigitLength(rs);
 577                                 break;
 578                             }
 579                             prec = bigDigitLength(rb);
 580                             drop = prec - mcp;
 581                         }
 582                     }
 583                     if (rs != INFLATED) {
 584                         int drop = prec - mcp;
 585                         while (drop > 0) {
 586                             scl = checkScaleNonZero((long) scl - drop);
 587                             rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 588                             prec = longDigitLength(rs);
 589                             drop = prec - mcp;
 590                         }
 591                         rb = null;
 592                     }
 593                 }
 594             }
 595         } catch (ArrayIndexOutOfBoundsException e) {
 596             throw new NumberFormatException();
 597         } catch (NegativeArraySizeException e) {
 598             throw new NumberFormatException();
 599         }
 600         this.scale = scl;
 601         this.precision = prec;
 602         this.intCompact = rs;
 603         this.intVal = rb;
 604     }
 605 
 606     private int adjustScale(int scl, long exp) {
 607         long adjustedScale = scl - exp;
 608         if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)
 609             throw new NumberFormatException("Scale out of range.");
 610         scl = (int) adjustedScale;
 611         return scl;
 612     }
 613 
 614     /*
 615      * parse exponent
 616      */
 617     private static long parseExp(char[] in, int offset, int len){
 618         long exp = 0;
 619         offset++;
 620         char c = in[offset];
 621         len--;
 622         boolean negexp = (c == '-');
 623         // optional sign
 624         if (negexp || c == '+') {
 625             offset++;
 626             c = in[offset];
 627             len--;
 628         }
 629         if (len <= 0) // no exponent digits
 630             throw new NumberFormatException();
 631         // skip leading zeros in the exponent
 632         while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {
 633             offset++;
 634             c = in[offset];
 635             len--;
 636         }
 637         if (len > 10) // too many nonzero exponent digits
 638             throw new NumberFormatException();
 639         // c now holds first digit of exponent
 640         for (;; len--) {
 641             int v;
 642             if (c >= '0' && c <= '9') {
 643                 v = c - '0';
 644             } else {
 645                 v = Character.digit(c, 10);
 646                 if (v < 0) // not a digit
 647                     throw new NumberFormatException();
 648             }
 649             exp = exp * 10 + v;
 650             if (len == 1)
 651                 break; // that was final character
 652             offset++;
 653             c = in[offset];
 654         }
 655         if (negexp) // apply sign
 656             exp = -exp;
 657         return exp;








































































 658     }
 659 
 660     /**
 661      * Translates a character array representation of a
 662      * {@code BigDecimal} into a {@code BigDecimal}, accepting the
 663      * same sequence of characters as the {@link #BigDecimal(String)}
 664      * constructor.
 665      *
 666      * <p>Note that if the sequence of characters is already available
 667      * as a character array, using this constructor is faster than
 668      * converting the {@code char} array to string and using the
 669      * {@code BigDecimal(String)} constructor .
 670      *
 671      * @param in {@code char} array that is the source of characters.
 672      * @throws NumberFormatException if {@code in} is not a valid
 673      *         representation of a {@code BigDecimal}.
 674      * @since  1.5
 675      */
 676     public BigDecimal(char[] in) {
 677         this(in, 0, in.length);


 813      */
 814     public BigDecimal(String val) {
 815         this(val.toCharArray(), 0, val.length());
 816     }
 817 
 818     /**
 819      * Translates the string representation of a {@code BigDecimal}
 820      * into a {@code BigDecimal}, accepting the same strings as the
 821      * {@link #BigDecimal(String)} constructor, with rounding
 822      * according to the context settings.
 823      *
 824      * @param  val string representation of a {@code BigDecimal}.
 825      * @param  mc the context to use.
 826      * @throws ArithmeticException if the result is inexact but the
 827      *         rounding mode is {@code UNNECESSARY}.
 828      * @throws NumberFormatException if {@code val} is not a valid
 829      *         representation of a BigDecimal.
 830      * @since  1.5
 831      */
 832     public BigDecimal(String val, MathContext mc) {
 833         this(val.toCharArray(), 0, val.length(), mc);


 834     }
 835 
 836     /**
 837      * Translates a {@code double} into a {@code BigDecimal} which
 838      * is the exact decimal representation of the {@code double}'s
 839      * binary floating-point value.  The scale of the returned
 840      * {@code BigDecimal} is the smallest value such that
 841      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 842      * <p>
 843      * <b>Notes:</b>
 844      * <ol>
 845      * <li>
 846      * The results of this constructor can be somewhat unpredictable.
 847      * One might assume that writing {@code new BigDecimal(0.1)} in
 848      * Java creates a {@code BigDecimal} which is exactly equal to
 849      * 0.1 (an unscaled value of 1, with a scale of 1), but it is
 850      * actually equal to
 851      * 0.1000000000000000055511151231257827021181583404541015625.
 852      * This is because 0.1 cannot be represented exactly as a
 853      * {@code double} (or, for that matter, as a binary fraction of


 861      * creates a {@code BigDecimal} which is <i>exactly</i> equal to
 862      * 0.1, as one would expect.  Therefore, it is generally
 863      * recommended that the {@linkplain #BigDecimal(String)
 864      * <tt>String</tt> constructor} be used in preference to this one.
 865      *
 866      * <li>
 867      * When a {@code double} must be used as a source for a
 868      * {@code BigDecimal}, note that this constructor provides an
 869      * exact conversion; it does not give the same result as
 870      * converting the {@code double} to a {@code String} using the
 871      * {@link Double#toString(double)} method and then using the
 872      * {@link #BigDecimal(String)} constructor.  To get that result,
 873      * use the {@code static} {@link #valueOf(double)} method.
 874      * </ol>
 875      *
 876      * @param val {@code double} value to be converted to
 877      *        {@code BigDecimal}.
 878      * @throws NumberFormatException if {@code val} is infinite or NaN.
 879      */
 880     public BigDecimal(double val) {
 881         this(val,MathContext.UNLIMITED);










































 882     }
 883 
 884     /**
 885      * Translates a {@code double} into a {@code BigDecimal}, with
 886      * rounding according to the context settings.  The scale of the
 887      * {@code BigDecimal} is the smallest value such that
 888      * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
 889      *
 890      * <p>The results of this constructor can be somewhat unpredictable
 891      * and its use is generally not recommended; see the notes under
 892      * the {@link #BigDecimal(double)} constructor.
 893      *
 894      * @param  val {@code double} value to be converted to
 895      *         {@code BigDecimal}.
 896      * @param  mc the context to use.
 897      * @throws ArithmeticException if the result is inexact but the
 898      *         RoundingMode is UNNECESSARY.
 899      * @throws NumberFormatException if {@code val} is infinite or NaN.
 900      * @since  1.5
 901      */
 902     public BigDecimal(double val, MathContext mc) {
 903         if (Double.isInfinite(val) || Double.isNaN(val))
 904             throw new NumberFormatException("Infinite or NaN");
 905         // Translate the double into sign, exponent and significand, according
 906         // to the formulae in JLS, Section 20.10.22.
 907         int sign = (val >= 0.0 ? 1 : -1); // Preserving sign of zero doesn't matter
 908         int exponent = Math.getExponent(val);
 909         long valBits = Double.doubleToLongBits(val);
 910         long significand = (exponent == (Double.MIN_EXPONENT-1)
 911                             ? (valBits & ((1L << 52) - 1)) << 1
 912                             : (valBits & ((1L << 52) - 1)) | (1L << 52));
 913         // At this point, val == sign * significand * 2**exponent.
 914 
 915         /*
 916          * Special case zero to supress nonterminating normalization and bogus
 917          * scale calculation.
 918          */
 919         if (significand == 0) {
 920             this.intVal = BigInteger.ZERO;
 921             this.scale = 0;
 922             this.intCompact = 0;
 923             this.precision = 1;
 924             return;
 925         }
 926         // Normalize
 927         while ((significand & 1) == 0) { // i.e., significand is even
 928             significand >>= 1;
 929             exponent++;
 930         }
 931         int scale = 0;
 932         // Calculate intVal and scale
 933         BigInteger intVal;
 934         long compactVal = sign * significand;
 935         if (exponent == 0) {
 936             // If the exponent is zero, the significant fits in a long
 937             assert compactVal != INFLATED;
 938             intVal = null;
 939         } else {
 940             if (exponent < 0) {
 941                 intVal = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
 942                 scale = -exponent;
 943             } else { //  (exponent > 0)
 944                 intVal = BigInteger.valueOf(2).pow(exponent).multiply(compactVal);
 945             }
 946             compactVal = compactValFor(intVal);
 947         }
 948         int prec = 0;
 949         int mcp = mc.precision;
 950         if (mcp > 0) { // do rounding
 951             int mode = mc.roundingMode.oldMode;
 952             int drop;
 953             if (compactVal == INFLATED) {
 954                 prec = bigDigitLength(intVal);
 955                 drop = prec - mcp;
 956                 while (drop > 0) {
 957                     scale = checkScaleNonZero((long) scale - drop);
 958                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
 959                     compactVal = compactValFor(intVal);
 960                     if (compactVal != INFLATED) {
 961                         break;
 962                     }
 963                     prec = bigDigitLength(intVal);
 964                     drop = prec - mcp;
 965                 }
 966             }
 967             if (compactVal != INFLATED) {
 968                 prec = longDigitLength(compactVal);
 969                 drop = prec - mcp;
 970                 while (drop > 0) {
 971                     scale = checkScaleNonZero((long) scale - drop);
 972                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
 973                     prec = longDigitLength(compactVal);
 974                     drop = prec - mcp;
 975                 }
 976                 intVal = null;
 977             }
 978         }
 979         this.intVal = intVal;
 980         this.intCompact = compactVal;
 981         this.scale = scale;
 982         this.precision = prec;
 983     }
 984 
 985     /**
 986      * Translates a {@code BigInteger} into a {@code BigDecimal}.
 987      * The scale of the {@code BigDecimal} is zero.
 988      *
 989      * @param val {@code BigInteger} value to be converted to
 990      *            {@code BigDecimal}.
 991      */
 992     public BigDecimal(BigInteger val) {
 993         scale = 0;
 994         intVal = val;
 995         intCompact = compactValFor(val);

 996     }
 997 
 998     /**
 999      * Translates a {@code BigInteger} into a {@code BigDecimal}
1000      * rounding according to the context settings.  The scale of the
1001      * {@code BigDecimal} is zero.
1002      *
1003      * @param val {@code BigInteger} value to be converted to
1004      *            {@code BigDecimal}.
1005      * @param  mc the context to use.
1006      * @throws ArithmeticException if the result is inexact but the
1007      *         rounding mode is {@code UNNECESSARY}.
1008      * @since  1.5
1009      */
1010     public BigDecimal(BigInteger val, MathContext mc) {
1011         this(val,0,mc);


1012     }
1013 
1014     /**
1015      * Translates a {@code BigInteger} unscaled value and an
1016      * {@code int} scale into a {@code BigDecimal}.  The value of
1017      * the {@code BigDecimal} is
1018      * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1019      *
1020      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1021      * @param scale scale of the {@code BigDecimal}.
1022      */
1023     public BigDecimal(BigInteger unscaledVal, int scale) {
1024         // Negative scales are now allowed
1025         this.intVal = unscaledVal;
1026         this.intCompact = compactValFor(unscaledVal);
1027         this.scale = scale;
1028     }
1029 
1030     /**
1031      * Translates a {@code BigInteger} unscaled value and an
1032      * {@code int} scale into a {@code BigDecimal}, with rounding
1033      * according to the context settings.  The value of the
1034      * {@code BigDecimal} is <tt>(unscaledVal &times;
1035      * 10<sup>-scale</sup>)</tt>, rounded according to the
1036      * {@code precision} and rounding mode settings.
1037      *
1038      * @param  unscaledVal unscaled value of the {@code BigDecimal}.
1039      * @param  scale scale of the {@code BigDecimal}.
1040      * @param  mc the context to use.
1041      * @throws ArithmeticException if the result is inexact but the
1042      *         rounding mode is {@code UNNECESSARY}.
1043      * @since  1.5
1044      */
1045     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1046         long compactVal = compactValFor(unscaledVal);
1047         int mcp = mc.precision;
1048         int prec = 0;
1049         if (mcp > 0) { // do rounding
1050             int mode = mc.roundingMode.oldMode;
1051             if (compactVal == INFLATED) {
1052                 prec = bigDigitLength(unscaledVal);
1053                 int drop = prec - mcp;
1054                 while (drop > 0) {
1055                     scale = checkScaleNonZero((long) scale - drop);
1056                     unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);
1057                     compactVal = compactValFor(unscaledVal);
1058                     if (compactVal != INFLATED) {
1059                         break;
1060                     }
1061                     prec = bigDigitLength(unscaledVal);
1062                     drop = prec - mcp;
1063                 }
1064             }
1065             if (compactVal != INFLATED) {
1066                 prec = longDigitLength(compactVal);
1067                 int drop = prec - mcp;     // drop can't be more than 18
1068                 while (drop > 0) {
1069                     scale = checkScaleNonZero((long) scale - drop);
1070                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);
1071                     prec = longDigitLength(compactVal);
1072                     drop = prec - mcp;
1073                 }
1074                 unscaledVal = null;
1075             }
1076         }
1077         this.intVal = unscaledVal;
1078         this.intCompact = compactVal;
1079         this.scale = scale;
1080         this.precision = prec;

1081     }
1082 
1083     /**
1084      * Translates an {@code int} into a {@code BigDecimal}.  The
1085      * scale of the {@code BigDecimal} is zero.
1086      *
1087      * @param val {@code int} value to be converted to
1088      *            {@code BigDecimal}.
1089      * @since  1.5
1090      */
1091     public BigDecimal(int val) {
1092         this.intCompact = val;
1093         this.scale = 0;
1094         this.intVal = null;
1095     }
1096 
1097     /**
1098      * Translates an {@code int} into a {@code BigDecimal}, with
1099      * rounding according to the context settings.  The scale of the
1100      * {@code BigDecimal}, before any rounding, is zero.
1101      *
1102      * @param  val {@code int} value to be converted to {@code BigDecimal}.
1103      * @param  mc the context to use.
1104      * @throws ArithmeticException if the result is inexact but the
1105      *         rounding mode is {@code UNNECESSARY}.
1106      * @since  1.5
1107      */
1108     public BigDecimal(int val, MathContext mc) {
1109         int mcp = mc.precision;
1110         long compactVal = val;
1111         int scale = 0;
1112         int prec = 0;
1113         if (mcp > 0) { // do rounding
1114             prec = longDigitLength(compactVal);
1115             int drop = prec - mcp; // drop can't be more than 18
1116             while (drop > 0) {
1117                 scale = checkScaleNonZero((long) scale - drop);
1118                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1119                 prec = longDigitLength(compactVal);
1120                 drop = prec - mcp;
1121             }
1122         }
1123         this.intVal = null;
1124         this.intCompact = compactVal;
1125         this.scale = scale;
1126         this.precision = prec;
1127     }
1128 
1129     /**
1130      * Translates a {@code long} into a {@code BigDecimal}.  The
1131      * scale of the {@code BigDecimal} is zero.
1132      *
1133      * @param val {@code long} value to be converted to {@code BigDecimal}.
1134      * @since  1.5
1135      */
1136     public BigDecimal(long val) {
1137         this.intCompact = val;
1138         this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1139         this.scale = 0;
1140     }
1141 
1142     /**
1143      * Translates a {@code long} into a {@code BigDecimal}, with
1144      * rounding according to the context settings.  The scale of the
1145      * {@code BigDecimal}, before any rounding, is zero.
1146      *
1147      * @param  val {@code long} value to be converted to {@code BigDecimal}.
1148      * @param  mc the context to use.
1149      * @throws ArithmeticException if the result is inexact but the
1150      *         rounding mode is {@code UNNECESSARY}.
1151      * @since  1.5
1152      */
1153     public BigDecimal(long val, MathContext mc) {
1154         int mcp = mc.precision;
1155         int mode = mc.roundingMode.oldMode;
1156         int prec = 0;
1157         int scale = 0;
1158         BigInteger intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1159         if (mcp > 0) { // do rounding
1160             if (val == INFLATED) {
1161                 prec = 19;
1162                 int drop = prec - mcp;
1163                 while (drop > 0) {
1164                     scale = checkScaleNonZero((long) scale - drop);
1165                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
1166                     val = compactValFor(intVal);
1167                     if (val != INFLATED) {
1168                         break;
1169                     }
1170                     prec = bigDigitLength(intVal);
1171                     drop = prec - mcp;
1172                 }
1173             }
1174             if (val != INFLATED) {
1175                 prec = longDigitLength(val);
1176                 int drop = prec - mcp;
1177                 while (drop > 0) {
1178                     scale = checkScaleNonZero((long) scale - drop);
1179                     val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1180                     prec = longDigitLength(val);
1181                     drop = prec - mcp;
1182                 }
1183                 intVal = null;
1184             }
1185         }
1186         this.intVal = intVal;
1187         this.intCompact = val;
1188         this.scale = scale;
1189         this.precision = prec;
1190     }
1191 
1192     // Static Factory Methods
1193 
1194     /**
1195      * Translates a {@code long} unscaled value and an
1196      * {@code int} scale into a {@code BigDecimal}.  This
1197      * {@literal "static factory method"} is provided in preference to
1198      * a ({@code long}, {@code int}) constructor because it
1199      * allows for reuse of frequently used {@code BigDecimal} values..
1200      *
1201      * @param unscaledVal unscaled value of the {@code BigDecimal}.
1202      * @param scale scale of the {@code BigDecimal}.
1203      * @return a {@code BigDecimal} whose value is
1204      *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
1205      */
1206     public static BigDecimal valueOf(long unscaledVal, int scale) {
1207         if (scale == 0)
1208             return valueOf(unscaledVal);
1209         else if (unscaledVal == 0) {
1210             return zeroValueOf(scale);



1211         }
1212         return new BigDecimal(unscaledVal == INFLATED ?
1213                               INFLATED_BIGINT : null,
1214                               unscaledVal, scale, 0);
1215     }
1216 
1217     /**
1218      * Translates a {@code long} value into a {@code BigDecimal}
1219      * with a scale of zero.  This {@literal "static factory method"}
1220      * is provided in preference to a ({@code long}) constructor
1221      * because it allows for reuse of frequently used
1222      * {@code BigDecimal} values.
1223      *
1224      * @param val value of the {@code BigDecimal}.
1225      * @return a {@code BigDecimal} whose value is {@code val}.
1226      */
1227     public static BigDecimal valueOf(long val) {
1228         if (val >= 0 && val < zeroThroughTen.length)
1229             return zeroThroughTen[(int)val];
1230         else if (val != INFLATED)
1231             return new BigDecimal(null, val, 0, 0);
1232         return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1233     }
1234 
1235     static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1236         if (scale == 0 && unscaledVal >= 0 && unscaledVal < zeroThroughTen.length) {
1237             return zeroThroughTen[(int) unscaledVal];
1238         } else if (unscaledVal == 0) {
1239             return zeroValueOf(scale);
1240         }
1241         return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1242                 unscaledVal, scale, prec);
1243     }
1244 
1245     static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1246         long val = compactValFor(intVal);
1247         if (val == 0) {
1248             return zeroValueOf(scale);
1249         } else if (scale == 0 && val >= 0 && val < zeroThroughTen.length) {
1250             return zeroThroughTen[(int) val];
1251         }
1252         return new BigDecimal(intVal, val, scale, prec);
1253     }
1254 
1255     static BigDecimal zeroValueOf(int scale) {
1256         if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1257             return ZERO_SCALED_BY[scale];
1258         else
1259             return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1260     }
1261 
1262     /**
1263      * Translates a {@code double} into a {@code BigDecimal}, using
1264      * the {@code double}'s canonical string representation provided
1265      * by the {@link Double#toString(double)} method.
1266      *
1267      * <p><b>Note:</b> This is generally the preferred way to convert
1268      * a {@code double} (or {@code float}) into a
1269      * {@code BigDecimal}, as the value returned is equal to that
1270      * resulting from constructing a {@code BigDecimal} from the
1271      * result of using {@link Double#toString(double)}.
1272      *
1273      * @param  val {@code double} to convert to a {@code BigDecimal}.
1274      * @return a {@code BigDecimal} whose value is equal to or approximately
1275      *         equal to the value of {@code val}.
1276      * @throws NumberFormatException if {@code val} is infinite or NaN.
1277      * @since  1.5
1278      */
1279     public static BigDecimal valueOf(double val) {
1280         // Reminder: a zero double returns '0.0', so we cannot fastpath
1281         // to use the constant ZERO.  This might be important enough to
1282         // justify a factory approach, a cache, or a few private
1283         // constants, later.
1284         return new BigDecimal(Double.toString(val));
1285     }
1286 
1287     // Arithmetic Operations
1288     /**
1289      * Returns a {@code BigDecimal} whose value is {@code (this +
1290      * augend)}, and whose scale is {@code max(this.scale(),
1291      * augend.scale())}.
1292      *
1293      * @param  augend value to be added to this {@code BigDecimal}.
1294      * @return {@code this + augend}
1295      */
1296     public BigDecimal add(BigDecimal augend) {
1297         if (this.intCompact != INFLATED) {
1298             if ((augend.intCompact != INFLATED)) {
1299                 return add(this.intCompact, this.scale, augend.intCompact, augend.scale);
1300             } else {
1301                 return add(this.intCompact, this.scale, augend.intVal, augend.scale);














1302             }
1303         } else {
1304             if ((augend.intCompact != INFLATED)) {
1305                 return add(augend.intCompact, augend.scale, this.intVal, this.scale);
1306             } else {
1307                 return add(this.intVal, this.scale, augend.intVal, augend.scale);
1308             }






1309         }








1310     }
1311 
1312     /**
1313      * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1314      * with rounding according to the context settings.
1315      *
1316      * If either number is zero and the precision setting is nonzero then
1317      * the other number, rounded if necessary, is used as the result.
1318      *
1319      * @param  augend value to be added to this {@code BigDecimal}.
1320      * @param  mc the context to use.
1321      * @return {@code this + augend}, rounded as necessary.
1322      * @throws ArithmeticException if the result is inexact but the
1323      *         rounding mode is {@code UNNECESSARY}.
1324      * @since  1.5
1325      */
1326     public BigDecimal add(BigDecimal augend, MathContext mc) {
1327         if (mc.precision == 0)
1328             return add(augend);
1329         BigDecimal lhs = this;
1330 




1331         // If either number is zero then the other number, rounded and
1332         // scaled if necessary, is used as the result.
1333         {
1334             boolean lhsIsZero = lhs.signum() == 0;
1335             boolean augendIsZero = augend.signum() == 0;
1336 
1337             if (lhsIsZero || augendIsZero) {
1338                 int preferredScale = Math.max(lhs.scale(), augend.scale());
1339                 BigDecimal result;
1340 

1341                 if (lhsIsZero && augendIsZero)
1342                     return zeroValueOf(preferredScale);

1343                 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1344 
1345                 if (result.scale() == preferredScale)
1346                     return result;
1347                 else if (result.scale() > preferredScale) {
1348                     return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);




1349                 } else { // result.scale < preferredScale
1350                     int precisionDiff = mc.precision - result.precision();
1351                     int scaleDiff     = preferredScale - result.scale();
1352 
1353                     if (precisionDiff >= scaleDiff)
1354                         return result.setScale(preferredScale); // can achieve target scale
1355                     else
1356                         return result.setScale(result.scale() + precisionDiff);
1357                 }
1358             }
1359         }
1360 
1361         long padding = (long) lhs.scale - augend.scale;
1362         if (padding != 0) { // scales differ; alignment needed
1363             BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1364             matchScale(arg);
1365             lhs = arg[0];
1366             augend = arg[1];
1367         }
1368         return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);



1369     }
1370 
1371     /**
1372      * Returns an array of length two, the sum of whose entries is
1373      * equal to the rounded sum of the {@code BigDecimal} arguments.
1374      *
1375      * <p>If the digit positions of the arguments have a sufficient
1376      * gap between them, the value smaller in magnitude can be
1377      * condensed into a {@literal "sticky bit"} and the end result will
1378      * round the same way <em>if</em> the precision of the final
1379      * result does not include the high order digit of the small
1380      * magnitude operand.
1381      *
1382      * <p>Note that while strictly speaking this is an optimization,
1383      * it makes a much wider range of additions practical.
1384      *
1385      * <p>This corresponds to a pre-shift operation in a fixed
1386      * precision floating-point adder; this method is complicated by
1387      * variable precision of the result as determined by the
1388      * MathContext.  A more nuanced operation could implement a
1389      * {@literal "right shift"} on the smaller magnitude operand so
1390      * that the number of digits of the smaller operand could be
1391      * reduced even though the significands partially overlapped.
1392      */
1393     private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {

1394         assert padding != 0;
1395         BigDecimal big;
1396         BigDecimal small;
1397 
1398         if (padding < 0) { // lhs is big; augend is small
1399             big = lhs;
1400             small = augend;
1401         } else { // lhs is small; augend is big
1402             big = augend;
1403             small = lhs;
1404         }
1405 
1406         /*
1407          * This is the estimated scale of an ulp of the result; it assumes that
1408          * the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>
1409          * 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>
1410          * 98.8)
1411          */
1412         long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;
1413 
1414         /*
1415          * The low-order digit position of big is big.scale().  This
1416          * is true regardless of whether big has a positive or
1417          * negative scale.  The high-order digit position of small is
1418          * small.scale - (small.precision() - 1).  To do the full
1419          * condensation, the digit positions of big and small must be
1420          * disjoint *and* the digit positions of small should not be
1421          * directly visible in the result.
1422          */
1423         long smallHighDigitPos = (long) small.scale - small.precision() + 1;
1424         if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1425             smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1426             small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));

1427         }
1428 
1429         // Since addition is symmetric, preserving input order in
1430         // returned operands doesn't matter
1431         BigDecimal[] result = {big, small};
1432         return result;
1433     }
1434 
1435     /**
1436      * Returns a {@code BigDecimal} whose value is {@code (this -
1437      * subtrahend)}, and whose scale is {@code max(this.scale(),
1438      * subtrahend.scale())}.
1439      *
1440      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1441      * @return {@code this - subtrahend}
1442      */
1443     public BigDecimal subtract(BigDecimal subtrahend) {
1444         if (this.intCompact != INFLATED) {
1445             if ((subtrahend.intCompact != INFLATED)) {
1446                 return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);
1447             } else {
1448                 return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1449             }
1450         } else {
1451             if ((subtrahend.intCompact != INFLATED)) {
1452                 // Pair of subtrahend values given before pair of
1453                 // values from this BigDecimal to avoid need for
1454                 // method overloading on the specialized add method
1455                 return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);
1456             } else {
1457                 return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);
1458             }
1459         }
1460     }
1461 
1462     /**
1463      * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1464      * with rounding according to the context settings.
1465      *
1466      * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1467      * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1468      *
1469      * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1470      * @param  mc the context to use.
1471      * @return {@code this - subtrahend}, rounded as necessary.
1472      * @throws ArithmeticException if the result is inexact but the
1473      *         rounding mode is {@code UNNECESSARY}.
1474      * @since  1.5
1475      */
1476     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {

1477         if (mc.precision == 0)
1478             return subtract(subtrahend);
1479         // share the special rounding code in add()
1480         return add(subtrahend.negate(), mc);
1481     }
1482 
1483     /**
1484      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1485      * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1486      * multiplicand.scale())}.
1487      *
1488      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1489      * @return {@code this * multiplicand}
1490      */
1491     public BigDecimal multiply(BigDecimal multiplicand) {
1492         int productScale = checkScale((long) scale + multiplicand.scale);
1493         if (this.intCompact != INFLATED) {
1494             if ((multiplicand.intCompact != INFLATED)) {
1495                 return multiply(this.intCompact, multiplicand.intCompact, productScale);
1496             } else {
1497                 return multiply(this.intCompact, multiplicand.intVal, productScale);
1498             }
1499         } else {
1500             if ((multiplicand.intCompact != INFLATED)) {
1501                 return multiply(multiplicand.intCompact, this.intVal, productScale);
1502             } else {
1503                 return multiply(this.intVal, multiplicand.intVal, productScale);
1504             }
1505         }

















1506     }
1507 
1508     /**
1509      * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1510      * multiplicand)</tt>, with rounding according to the context settings.
1511      *
1512      * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1513      * @param  mc the context to use.
1514      * @return {@code this * multiplicand}, rounded as necessary.
1515      * @throws ArithmeticException if the result is inexact but the
1516      *         rounding mode is {@code UNNECESSARY}.
1517      * @since  1.5
1518      */
1519     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1520         if (mc.precision == 0)
1521             return multiply(multiplicand);
1522         int productScale = checkScale((long) scale + multiplicand.scale);
1523         if (this.intCompact != INFLATED) {
1524             if ((multiplicand.intCompact != INFLATED)) {
1525                 return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);
1526             } else {
1527                 return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);
1528             }
1529         } else {
1530             if ((multiplicand.intCompact != INFLATED)) {
1531                 return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);
1532             } else {
1533                 return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);
1534             }
1535         }
1536     }
1537 
1538     /**
1539      * Returns a {@code BigDecimal} whose value is {@code (this /
1540      * divisor)}, and whose scale is as specified.  If rounding must
1541      * be performed to generate a result with the specified scale, the
1542      * specified rounding mode is applied.
1543      *
1544      * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1545      * should be used in preference to this legacy method.
1546      *
1547      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1548      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1549      * @param  roundingMode rounding mode to apply.
1550      * @return {@code this / divisor}
1551      * @throws ArithmeticException if {@code divisor} is zero,
1552      *         {@code roundingMode==ROUND_UNNECESSARY} and
1553      *         the specified scale is insufficient to represent the result
1554      *         of the division exactly.
1555      * @throws IllegalArgumentException if {@code roundingMode} does not
1556      *         represent a valid rounding mode.
1557      * @see    #ROUND_UP
1558      * @see    #ROUND_DOWN
1559      * @see    #ROUND_CEILING
1560      * @see    #ROUND_FLOOR
1561      * @see    #ROUND_HALF_UP
1562      * @see    #ROUND_HALF_DOWN
1563      * @see    #ROUND_HALF_EVEN
1564      * @see    #ROUND_UNNECESSARY
1565      */
1566     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {





1567         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1568             throw new IllegalArgumentException("Invalid rounding mode");
1569         if (this.intCompact != INFLATED) {
1570             if ((divisor.intCompact != INFLATED)) {
1571                 return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);


















































1572             } else {
1573                 return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);



1574             }



















1575         } else {
1576             if ((divisor.intCompact != INFLATED)) {
1577                 return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);
1578             } else {
1579                 return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);
1580             }



















1581         }



1582     }
1583 
1584     /**
1585      * Returns a {@code BigDecimal} whose value is {@code (this /
1586      * divisor)}, and whose scale is as specified.  If rounding must
1587      * be performed to generate a result with the specified scale, the
1588      * specified rounding mode is applied.
1589      *
1590      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1591      * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1592      * @param  roundingMode rounding mode to apply.
1593      * @return {@code this / divisor}
1594      * @throws ArithmeticException if {@code divisor} is zero,
1595      *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1596      *         the specified scale is insufficient to represent the result
1597      *         of the division exactly.
1598      * @since 1.5
1599      */
1600     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1601         return divide(divisor, scale, roundingMode.oldMode);


1659      * expansion) an {@code ArithmeticException} is thrown.
1660      *
1661      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1662      * @throws ArithmeticException if the exact quotient does not have a
1663      *         terminating decimal expansion
1664      * @return {@code this / divisor}
1665      * @since 1.5
1666      * @author Joseph D. Darcy
1667      */
1668     public BigDecimal divide(BigDecimal divisor) {
1669         /*
1670          * Handle zero cases first.
1671          */
1672         if (divisor.signum() == 0) {   // x/0
1673             if (this.signum() == 0)    // 0/0
1674                 throw new ArithmeticException("Division undefined");  // NaN
1675             throw new ArithmeticException("Division by zero");
1676         }
1677 
1678         // Calculate preferred scale
1679         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1680 
1681         if (this.signum() == 0) // 0/y
1682             return zeroValueOf(preferredScale);



1683         else {


1684             /*
1685              * If the quotient this/divisor has a terminating decimal
1686              * expansion, the expansion can have no more than
1687              * (a.precision() + ceil(10*b.precision)/3) digits.
1688              * Therefore, create a MathContext object with this
1689              * precision and do a divide with the UNNECESSARY rounding
1690              * mode.
1691              */
1692             MathContext mc = new MathContext( (int)Math.min(this.precision() +
1693                                                             (long)Math.ceil(10.0*divisor.precision()/3.0),
1694                                                             Integer.MAX_VALUE),
1695                                               RoundingMode.UNNECESSARY);
1696             BigDecimal quotient;
1697             try {
1698                 quotient = this.divide(divisor, mc);
1699             } catch (ArithmeticException e) {
1700                 throw new ArithmeticException("Non-terminating decimal expansion; " +
1701                                               "no exact representable decimal result.");
1702             }
1703 
1704             int quotientScale = quotient.scale();
1705 
1706             // divide(BigDecimal, mc) tries to adjust the quotient to
1707             // the desired one by removing trailing zeros; since the
1708             // exact divide method does not have an explicit digit
1709             // limit, we can add zeros too.

1710             if (preferredScale > quotientScale)
1711                 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1712 
1713             return quotient;
1714         }
1715     }
1716 
1717     /**
1718      * Returns a {@code BigDecimal} whose value is {@code (this /
1719      * divisor)}, with rounding according to the context settings.
1720      *
1721      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1722      * @param  mc the context to use.
1723      * @return {@code this / divisor}, rounded as necessary.
1724      * @throws ArithmeticException if the result is inexact but the
1725      *         rounding mode is {@code UNNECESSARY} or
1726      *         {@code mc.precision == 0} and the quotient has a
1727      *         non-terminating decimal expansion.
1728      * @since  1.5
1729      */


1735         BigDecimal dividend = this;
1736         long preferredScale = (long)dividend.scale - divisor.scale;
1737         // Now calculate the answer.  We use the existing
1738         // divide-and-round method, but as this rounds to scale we have
1739         // to normalize the values here to achieve the desired result.
1740         // For x/y we first handle y=0 and x=0, and then normalize x and
1741         // y to give x' and y' with the following constraints:
1742         //   (a) 0.1 <= x' < 1
1743         //   (b)  x' <= y' < 10*x'
1744         // Dividing x'/y' with the required scale set to mc.precision then
1745         // will give a result in the range 0.1 to 1 rounded to exactly
1746         // the right number of digits (except in the case of a result of
1747         // 1.000... which can arise when x=y, or when rounding overflows
1748         // The 1.000... case will reduce properly to 1.
1749         if (divisor.signum() == 0) {      // x/0
1750             if (dividend.signum() == 0)    // 0/0
1751                 throw new ArithmeticException("Division undefined");  // NaN
1752             throw new ArithmeticException("Division by zero");
1753         }
1754         if (dividend.signum() == 0) // 0/y
1755             return zeroValueOf(saturateLong(preferredScale));



1756         int xscale = dividend.precision();
1757         int yscale = divisor.precision();
1758         if(dividend.intCompact!=INFLATED) {
1759             if(divisor.intCompact!=INFLATED) {
1760                 return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);
1761             } else {
1762                 return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);
1763             }
1764         } else {
1765             if(divisor.intCompact!=INFLATED) {
1766                 return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);
1767             } else {
1768                 return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);
1769             }
1770         }












1771     }
1772 
1773     /**
1774      * Returns a {@code BigDecimal} whose value is the integer part
1775      * of the quotient {@code (this / divisor)} rounded down.  The
1776      * preferred scale of the result is {@code (this.scale() -
1777      * divisor.scale())}.
1778      *
1779      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1780      * @return The integer part of {@code this / divisor}.
1781      * @throws ArithmeticException if {@code divisor==0}
1782      * @since  1.5
1783      */
1784     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1785         // Calculate preferred scale
1786         int preferredScale = saturateLong((long) this.scale - divisor.scale);
1787         if (this.compareMagnitude(divisor) < 0) {
1788             // much faster when this << divisor
1789             return zeroValueOf(preferredScale);
1790         }
1791 
1792         if (this.signum() == 0 && divisor.signum() != 0)
1793             return this.setScale(preferredScale, ROUND_UNNECESSARY);
1794 
1795         // Perform a divide with enough digits to round to a correct
1796         // integer value; then remove any fractional digits
1797 
1798         int maxDigits = (int)Math.min(this.precision() +
1799                                       (long)Math.ceil(10.0*divisor.precision()/3.0) +
1800                                       Math.abs((long)this.scale() - divisor.scale()) + 2,
1801                                       Integer.MAX_VALUE);
1802         BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1803                                                                    RoundingMode.DOWN));
1804         if (quotient.scale > 0) {
1805             quotient = quotient.setScale(0, RoundingMode.DOWN);
1806             quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);
1807         }
1808 
1809         if (quotient.scale < preferredScale) {
1810             // pad with zeros if necessary
1811             quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1812         }
1813 
1814         return quotient;
1815     }
1816 
1817     /**
1818      * Returns a {@code BigDecimal} whose value is the integer part
1819      * of {@code (this / divisor)}.  Since the integer part of the
1820      * exact quotient does not depend on the rounding mode, the
1821      * rounding mode does not affect the values returned by this
1822      * method.  The preferred scale of the result is
1823      * {@code (this.scale() - divisor.scale())}.  An
1824      * {@code ArithmeticException} is thrown if the integer part of
1825      * the exact quotient needs more than {@code mc.precision}
1826      * digits.
1827      *
1828      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1829      * @param  mc the context to use.
1830      * @return The integer part of {@code this / divisor}.
1831      * @throws ArithmeticException if {@code divisor==0}
1832      * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1833      *         requires a precision of more than {@code mc.precision} digits.
1834      * @since  1.5
1835      * @author Joseph D. Darcy
1836      */
1837     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1838         if (mc.precision == 0 || // exact result
1839             (this.compareMagnitude(divisor) < 0)) // zero result
1840             return divideToIntegralValue(divisor);
1841 
1842         // Calculate preferred scale
1843         int preferredScale = saturateLong((long)this.scale - divisor.scale);
1844 
1845         /*
1846          * Perform a normal divide to mc.precision digits.  If the
1847          * remainder has absolute value less than the divisor, the
1848          * integer portion of the quotient fits into mc.precision
1849          * digits.  Next, remove any fractional digits from the
1850          * quotient and adjust the scale to the preferred value.
1851          */
1852         BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));

1853 
1854         if (result.scale() < 0) {
1855             /*
1856              * Result is an integer. See if quotient represents the
1857              * full integer portion of the exact quotient; if it does,
1858              * the computed remainder will be less than the divisor.
1859              */
1860             BigDecimal product = result.multiply(divisor);
1861             // If the quotient is the full integer value,
1862             // |dividend-product| < |divisor|.
1863             if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1864                 throw new ArithmeticException("Division impossible");
1865             }
1866         } else if (result.scale() > 0) {
1867             /*
1868              * Integer portion of quotient will fit into precision
1869              * digits; recompute quotient to scale 0 to avoid double
1870              * rounding and then try to adjust, if necessary.
1871              */
1872             result = result.setScale(0, RoundingMode.DOWN);
1873         }
1874         // else result.scale() == 0;
1875 
1876         int precisionDiff;
1877         if ((preferredScale > result.scale()) &&
1878             (precisionDiff = mc.precision - result.precision()) > 0) {
1879             return result.setScale(result.scale() +
1880                                    Math.min(precisionDiff, preferredScale - result.scale) );
1881         } else {
1882             return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);

1883         }
1884     }
1885 
1886     /**
1887      * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1888      *
1889      * <p>The remainder is given by
1890      * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1891      * Note that this is not the modulo operation (the result can be
1892      * negative).
1893      *
1894      * @param  divisor value by which this {@code BigDecimal} is to be divided.
1895      * @return {@code this % divisor}.
1896      * @throws ArithmeticException if {@code divisor==0}
1897      * @since  1.5
1898      */
1899     public BigDecimal remainder(BigDecimal divisor) {
1900         BigDecimal divrem[] = this.divideAndRemainder(divisor);
1901         return divrem[1];
1902     }


2004      * unlimited precision.
2005      *
2006      * <p>The parameter {@code n} must be in the range 0 through
2007      * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
2008      * #ONE}.
2009      *
2010      * Note that future releases may expand the allowable exponent
2011      * range of this method.
2012      *
2013      * @param  n power to raise this {@code BigDecimal} to.
2014      * @return <tt>this<sup>n</sup></tt>
2015      * @throws ArithmeticException if {@code n} is out of range.
2016      * @since  1.5
2017      */
2018     public BigDecimal pow(int n) {
2019         if (n < 0 || n > 999999999)
2020             throw new ArithmeticException("Invalid operation");
2021         // No need to calculate pow(n) if result will over/underflow.
2022         // Don't attempt to support "supernormal" numbers.
2023         int newScale = checkScale((long)scale * n);
2024         return new BigDecimal(this.inflated().pow(n), newScale);

2025     }
2026 
2027 
2028     /**
2029      * Returns a {@code BigDecimal} whose value is
2030      * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
2031      * the core algorithm defined in ANSI standard X3.274-1996 with
2032      * rounding according to the context settings.  In general, the
2033      * returned numerical value is within two ulps of the exact
2034      * numerical value for the chosen precision.  Note that future
2035      * releases may use a different algorithm with a decreased
2036      * allowable error bound and increased allowable exponent range.
2037      *
2038      * <p>The X3.274-1996 algorithm is:
2039      *
2040      * <ul>
2041      * <li> An {@code ArithmeticException} exception is thrown if
2042      *  <ul>
2043      *    <li>{@code abs(n) > 999999999}
2044      *    <li>{@code mc.precision == 0} and {@code n < 0}


2065      *   is then rounded to the destination precision.
2066      *   </ul>
2067      * </ul>
2068      *
2069      * @param  n power to raise this {@code BigDecimal} to.
2070      * @param  mc the context to use.
2071      * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
2072      *         algorithm
2073      * @throws ArithmeticException if the result is inexact but the
2074      *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
2075      *         of range.
2076      * @since  1.5
2077      */
2078     public BigDecimal pow(int n, MathContext mc) {
2079         if (mc.precision == 0)
2080             return pow(n);
2081         if (n < -999999999 || n > 999999999)
2082             throw new ArithmeticException("Invalid operation");
2083         if (n == 0)
2084             return ONE;                      // x**0 == 1 in X3.274

2085         BigDecimal lhs = this;
2086         MathContext workmc = mc;           // working settings
2087         int mag = Math.abs(n);               // magnitude of n
2088         if (mc.precision > 0) {

2089             int elength = longDigitLength(mag); // length of n in digits
2090             if (elength > mc.precision)        // X3.274 rule
2091                 throw new ArithmeticException("Invalid operation");
2092             workmc = new MathContext(mc.precision + elength + 1,
2093                                       mc.roundingMode);
2094         }
2095         // ready to carry out power calculation...
2096         BigDecimal acc = ONE;           // accumulator
2097         boolean seenbit = false;        // set once we've seen a 1-bit
2098         for (int i=1;;i++) {            // for each bit [top bit ignored]
2099             mag += mag;                 // shift left 1 bit
2100             if (mag < 0) {              // top bit is set
2101                 seenbit = true;         // OK, we're off
2102                 acc = acc.multiply(lhs, workmc); // acc=acc*x
2103             }
2104             if (i == 31)
2105                 break;                  // that was the last bit
2106             if (seenbit)
2107                 acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
2108                 // else (!seenbit) no point in squaring ONE
2109         }
2110         // if negative n, calculate the reciprocal using working precision
2111         if (n < 0) // [hence mc.precision>0]
2112             acc=ONE.divide(acc, workmc);
2113         // round to final precision and strip zeros
2114         return doRound(acc, mc);
2115     }
2116 
2117     /**
2118      * Returns a {@code BigDecimal} whose value is the absolute value
2119      * of this {@code BigDecimal}, and whose scale is
2120      * {@code this.scale()}.
2121      *
2122      * @return {@code abs(this)}
2123      */
2124     public BigDecimal abs() {
2125         return (signum() < 0 ? negate() : this);
2126     }
2127 
2128     /**
2129      * Returns a {@code BigDecimal} whose value is the absolute value
2130      * of this {@code BigDecimal}, with rounding according to the
2131      * context settings.
2132      *
2133      * @param mc the context to use.
2134      * @return {@code abs(this)}, rounded as necessary.
2135      * @throws ArithmeticException if the result is inexact but the
2136      *         rounding mode is {@code UNNECESSARY}.
2137      * @since 1.5
2138      */
2139     public BigDecimal abs(MathContext mc) {
2140         return (signum() < 0 ? negate(mc) : plus(mc));
2141     }
2142 
2143     /**
2144      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2145      * and whose scale is {@code this.scale()}.
2146      *
2147      * @return {@code -this}.
2148      */
2149     public BigDecimal negate() {
2150         if (intCompact == INFLATED) {
2151             return new BigDecimal(intVal.negate(), INFLATED, scale, precision);
2152         } else {
2153             return valueOf(-intCompact, scale, precision);


2154         }

2155     }
2156 
2157     /**
2158      * Returns a {@code BigDecimal} whose value is {@code (-this)},
2159      * with rounding according to the context settings.
2160      *
2161      * @param mc the context to use.
2162      * @return {@code -this}, rounded as necessary.
2163      * @throws ArithmeticException if the result is inexact but the
2164      *         rounding mode is {@code UNNECESSARY}.
2165      * @since  1.5
2166      */
2167     public BigDecimal negate(MathContext mc) {
2168         return negate().plus(mc);
2169     }
2170 
2171     /**
2172      * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2173      * scale is {@code this.scale()}.
2174      *


2230     public int scale() {
2231         return scale;
2232     }
2233 
2234     /**
2235      * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2236      * precision is the number of digits in the unscaled value.)
2237      *
2238      * <p>The precision of a zero value is 1.
2239      *
2240      * @return the precision of this {@code BigDecimal}.
2241      * @since  1.5
2242      */
2243     public int precision() {
2244         int result = precision;
2245         if (result == 0) {
2246             long s = intCompact;
2247             if (s != INFLATED)
2248                 result = longDigitLength(s);
2249             else
2250                 result = bigDigitLength(intVal);
2251             precision = result;
2252         }
2253         return result;
2254     }
2255 
2256 
2257     /**
2258      * Returns a {@code BigInteger} whose value is the <i>unscaled
2259      * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
2260      * 10<sup>this.scale()</sup>)</tt>.)
2261      *
2262      * @return the unscaled value of this {@code BigDecimal}.
2263      * @since  1.2
2264      */
2265     public BigInteger unscaledValue() {
2266         return this.inflated();
2267     }
2268 
2269     // Rounding Modes
2270 
2271     /**
2272      * Rounding mode to round away from zero.  Always increments the
2273      * digit prior to a nonzero discarded fraction.  Note that this rounding
2274      * mode never decreases the magnitude of the calculated value.
2275      */
2276     public final static int ROUND_UP =           0;
2277 
2278     /**
2279      * Rounding mode to round towards zero.  Never increments the digit
2280      * prior to a discarded fraction (i.e., truncates).  Note that this
2281      * rounding mode never increases the magnitude of the calculated value.
2282      */
2283     public final static int ROUND_DOWN =         1;
2284 
2285     /**
2286      * Rounding mode to round towards positive infinity.  If the


2427      *         rounding.
2428      * @throws IllegalArgumentException if {@code roundingMode} does not
2429      *         represent a valid rounding mode.
2430      * @see    #ROUND_UP
2431      * @see    #ROUND_DOWN
2432      * @see    #ROUND_CEILING
2433      * @see    #ROUND_FLOOR
2434      * @see    #ROUND_HALF_UP
2435      * @see    #ROUND_HALF_DOWN
2436      * @see    #ROUND_HALF_EVEN
2437      * @see    #ROUND_UNNECESSARY
2438      */
2439     public BigDecimal setScale(int newScale, int roundingMode) {
2440         if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2441             throw new IllegalArgumentException("Invalid rounding mode");
2442 
2443         int oldScale = this.scale;
2444         if (newScale == oldScale)        // easy case
2445             return this;
2446         if (this.signum() == 0)            // zero can have any scale
2447             return zeroValueOf(newScale);
2448         if(this.intCompact!=INFLATED) {
2449             long rs = this.intCompact;
2450             if (newScale > oldScale) {
2451                 int raise = checkScale((long) newScale - oldScale);
2452                 if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {
2453                     return valueOf(rs,newScale);
2454                 }
2455                 BigInteger rb = bigMultiplyPowerTen(raise);
2456                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2457             } else {
2458                 // newScale < oldScale -- drop some digits
2459                 // Can't predict the precision due to the effect of rounding.
2460                 int drop = checkScale((long) oldScale - newScale);
2461                 if (drop < LONG_TEN_POWERS_TABLE.length) {
2462                     return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);
2463                 } else {
2464                     return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);
2465                 }
2466             }
2467         } else {
2468             if (newScale > oldScale) {
2469                 int raise = checkScale((long) newScale - oldScale);
2470                 BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);
2471                 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);
2472             } else {
2473                 // newScale < oldScale -- drop some digits
2474                 // Can't predict the precision due to the effect of rounding.
2475                 int drop = checkScale((long) oldScale - newScale);
2476                 if (drop < LONG_TEN_POWERS_TABLE.length)
2477                     return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,
2478                                           newScale);

2479                 else
2480                     return divideAndRound(this.intVal,  bigTenToThe(drop), newScale, roundingMode, newScale);
2481             }

2482         }
2483     }
2484 
2485     /**
2486      * Returns a {@code BigDecimal} whose scale is the specified
2487      * value, and whose value is numerically equal to this
2488      * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2489      * if this is not possible.
2490      *
2491      * <p>This call is typically used to increase the scale, in which
2492      * case it is guaranteed that there exists a {@code BigDecimal}
2493      * of the specified scale and the correct value.  The call can
2494      * also be used to reduce the scale if the caller knows that the
2495      * {@code BigDecimal} has sufficiently many zeros at the end of
2496      * its fractional part (i.e., factors of ten in its integer value)
2497      * to allow for the rescaling without changing its value.
2498      *
2499      * <p>This method returns the same result as the two-argument
2500      * versions of {@code setScale}, but saves the caller the trouble
2501      * of specifying a rounding mode in cases where it is irrelevant.


2580      */
2581     public BigDecimal scaleByPowerOfTen(int n) {
2582         return new BigDecimal(intVal, intCompact,
2583                               checkScale((long)scale - n), precision);
2584     }
2585 
2586     /**
2587      * Returns a {@code BigDecimal} which is numerically equal to
2588      * this one but with any trailing zeros removed from the
2589      * representation.  For example, stripping the trailing zeros from
2590      * the {@code BigDecimal} value {@code 600.0}, which has
2591      * [{@code BigInteger}, {@code scale}] components equals to
2592      * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2593      * {@code scale}] components equals to [6, -2]
2594      *
2595      * @return a numerically equal {@code BigDecimal} with any
2596      * trailing zeros removed.
2597      * @since 1.5
2598      */
2599     public BigDecimal stripTrailingZeros() {
2600         if(intCompact!=INFLATED) {
2601             return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);
2602         } else {
2603             return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);
2604         }
2605     }
2606 
2607     // Comparison Operations
2608 
2609     /**
2610      * Compares this {@code BigDecimal} with the specified
2611      * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2612      * equal in value but have a different scale (like 2.0 and 2.00)
2613      * are considered equal by this method.  This method is provided
2614      * in preference to individual methods for each of the six boolean
2615      * comparison operators ({@literal <}, ==,
2616      * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2617      * suggested idiom for performing these comparisons is:
2618      * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2619      * &lt;<i>op</i>&gt; is one of the six comparison operators.
2620      *
2621      * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
2622      *         to be compared.
2623      * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2624      *          less than, equal to, or greater than {@code val}.


2704      * @see    #hashCode
2705      */
2706     @Override
2707     public boolean equals(Object x) {
2708         if (!(x instanceof BigDecimal))
2709             return false;
2710         BigDecimal xDec = (BigDecimal) x;
2711         if (x == this)
2712             return true;
2713         if (scale != xDec.scale)
2714             return false;
2715         long s = this.intCompact;
2716         long xs = xDec.intCompact;
2717         if (s != INFLATED) {
2718             if (xs == INFLATED)
2719                 xs = compactValFor(xDec.intVal);
2720             return xs == s;
2721         } else if (xs != INFLATED)
2722             return xs == compactValFor(this.intVal);
2723 
2724         return this.inflated().equals(xDec.inflated());
2725     }
2726 
2727     /**
2728      * Returns the minimum of this {@code BigDecimal} and
2729      * {@code val}.
2730      *
2731      * @param  val value with which the minimum is to be computed.
2732      * @return the {@code BigDecimal} whose value is the lesser of this
2733      *         {@code BigDecimal} and {@code val}.  If they are equal,
2734      *         as defined by the {@link #compareTo(BigDecimal) compareTo}
2735      *         method, {@code this} is returned.
2736      * @see    #compareTo(java.math.BigDecimal)
2737      */
2738     public BigDecimal min(BigDecimal val) {
2739         return (compareTo(val) <= 0 ? this : val);
2740     }
2741 
2742     /**
2743      * Returns the maximum of this {@code BigDecimal} and {@code val}.
2744      *


2929      *
2930      * Note that if the result of this method is passed to the
2931      * {@linkplain #BigDecimal(String) string constructor}, only the
2932      * numerical value of this {@code BigDecimal} will necessarily be
2933      * recovered; the representation of the new {@code BigDecimal}
2934      * may have a different scale.  In particular, if this
2935      * {@code BigDecimal} has a negative scale, the string resulting
2936      * from this method will have a scale of zero when processed by
2937      * the string constructor.
2938      *
2939      * (This method behaves analogously to the {@code toString}
2940      * method in 1.4 and earlier releases.)
2941      *
2942      * @return a string representation of this {@code BigDecimal}
2943      * without an exponent field.
2944      * @since 1.5
2945      * @see #toString()
2946      * @see #toEngineeringString()
2947      */
2948     public String toPlainString() {
2949         if(scale==0) {
2950             if(intCompact!=INFLATED) {
2951                 return Long.toString(intCompact);
2952             } else {
2953                 return intVal.toString();
2954             }
2955         }
2956         if(this.scale<0) { // No decimal point
2957             if(signum()==0) {
2958                 return "0";
2959             }
2960             int tailingZeros = checkScaleNonZero((-(long)scale));
2961             StringBuilder buf;
2962             if(intCompact!=INFLATED) {
2963                 buf = new StringBuilder(20+tailingZeros);
2964                 buf.append(intCompact);
2965             } else {
2966                 String str = intVal.toString();
2967                 buf = new StringBuilder(str.length()+tailingZeros);
2968                 buf.append(str);
2969             }
2970             for (int i = 0; i < tailingZeros; i++)
2971                 buf.append('0');
2972             return buf.toString();
2973         }
2974         String str ;
2975         if(intCompact!=INFLATED) {
2976             str = Long.toString(Math.abs(intCompact));
2977         } else {
2978             str = intVal.abs().toString();
2979         }
2980         return getValueString(signum(), str, scale);
2981     }
2982 
2983     /* Returns a digit.digit string */
2984     private String getValueString(int signum, String intString, int scale) {
2985         /* Insert decimal point */
2986         StringBuilder buf;
2987         int insertionPoint = intString.length() - scale;
2988         if (insertionPoint == 0) {  /* Point goes right before intVal */
2989             return (signum<0 ? "-0." : "0.") + intString;
2990         } else if (insertionPoint > 0) { /* Point goes inside intVal */
2991             buf = new StringBuilder(intString);
2992             buf.insert(insertionPoint, '.');
2993             if (signum < 0)
2994                 buf.insert(0, '-');
2995         } else { /* We must insert zeros between point and intVal */
2996             buf = new StringBuilder(3-insertionPoint + intString.length());
2997             buf.append(signum<0 ? "-0." : "0.");
2998             for (int i=0; i<-insertionPoint; i++)
2999                 buf.append('0');
3000             buf.append(intString);


3004 
3005     /**
3006      * Converts this {@code BigDecimal} to a {@code BigInteger}.
3007      * This conversion is analogous to the
3008      * <i>narrowing primitive conversion</i> from {@code double} to
3009      * {@code long} as defined in section 5.1.3 of
3010      * <cite>The Java&trade; Language Specification</cite>:
3011      * any fractional part of this
3012      * {@code BigDecimal} will be discarded.  Note that this
3013      * conversion can lose information about the precision of the
3014      * {@code BigDecimal} value.
3015      * <p>
3016      * To have an exception thrown if the conversion is inexact (in
3017      * other words if a nonzero fractional part is discarded), use the
3018      * {@link #toBigIntegerExact()} method.
3019      *
3020      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3021      */
3022     public BigInteger toBigInteger() {
3023         // force to an integer, quietly
3024         return this.setScale(0, ROUND_DOWN).inflated();
3025     }
3026 
3027     /**
3028      * Converts this {@code BigDecimal} to a {@code BigInteger},
3029      * checking for lost information.  An exception is thrown if this
3030      * {@code BigDecimal} has a nonzero fractional part.
3031      *
3032      * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3033      * @throws ArithmeticException if {@code this} has a nonzero
3034      *         fractional part.
3035      * @since  1.5
3036      */
3037     public BigInteger toBigIntegerExact() {
3038         // round to an integer, with Exception if decimal part non-0
3039         return this.setScale(0, ROUND_UNNECESSARY).inflated();
3040     }
3041 
3042     /**
3043      * Converts this {@code BigDecimal} to a {@code long}.
3044      * This conversion is analogous to the
3045      * <i>narrowing primitive conversion</i> from {@code double} to
3046      * {@code short} as defined in section 5.1.3 of
3047      * <cite>The Java&trade; Language Specification</cite>:
3048      * any fractional part of this
3049      * {@code BigDecimal} will be discarded, and if the resulting
3050      * "{@code BigInteger}" is too big to fit in a
3051      * {@code long}, only the low-order 64 bits are returned.
3052      * Note that this conversion can lose information about the
3053      * overall magnitude and precision of this {@code BigDecimal} value as well
3054      * as return a result with the opposite sign.
3055      *
3056      * @return this {@code BigDecimal} converted to a {@code long}.
3057      */
3058     public long longValue(){
3059         return (intCompact != INFLATED && scale == 0) ?


3072      * @throws ArithmeticException if {@code this} has a nonzero
3073      *         fractional part, or will not fit in a {@code long}.
3074      * @since  1.5
3075      */
3076     public long longValueExact() {
3077         if (intCompact != INFLATED && scale == 0)
3078             return intCompact;
3079         // If more than 19 digits in integer part it cannot possibly fit
3080         if ((precision() - scale) > 19) // [OK for negative scale too]
3081             throw new java.lang.ArithmeticException("Overflow");
3082         // Fastpath zero and < 1.0 numbers (the latter can be very slow
3083         // to round if very small)
3084         if (this.signum() == 0)
3085             return 0;
3086         if ((this.precision() - this.scale) <= 0)
3087             throw new ArithmeticException("Rounding necessary");
3088         // round to an integer, with Exception if decimal part non-0
3089         BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
3090         if (num.precision() >= 19) // need to check carefully
3091             LongOverflow.check(num);
3092         return num.inflated().longValue();
3093     }
3094 
3095     private static class LongOverflow {
3096         /** BigInteger equal to Long.MIN_VALUE. */
3097         private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3098 
3099         /** BigInteger equal to Long.MAX_VALUE. */
3100         private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3101 
3102         public static void check(BigDecimal num) {
3103             BigInteger intVal = num.inflated();
3104             if (intVal.compareTo(LONGMIN) < 0 ||
3105                 intVal.compareTo(LONGMAX) > 0)
3106                 throw new java.lang.ArithmeticException("Overflow");
3107         }
3108     }
3109 
3110     /**
3111      * Converts this {@code BigDecimal} to an {@code int}.
3112      * This conversion is analogous to the
3113      * <i>narrowing primitive conversion</i> from {@code double} to
3114      * {@code short} as defined in section 5.1.3 of
3115      * <cite>The Java&trade; Language Specification</cite>:
3116      * any fractional part of this
3117      * {@code BigDecimal} will be discarded, and if the resulting
3118      * "{@code BigInteger}" is too big to fit in an
3119      * {@code int}, only the low-order 32 bits are returned.
3120      * Note that this conversion can lose information about the
3121      * overall magnitude and precision of this {@code BigDecimal}
3122      * value as well as return a result with the opposite sign.
3123      *
3124      * @return this {@code BigDecimal} converted to an {@code int}.
3125      */


3189        return (byte)num;
3190     }
3191 
3192     /**
3193      * Converts this {@code BigDecimal} to a {@code float}.
3194      * This conversion is similar to the
3195      * <i>narrowing primitive conversion</i> from {@code double} to
3196      * {@code float} as defined in section 5.1.3 of
3197      * <cite>The Java&trade; Language Specification</cite>:
3198      * if this {@code BigDecimal} has too great a
3199      * magnitude to represent as a {@code float}, it will be
3200      * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3201      * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3202      * the return value is finite, this conversion can lose
3203      * information about the precision of the {@code BigDecimal}
3204      * value.
3205      *
3206      * @return this {@code BigDecimal} converted to a {@code float}.
3207      */
3208     public float floatValue(){
3209         if(intCompact != INFLATED) {
3210             if (scale == 0) {
3211                 return (float)intCompact;
3212             } else {
3213                 /*
3214                  * If both intCompact and the scale can be exactly
3215                  * represented as float values, perform a single float
3216                  * multiply or divide to compute the (properly
3217                  * rounded) result.
3218                  */
3219                 if (Math.abs(intCompact) < 1L<<22 ) {
3220                     // Don't have too guard against
3221                     // Math.abs(MIN_VALUE) because of outer check
3222                     // against INFLATED.
3223                     if (scale > 0 && scale < float10pow.length) {
3224                         return (float)intCompact / float10pow[scale];
3225                     } else if (scale < 0 && scale > -float10pow.length) {
3226                         return (float)intCompact * float10pow[-scale];
3227                     }
3228                 }
3229             }
3230         }
3231         // Somewhat inefficient, but guaranteed to work.
3232         return Float.parseFloat(this.toString());
3233     }
3234 
3235     /**
3236      * Converts this {@code BigDecimal} to a {@code double}.
3237      * This conversion is similar to the
3238      * <i>narrowing primitive conversion</i> from {@code double} to
3239      * {@code float} as defined in section 5.1.3 of
3240      * <cite>The Java&trade; Language Specification</cite>:
3241      * if this {@code BigDecimal} has too great a
3242      * magnitude represent as a {@code double}, it will be
3243      * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3244      * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3245      * the return value is finite, this conversion can lose
3246      * information about the precision of the {@code BigDecimal}
3247      * value.
3248      *
3249      * @return this {@code BigDecimal} converted to a {@code double}.
3250      */
3251     public double doubleValue(){
3252         if(intCompact != INFLATED) {
3253             if (scale == 0) {
3254                 return (double)intCompact;
3255             } else {
3256                 /*
3257                  * If both intCompact and the scale can be exactly
3258                  * represented as double values, perform a single
3259                  * double multiply or divide to compute the (properly
3260                  * rounded) result.
3261                  */
3262                 if (Math.abs(intCompact) < 1L<<52 ) {
3263                     // Don't have too guard against
3264                     // Math.abs(MIN_VALUE) because of outer check
3265                     // against INFLATED.
3266                     if (scale > 0 && scale < double10pow.length) {
3267                         return (double)intCompact / double10pow[scale];
3268                     } else if (scale < 0 && scale > -double10pow.length) {
3269                         return (double)intCompact * double10pow[-scale];
3270                     }
3271                 }
3272             }
3273         }
3274         // Somewhat inefficient, but guaranteed to work.
3275         return Double.parseDouble(this.toString());
3276     }
3277 
3278     /**
3279      * Powers of 10 which can be represented exactly in {@code
3280      * double}.
3281      */
3282     private static final double double10pow[] = {
3283         1.0e0,  1.0e1,  1.0e2,  1.0e3,  1.0e4,  1.0e5,
3284         1.0e6,  1.0e7,  1.0e8,  1.0e9,  1.0e10, 1.0e11,
3285         1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3286         1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3287     };
3288 
3289     /**
3290      * Powers of 10 which can be represented exactly in {@code
3291      * float}.
3292      */
3293     private static final float float10pow[] = {
3294         1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3295         1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3296     };
3297 
3298     /**
3299      * Returns the size of an ulp, a unit in the last place, of this
3300      * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3301      * value is the positive distance between this value and the
3302      * {@code BigDecimal} value next larger in magnitude with the
3303      * same number of digits.  An ulp of a zero value is numerically
3304      * equal to 1 with the scale of {@code this}.  The result is
3305      * stored with the same scale as {@code this} so the result
3306      * for zero and nonzero values is equal to {@code [1,
3307      * this.scale()]}.
3308      *
3309      * @return the size of an ulp of {@code this}
3310      * @since 1.5
3311      */
3312     public BigDecimal ulp() {
3313         return BigDecimal.valueOf(1, this.scale(), 1);
3314     }
3315 

3316     // Private class to build a string representation for BigDecimal object.
3317     // "StringBuilderHelper" is constructed as a thread local variable so it is
3318     // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3319     // representation of BigDecimal. The cmpCharArray holds all the characters for
3320     // the compact representation of BigDecimal (except for '-' sign' if it is
3321     // negative) if its intCompact field is not INFLATED. It is shared by all
3322     // calls to toString() and its variants in that particular thread.
3323     static class StringBuilderHelper {
3324         final StringBuilder sb;    // Placeholder for BigDecimal string
3325         final char[] cmpCharArray; // character array to place the intCompact
3326 
3327         StringBuilderHelper() {
3328             sb = new StringBuilder();
3329             // All non negative longs can be made to fit into 19 character array.
3330             cmpCharArray = new char[19];
3331         }
3332 
3333         // Accessors.
3334         StringBuilder getStringBuilder() {
3335             sb.setLength(0);


3409             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3410             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3411             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3412         };
3413     }
3414 
3415     /**
3416      * Lay out this {@code BigDecimal} into a {@code char[]} array.
3417      * The Java 1.2 equivalent to this was called {@code getValueString}.
3418      *
3419      * @param  sci {@code true} for Scientific exponential notation;
3420      *          {@code false} for Engineering
3421      * @return string with canonical string representation of this
3422      *         {@code BigDecimal}
3423      */
3424     private String layoutChars(boolean sci) {
3425         if (scale == 0)                      // zero scale is trivial
3426             return (intCompact != INFLATED) ?
3427                 Long.toString(intCompact):
3428                 intVal.toString();
3429         if (scale == 2  &&
3430             intCompact >= 0 && intCompact < Integer.MAX_VALUE) {
3431             // currency fast path
3432             int lowInt = (int)intCompact % 100;
3433             int highInt = (int)intCompact / 100;
3434             return (Integer.toString(highInt) + '.' +
3435                     StringBuilderHelper.DIGIT_TENS[lowInt] +
3436                     StringBuilderHelper.DIGIT_ONES[lowInt]) ;
3437         }
3438 
3439         StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
3440         char[] coeff;
3441         int offset;  // offset is the starting index for coeff array
3442         // Get the significand as an absolute value
3443         if (intCompact != INFLATED) {
3444             offset = sbHelper.putIntCompact(Math.abs(intCompact));
3445             coeff  = sbHelper.getCompactCharArray();
3446         } else {
3447             offset = 0;
3448             coeff  = intVal.abs().toString().toCharArray();
3449         }
3450 
3451         // Construct a buffer, with sufficient capacity for all cases.
3452         // If E-notation is needed, length will be: +1 if negative, +1
3453         // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3454         // Otherwise it could have +1 if negative, plus leading "0.00000"
3455         StringBuilder buf = sbHelper.getStringBuilder();
3456         if (signum() < 0)             // prefix '-' if negative
3457             buf.append('-');


3527      * @param  n the power of ten to be returned (>=0)
3528      * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3529      */
3530     private static BigInteger bigTenToThe(int n) {
3531         if (n < 0)
3532             return BigInteger.ZERO;
3533 
3534         if (n < BIG_TEN_POWERS_TABLE_MAX) {
3535             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3536             if (n < pows.length)
3537                 return pows[n];
3538             else
3539                 return expandBigIntegerTenPowers(n);
3540         }
3541         // BigInteger.pow is slow, so make 10**n by constructing a
3542         // BigInteger from a character string (still not very fast)
3543         char tenpow[] = new char[n + 1];
3544         tenpow[0] = '1';
3545         for (int i = 1; i <= n; i++)
3546             tenpow[i] = '0';
3547         return new BigInteger(tenpow,1, tenpow.length);
3548     }
3549 
3550     /**
3551      * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3552      *
3553      * @param n the power of ten to be returned (>=0)
3554      * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3555      *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
3556      *         expanded to the size greater than n.
3557      */
3558     private static BigInteger expandBigIntegerTenPowers(int n) {
3559         synchronized(BigDecimal.class) {
3560             BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3561             int curLen = pows.length;
3562             // The following comparison and the above synchronized statement is
3563             // to prevent multiple threads from expanding the same array.
3564             if (curLen <= n) {
3565                 int newLen = curLen << 1;
3566                 while (newLen <= n)
3567                     newLen <<= 1;


3583         10,                    // 1 / 10^1
3584         100,                   // 2 / 10^2
3585         1000,                  // 3 / 10^3
3586         10000,                 // 4 / 10^4
3587         100000,                // 5 / 10^5
3588         1000000,               // 6 / 10^6
3589         10000000,              // 7 / 10^7
3590         100000000,             // 8 / 10^8
3591         1000000000,            // 9 / 10^9
3592         10000000000L,          // 10 / 10^10
3593         100000000000L,         // 11 / 10^11
3594         1000000000000L,        // 12 / 10^12
3595         10000000000000L,       // 13 / 10^13
3596         100000000000000L,      // 14 / 10^14
3597         1000000000000000L,     // 15 / 10^15
3598         10000000000000000L,    // 16 / 10^16
3599         100000000000000000L,   // 17 / 10^17
3600         1000000000000000000L   // 18 / 10^18
3601     };
3602 
3603     private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {
3604         BigInteger.ONE,
3605         BigInteger.valueOf(10),
3606         BigInteger.valueOf(100),
3607         BigInteger.valueOf(1000),
3608         BigInteger.valueOf(10000),
3609         BigInteger.valueOf(100000),
3610         BigInteger.valueOf(1000000),
3611         BigInteger.valueOf(10000000),
3612         BigInteger.valueOf(100000000),
3613         BigInteger.valueOf(1000000000),
3614         BigInteger.valueOf(10000000000L),
3615         BigInteger.valueOf(100000000000L),
3616         BigInteger.valueOf(1000000000000L),
3617         BigInteger.valueOf(10000000000000L),
3618         BigInteger.valueOf(100000000000000L),
3619         BigInteger.valueOf(1000000000000000L),
3620         BigInteger.valueOf(10000000000000000L),
3621         BigInteger.valueOf(100000000000000000L),
3622         BigInteger.valueOf(1000000000000000000L)
3623     };
3624 
3625     private static final int BIG_TEN_POWERS_TABLE_INITLEN =
3626         BIG_TEN_POWERS_TABLE.length;
3627     private static final int BIG_TEN_POWERS_TABLE_MAX =
3628         16 * BIG_TEN_POWERS_TABLE_INITLEN;
3629 
3630     private static final long THRESHOLDS_TABLE[] = {
3631         Long.MAX_VALUE,                     // 0
3632         Long.MAX_VALUE/10L,                 // 1


3657         if (val == 0 || n <= 0)
3658             return val;
3659         long[] tab = LONG_TEN_POWERS_TABLE;
3660         long[] bounds = THRESHOLDS_TABLE;
3661         if (n < tab.length && n < bounds.length) {
3662             long tenpower = tab[n];
3663             if (val == 1)
3664                 return tenpower;
3665             if (Math.abs(val) <= bounds[n])
3666                 return val * tenpower;
3667         }
3668         return INFLATED;
3669     }
3670 
3671     /**
3672      * Compute this * 10 ^ n.
3673      * Needed mainly to allow special casing to trap zero value
3674      */
3675     private BigInteger bigMultiplyPowerTen(int n) {
3676         if (n <= 0)
3677             return this.inflated();
3678 
3679         if (intCompact != INFLATED)
3680             return bigTenToThe(n).multiply(intCompact);
3681         else
3682             return intVal.multiply(bigTenToThe(n));
3683     }
3684 
3685     /**
3686      * Returns appropriate BigInteger from intVal field if intVal is
3687      * null, i.e. the compact representation is in use.
3688      */
3689     private BigInteger inflated() {
3690         if (intVal == null) {
3691             return BigInteger.valueOf(intCompact);
3692         }
3693         return intVal;
3694     }
3695 
3696     /**
3697      * Match the scales of two {@code BigDecimal}s to align their
3698      * least significant digits.
3699      *
3700      * <p>If the scales of val[0] and val[1] differ, rescale
3701      * (non-destructively) the lower-scaled {@code BigDecimal} so
3702      * they match.  That is, the lower-scaled reference will be
3703      * replaced by a reference to a new object with the same scale as
3704      * the other {@code BigDecimal}.
3705      *
3706      * @param  val array of two elements referring to the two
3707      *         {@code BigDecimal}s to be aligned.
3708      */
3709     private static void matchScale(BigDecimal[] val) {
3710         if (val[0].scale == val[1].scale) {
3711             return;
3712         } else if (val[0].scale < val[1].scale) {
3713             val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3714         } else if (val[1].scale < val[0].scale) {
3715             val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3716         }
3717     }
3718 
3719     private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
3720     private static final long intCompactOffset;
3721     private static final long intValOffset;
3722     static {
3723         try {
3724             intCompactOffset = unsafe.objectFieldOffset
3725                 (BigDecimal.class.getDeclaredField("intCompact"));
3726             intValOffset = unsafe.objectFieldOffset
3727                 (BigDecimal.class.getDeclaredField("intVal"));
3728         } catch (Exception ex) {
3729             throw new Error(ex);
3730         }
3731     }
3732 
3733     private void setIntCompactVolatile(long val) {
3734         unsafe.putLongVolatile(this, intCompactOffset, val);
3735     }
3736 
3737     private void setIntValVolatile(BigInteger val) {
3738         unsafe.putObjectVolatile(this, intValOffset, val);
3739     }
3740 
3741     /**
3742      * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3743      * deserialize it).
3744      *
3745      * @param s the stream being read.
3746      */
3747     private void readObject(java.io.ObjectInputStream s)
3748         throws java.io.IOException, ClassNotFoundException {
3749         // Read in all fields
3750         s.defaultReadObject();
3751         // validate possibly bad fields
3752         if (intVal == null) {
3753             String message = "BigDecimal: null intVal in stream";
3754             throw new java.io.StreamCorruptedException(message);
3755         // [all values of scale are now allowed]
3756         }
3757         setIntCompactVolatile(compactValFor(intVal));
3758     }
3759 
3760    /**
3761     * Serialize this {@code BigDecimal} to the stream in question
3762     *
3763     * @param s the stream to serialize to.
3764     */
3765    private void writeObject(java.io.ObjectOutputStream s)
3766        throws java.io.IOException {
3767        // Must inflate to maintain compatible serial form.
3768        if (this.intVal == null)
3769            this.setIntValVolatile(BigInteger.valueOf(this.intCompact));
3770        // Could reset intVal back to null if it has to be set.
3771        s.defaultWriteObject();
3772    }
3773 

3774     /**
3775      * Returns the length of the absolute value of a {@code long}, in decimal
3776      * digits.
3777      *
3778      * @param x the {@code long}
3779      * @return the length of the unscaled value, in deciaml digits.
3780      */
3781     static int longDigitLength(long x) {
3782         /*
3783          * As described in "Bit Twiddling Hacks" by Sean Anderson,
3784          * (http://graphics.stanford.edu/~seander/bithacks.html)
3785          * integer log 10 of x is within 1 of (1233/4096)* (1 +
3786          * integer log 2 of x). The fraction 1233/4096 approximates
3787          * log10(2). So we first do a version of log2 (a variant of
3788          * Long class with pre-checks and opposite directionality) and
3789          * then scale and check against powers table. This is a little
3790          * simpler in present context than the version in Hacker's
3791          * Delight sec 11-4. Adding one to bit length allows comparing
3792          * downward from the LONG_TEN_POWERS_TABLE that we need
3793          * anyway.
3794          */
3795         assert x != BigDecimal.INFLATED;
3796         if (x < 0)
3797             x = -x;
3798         if (x < 10) // must screen for 0, might as well 10
3799             return 1;
3800         int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;







3801         long[] tab = LONG_TEN_POWERS_TABLE;
3802         // if r >= length, must have max possible digits for long
3803         return (r >= tab.length || x < tab[r]) ? r : r + 1;
3804     }
3805 
3806     /**
3807      * Returns the length of the absolute value of a BigInteger, in
3808      * decimal digits.
3809      *
3810      * @param b the BigInteger
3811      * @return the length of the unscaled value, in decimal digits
3812      */
3813     private static int bigDigitLength(BigInteger b) {
3814         /*
3815          * Same idea as the long version, but we need a better
3816          * approximation of log10(2). Using 646456993/2^31
3817          * is accurate up to max possible reported bitLength.
3818          */
3819         if (b.signum == 0)
3820             return 1;
3821         int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3822         return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3823     }
3824 



































3825     /**
3826      * Check a scale for Underflow or Overflow.  If this BigDecimal is
3827      * nonzero, throw an exception if the scale is outof range. If this
3828      * is zero, saturate the scale to the extreme value of the right
3829      * sign if the scale is out of range.
3830      *
3831      * @param val The new scale.
3832      * @throws ArithmeticException (overflow or underflow) if the new
3833      *         scale is out of range.
3834      * @return validated scale as an int.
3835      */
3836     private int checkScale(long val) {
3837         int asInt = (int)val;
3838         if (asInt != val) {
3839             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3840             BigInteger b;
3841             if (intCompact != 0 &&
3842                 ((b = intVal) == null || b.signum() != 0))
3843                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3844         }
3845         return asInt;
3846     }
3847 
3848    /**



































































3849      * Returns the compact value for given {@code BigInteger}, or
3850      * INFLATED if too big. Relies on internal representation of
3851      * {@code BigInteger}.
3852      */
3853     private static long compactValFor(BigInteger b) {
3854         int[] m = b.mag;
3855         int len = m.length;
3856         if (len == 0)
3857             return 0;
3858         int d = m[0];
3859         if (len > 2 || (len == 2 && d < 0))
3860             return INFLATED;
3861 
3862         long u = (len == 2)?
3863             (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3864             (((long)d)   & LONG_MASK);
3865         return (b.signum < 0)? -u : u;
3866     }
3867 
3868     private static int longCompareMagnitude(long x, long y) {


3920                 print("audit", this);
3921                 throw new AssertionError("precision mismatch");
3922             }
3923         } else {
3924             if (intVal != null) {
3925                 long val = intVal.longValue();
3926                 if (val != intCompact) {
3927                     print("audit", this);
3928                     throw new AssertionError("Inconsistent state, intCompact=" +
3929                                              intCompact + "\t intVal=" + val);
3930                 }
3931             }
3932             // Check precision
3933             if (precision > 0 && precision != longDigitLength(intCompact)) {
3934                 print("audit", this);
3935                 throw new AssertionError("precision mismatch");
3936             }
3937         }
3938         return this;
3939     }
3940 
3941     /* the same as checkScale where value!=0 */
3942     private static int checkScaleNonZero(long val) {
3943         int asInt = (int)val;
3944         if (asInt != val) {
3945             throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3946         }
3947         return asInt;
3948     }
3949 
3950     private static int checkScale(long intCompact, long val) {
3951         int asInt = (int)val;
3952         if (asInt != val) {
3953             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3954             if (intCompact != 0)
3955                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3956         }
3957         return asInt;
3958     }
3959 
3960     private static int checkScale(BigInteger intVal, long val) {
3961         int asInt = (int)val;
3962         if (asInt != val) {
3963             asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3964             if (intVal.signum() != 0)
3965                 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3966         }
3967         return asInt;
3968     }
3969 
3970     /**
3971      * Returns a {@code BigDecimal} rounded according to the MathContext
3972      * settings;
3973      * If rounding is needed a new {@code BigDecimal} is created and returned.
3974      *
3975      * @param val the value to be rounded
3976      * @param mc the context to use.
3977      * @return a {@code BigDecimal} rounded according to the MathContext
3978      *         settings.  May return {@code value}, if no rounding needed.
3979      * @throws ArithmeticException if the rounding mode is
3980      *         {@code RoundingMode.UNNECESSARY} and the
3981      *         result is inexact.
3982      */
3983     private static BigDecimal doRound(BigDecimal val, MathContext mc) {
3984         int mcp = mc.precision;
3985         boolean wasDivided = false;
3986         if (mcp > 0) {
3987             BigInteger intVal = val.intVal;
3988             long compactVal = val.intCompact;
3989             int scale = val.scale;
3990             int prec = val.precision();
3991             int mode = mc.roundingMode.oldMode;
3992             int drop;
3993             if (compactVal == INFLATED) {
3994                 drop = prec - mcp;
3995                 while (drop > 0) {
3996                     scale = checkScaleNonZero((long) scale - drop);
3997                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
3998                     wasDivided = true;
3999                     compactVal = compactValFor(intVal);
4000                     if (compactVal != INFLATED) {
4001                         prec = longDigitLength(compactVal);
4002                         break;
4003                     }
4004                     prec = bigDigitLength(intVal);
4005                     drop = prec - mcp;
4006                 }
4007             }
4008             if (compactVal != INFLATED) {
4009                 drop = prec - mcp;  // drop can't be more than 18
4010                 while (drop > 0) {
4011                     scale = checkScaleNonZero((long) scale - drop);
4012                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4013                     wasDivided = true;
4014                     prec = longDigitLength(compactVal);
4015                     drop = prec - mcp;
4016                     intVal = null;
4017                 }
4018             }
4019             return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;
4020         }
4021         return val;
4022     }
4023 
4024     /*
4025      * Returns a {@code BigDecimal} created from {@code long} value with
4026      * given scale rounded according to the MathContext settings
4027      */
4028     private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {
4029         int mcp = mc.precision;
4030         if (mcp > 0 && mcp < 19) {
4031             int prec = longDigitLength(compactVal);
4032             int drop = prec - mcp;  // drop can't be more than 18
4033             while (drop > 0) {
4034                 scale = checkScaleNonZero((long) scale - drop);
4035                 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4036                 prec = longDigitLength(compactVal);
4037                 drop = prec - mcp;
4038             }
4039             return valueOf(compactVal, scale, prec);
4040         }
4041         return valueOf(compactVal, scale);
4042     }
4043 
4044     /*
4045      * Returns a {@code BigDecimal} created from {@code BigInteger} value with
4046      * given scale rounded according to the MathContext settings
4047      */
4048     private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {
4049         int mcp = mc.precision;
4050         int prec = 0;
4051         if (mcp > 0) {
4052             long compactVal = compactValFor(intVal);
4053             int mode = mc.roundingMode.oldMode;
4054             int drop;
4055             if (compactVal == INFLATED) {
4056                 prec = bigDigitLength(intVal);
4057                 drop = prec - mcp;
4058                 while (drop > 0) {
4059                     scale = checkScaleNonZero((long) scale - drop);
4060                     intVal = divideAndRoundByTenPow(intVal, drop, mode);
4061                     compactVal = compactValFor(intVal);
4062                     if (compactVal != INFLATED) {
4063                         break;
4064                     }
4065                     prec = bigDigitLength(intVal);
4066                     drop = prec - mcp;
4067                 }
4068             }
4069             if (compactVal != INFLATED) {
4070                 prec = longDigitLength(compactVal);
4071                 drop = prec - mcp;     // drop can't be more than 18
4072                 while (drop > 0) {
4073                     scale = checkScaleNonZero((long) scale - drop);
4074                     compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
4075                     prec = longDigitLength(compactVal);
4076                     drop = prec - mcp;
4077                 }
4078                 return valueOf(compactVal,scale,prec);
4079             }
4080         }
4081         return new BigDecimal(intVal,INFLATED,scale,prec);
4082     }
4083 
4084     /*
4085      * Divides {@code BigInteger} value by ten power.
4086      */
4087     private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {
4088         if (tenPow < LONG_TEN_POWERS_TABLE.length)
4089             intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);
4090         else
4091             intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);
4092         return intVal;
4093     }
4094 
4095     /**
4096      * Internally used for division operation for division {@code long} by
4097      * {@code long}.
4098      * The returned {@code BigDecimal} object is the quotient whose scale is set
4099      * to the passed in scale. If the remainder is not zero, it will be rounded
4100      * based on the passed in roundingMode. Also, if the remainder is zero and
4101      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4102      * trailing zeros of the result is stripped to match the preferredScale.
4103      */
4104     private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,
4105                                              int preferredScale) {
4106 
4107         int qsign; // quotient sign
4108         long q = ldividend / ldivisor; // store quotient in long
4109         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4110             return valueOf(q, scale);
4111         long r = ldividend % ldivisor; // store remainder in long
4112         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4113         if (r != 0) {
4114             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);
4115             return valueOf((increment ? q + qsign : q), scale);
4116         } else {
4117             if (preferredScale != scale)
4118                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4119             else
4120                 return valueOf(q, scale);
4121         }
4122     }
4123 
4124     /**
4125      * Divides {@code long} by {@code long} and do rounding based on the
4126      * passed in roundingMode.
4127      */
4128     private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {
4129         int qsign; // quotient sign
4130         long q = ldividend / ldivisor; // store quotient in long
4131         if (roundingMode == ROUND_DOWN)
4132             return q;
4133         long r = ldividend % ldivisor; // store remainder in long
4134         qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
4135         if (r != 0) {
4136             boolean increment = needIncrement(ldivisor, roundingMode, qsign, q,     r);
4137             return increment ? q + qsign : q;
4138         } else {
4139             return q;
4140         }
4141     }
4142 
4143     /**
4144      * Shared logic of need increment computation.
4145      */
4146     private static boolean commonNeedIncrement(int roundingMode, int qsign,
4147                                         int cmpFracHalf, boolean oddQuot) {
4148         switch(roundingMode) {
4149         case ROUND_UNNECESSARY:
4150             throw new ArithmeticException("Rounding necessary");
4151 
4152         case ROUND_UP: // Away from zero
4153             return true;
4154 
4155         case ROUND_DOWN: // Towards zero
4156             return false;
4157 
4158         case ROUND_CEILING: // Towards +infinity
4159             return qsign > 0;
4160 
4161         case ROUND_FLOOR: // Towards -infinity
4162             return qsign < 0;
4163 
4164         default: // Some kind of half-way rounding
4165             if (roundingMode == ROUND_HALF_DOWN ||
4166                 cmpFracHalf < 0 ) // We're closer to higher digit
4167                 return false;
4168             else if (roundingMode == ROUND_HALF_UP ||
4169                      cmpFracHalf > 0 ) // We're closer to lower digit
4170                 return true;
4171             else
4172                 // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
4173                 return oddQuot;
4174         }
4175     }
4176 
4177     /**
4178      * Tests if quotient has to be incremented according the roundingMode
4179      */
4180     private static boolean needIncrement(long ldivisor, int roundingMode,
4181                                          int qsign, long q, long r) {
4182         assert r != 0L;
4183 
4184         int cmpFracHalf;
4185         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4186             cmpFracHalf = 1; // 2 * r can't fit into long
4187         } else {
4188             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4189         }
4190 
4191         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4192     }
4193 
4194     /**
4195      * Divides {@code BigInteger} value by {@code long} value and
4196      * do rounding based on the passed in roundingMode.
4197      */
4198     private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4199         boolean isRemainderZero; // record remainder is zero or not
4200         int qsign; // quotient sign
4201         long r = 0; // store quotient & remainder in long
4202         MutableBigInteger mq = null; // store quotient
4203         // Descend into mutables for faster remainder checks
4204         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4205         mq = new MutableBigInteger();
4206         r = mdividend.divide(ldivisor, mq);
4207         isRemainderZero = (r == 0);
4208         qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4209         if (!isRemainderZero) {
4210             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4211                 mq.add(MutableBigInteger.ONE);
4212             }
4213         }
4214         return mq.toBigInteger(qsign);
4215     }
4216 
4217     /**
4218      * Internally used for division operation for division {@code BigInteger}
4219      * by {@code long}.
4220      * The returned {@code BigDecimal} object is the quotient whose scale is set
4221      * to the passed in scale. If the remainder is not zero, it will be rounded
4222      * based on the passed in roundingMode. Also, if the remainder is zero and
4223      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4224      * trailing zeros of the result is stripped to match the preferredScale.
4225      */
4226     private static BigDecimal divideAndRound(BigInteger bdividend,
4227                                              long ldivisor, int scale, int roundingMode, int preferredScale) {
4228         boolean isRemainderZero; // record remainder is zero or not
4229         int qsign; // quotient sign
4230         long r = 0; // store quotient & remainder in long
4231         MutableBigInteger mq = null; // store quotient
4232         // Descend into mutables for faster remainder checks
4233         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4234         mq = new MutableBigInteger();
4235         r = mdividend.divide(ldivisor, mq);
4236         isRemainderZero = (r == 0);
4237         qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4238         if (!isRemainderZero) {
4239             if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4240                 mq.add(MutableBigInteger.ONE);
4241             }
4242             return mq.toBigDecimal(qsign, scale);
4243         } else {
4244             if (preferredScale != scale) {
4245                 long compactVal = mq.toCompactValue(qsign);
4246                 if(compactVal!=INFLATED) {
4247                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4248                 }
4249                 BigInteger intVal =  mq.toBigInteger(qsign);
4250                 return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4251             } else {
4252                 return mq.toBigDecimal(qsign, scale);
4253             }
4254         }
4255     }
4256 
4257     /**
4258      * Tests if quotient has to be incremented according the roundingMode
4259      */
4260     private static boolean needIncrement(long ldivisor, int roundingMode,
4261                                          int qsign, MutableBigInteger mq, long r) {
4262         assert r != 0L;
4263 
4264         int cmpFracHalf;
4265         if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4266             cmpFracHalf = 1; // 2 * r can't fit into long
4267         } else {
4268             cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4269         }
4270 
4271         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4272     }
4273 
4274     /**
4275      * Divides {@code BigInteger} value by {@code BigInteger} value and
4276      * do rounding based on the passed in roundingMode.
4277      */
4278     private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {
4279         boolean isRemainderZero; // record remainder is zero or not
4280         int qsign; // quotient sign
4281         // Descend into mutables for faster remainder checks
4282         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4283         MutableBigInteger mq = new MutableBigInteger();
4284         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4285         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4286         isRemainderZero = mr.isZero();
4287         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4288         if (!isRemainderZero) {
4289             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4290                 mq.add(MutableBigInteger.ONE);
4291             }
4292         }
4293         return mq.toBigInteger(qsign);
4294     }
4295 
4296     /**
4297      * Internally used for division operation for division {@code BigInteger}
4298      * by {@code BigInteger}.
4299      * The returned {@code BigDecimal} object is the quotient whose scale is set
4300      * to the passed in scale. If the remainder is not zero, it will be rounded
4301      * based on the passed in roundingMode. Also, if the remainder is zero and
4302      * the last parameter, i.e. preferredScale is NOT equal to scale, the
4303      * trailing zeros of the result is stripped to match the preferredScale.
4304      */
4305     private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,
4306                                              int preferredScale) {
4307         boolean isRemainderZero; // record remainder is zero or not
4308         int qsign; // quotient sign
4309         // Descend into mutables for faster remainder checks
4310         MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4311         MutableBigInteger mq = new MutableBigInteger();
4312         MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);
4313         MutableBigInteger mr = mdividend.divide(mdivisor, mq);
4314         isRemainderZero = mr.isZero();
4315         qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
4316         if (!isRemainderZero) {
4317             if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {
4318                 mq.add(MutableBigInteger.ONE);
4319             }
4320             return mq.toBigDecimal(qsign, scale);
4321         } else {
4322             if (preferredScale != scale) {
4323                 long compactVal = mq.toCompactValue(qsign);
4324                 if (compactVal != INFLATED) {
4325                     return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4326                 }
4327                 BigInteger intVal = mq.toBigInteger(qsign);
4328                 return createAndStripZerosToMatchScale(intVal, scale, preferredScale);
4329             } else {
4330                 return mq.toBigDecimal(qsign, scale);
4331             }
4332         }
4333     }
4334 
4335     /**
4336      * Tests if quotient has to be incremented according the roundingMode
4337      */
4338     private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,
4339                                          int qsign, MutableBigInteger mq, MutableBigInteger mr) {
4340         assert !mr.isZero();
4341         int cmpFracHalf = mr.compareHalf(mdivisor);
4342         return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());
4343     }
4344 
4345     /**
4346      * Remove insignificant trailing zeros from this
4347      * {@code BigInteger} value until the preferred scale is reached or no
4348      * more zeros can be removed.  If the preferred scale is less than
4349      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4350      *
4351      * @return new {@code BigDecimal} with a scale possibly reduced
4352      * to be closed to the preferred scale.
4353      */
4354     private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {
4355         BigInteger qr[]; // quotient-remainder pair
4356         while (intVal.compareMagnitude(BigInteger.TEN) >= 0
4357                && scale > preferredScale) {
4358             if (intVal.testBit(0))
4359                 break; // odd number cannot end in 0
4360             qr = intVal.divideAndRemainder(BigInteger.TEN);
4361             if (qr[1].signum() != 0)
4362                 break; // non-0 remainder
4363             intVal = qr[0];
4364             scale = checkScale(intVal,(long) scale - 1); // could Overflow
4365         }
4366         return valueOf(intVal, scale, 0);
4367     }
4368 
4369     /**
4370      * Remove insignificant trailing zeros from this
4371      * {@code long} value until the preferred scale is reached or no
4372      * more zeros can be removed.  If the preferred scale is less than
4373      * Integer.MIN_VALUE, all the trailing zeros will be removed.
4374      *
4375      * @return new {@code BigDecimal} with a scale possibly reduced
4376      * to be closed to the preferred scale.
4377      */
4378     private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {
4379         while (Math.abs(compactVal) >= 10L && scale > preferredScale) {
4380             if ((compactVal & 1L) != 0L)
4381                 break; // odd number cannot end in 0
4382             long r = compactVal % 10L;
4383             if (r != 0L)
4384                 break; // non-0 remainder
4385             compactVal /= 10;
4386             scale = checkScale(compactVal, (long) scale - 1); // could Overflow
4387         }
4388         return valueOf(compactVal, scale);
4389     }
4390 
4391     private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {
4392         if(intCompact!=INFLATED) {
4393             return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);
4394         } else {
4395             return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,
4396                                                    scale, preferredScale);
4397         }
4398     }
4399 
4400     /*
4401      * returns INFLATED if oveflow
4402      */
4403     private static long add(long xs, long ys){
4404         long sum = xs + ys;
4405         // See "Hacker's Delight" section 2-12 for explanation of
4406         // the overflow test.
4407         if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed
4408             return sum;
4409         }
4410         return INFLATED;
4411     }
4412 
4413     private static BigDecimal add(long xs, long ys, int scale){
4414         long sum = add(xs, ys);
4415         if (sum!=INFLATED)
4416             return BigDecimal.valueOf(sum, scale);
4417         return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);
4418     }
4419 
4420     private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {
4421         long sdiff = (long) scale1 - scale2;
4422         if (sdiff == 0) {
4423             return add(xs, ys, scale1);
4424         } else if (sdiff < 0) {
4425             int raise = checkScale(xs,-sdiff);
4426             long scaledX = longMultiplyPowerTen(xs, raise);
4427             if (scaledX != INFLATED) {
4428                 return add(scaledX, ys, scale2);
4429             } else {
4430                 BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);
4431                 return ((xs^ys)>=0) ? // same sign test
4432                     new BigDecimal(bigsum, INFLATED, scale2, 0)
4433                     : valueOf(bigsum, scale2, 0);
4434             }
4435         } else {
4436             int raise = checkScale(ys,sdiff);
4437             long scaledY = longMultiplyPowerTen(ys, raise);
4438             if (scaledY != INFLATED) {
4439                 return add(xs, scaledY, scale1);
4440             } else {
4441                 BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);
4442                 return ((xs^ys)>=0) ?
4443                     new BigDecimal(bigsum, INFLATED, scale1, 0)
4444                     : valueOf(bigsum, scale1, 0);
4445             }
4446         }
4447     }
4448 
4449     private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {
4450         int rscale = scale1;
4451         long sdiff = (long)rscale - scale2;
4452         boolean sameSigns =  (Long.signum(xs) == snd.signum);
4453         BigInteger sum;
4454         if (sdiff < 0) {
4455             int raise = checkScale(xs,-sdiff);
4456             rscale = scale2;
4457             long scaledX = longMultiplyPowerTen(xs, raise);
4458             if (scaledX == INFLATED) {
4459                 sum = snd.add(bigMultiplyPowerTen(xs,raise));
4460             } else {
4461                 sum = snd.add(scaledX);
4462             }
4463         } else { //if (sdiff > 0) {
4464             int raise = checkScale(snd,sdiff);
4465             snd = bigMultiplyPowerTen(snd,raise);
4466             sum = snd.add(xs);
4467         }
4468         return (sameSigns) ?
4469             new BigDecimal(sum, INFLATED, rscale, 0) :
4470             valueOf(sum, rscale, 0);
4471     }
4472 
4473     private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {
4474         int rscale = scale1;
4475         long sdiff = (long)rscale - scale2;
4476         if (sdiff != 0) {
4477             if (sdiff < 0) {
4478                 int raise = checkScale(fst,-sdiff);
4479                 rscale = scale2;
4480                 fst = bigMultiplyPowerTen(fst,raise);
4481             } else {
4482                 int raise = checkScale(snd,sdiff);
4483                 snd = bigMultiplyPowerTen(snd,raise);
4484             }
4485         }
4486         BigInteger sum = fst.add(snd);
4487         return (fst.signum == snd.signum) ?
4488                 new BigDecimal(sum, INFLATED, rscale, 0) :
4489                 valueOf(sum, rscale, 0);
4490     }
4491 
4492     private static BigInteger bigMultiplyPowerTen(long value, int n) {
4493         if (n <= 0)
4494             return BigInteger.valueOf(value);
4495         return bigTenToThe(n).multiply(value);
4496     }
4497 
4498     private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {
4499         if (n <= 0)
4500             return value;
4501         if(n<LONG_TEN_POWERS_TABLE.length) {
4502                 return value.multiply(LONG_TEN_POWERS_TABLE[n]);
4503         }
4504         return value.multiply(bigTenToThe(n));
4505     }
4506 
4507     /**
4508      * Returns a {@code BigDecimal} whose value is {@code (xs /
4509      * ys)}, with rounding according to the context settings.
4510      *
4511      * Fast path - used only when (xscale <= yscale && yscale < 18
4512      *  && mc.presision<18) {
4513      */
4514     private static BigDecimal divideSmallFastPath(final long xs, int xscale,
4515                                                   final long ys, int yscale,
4516                                                   long preferredScale, MathContext mc) {
4517         int mcp = mc.precision;
4518         int roundingMode = mc.roundingMode.oldMode;
4519 
4520         assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);
4521         int xraise = yscale - xscale; // xraise >=0
4522         long scaledX = (xraise==0) ? xs :
4523             longMultiplyPowerTen(xs, xraise); // can't overflow here!
4524         BigDecimal quotient;
4525 
4526         int cmp = longCompareMagnitude(scaledX, ys);
4527         if(cmp > 0) { // satisfy constraint (b)
4528             yscale -= 1; // [that is, divisor *= 10]
4529             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4530             if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4531                 // assert newScale >= xscale
4532                 int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4533                 long scaledXs;
4534                 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4535                     quotient = null;
4536                     if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {
4537                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4538                     }
4539                     if(quotient==null) {
4540                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);
4541                         quotient = divideAndRound(rb, ys,
4542                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4543                     }
4544                 } else {
4545                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4546                 }
4547             } else {
4548                 int newScale = checkScaleNonZero((long) xscale - mcp);
4549                 // assert newScale >= yscale
4550                 if (newScale == yscale) { // easy case
4551                     quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4552                 } else {
4553                     int raise = checkScaleNonZero((long) newScale - yscale);
4554                     long scaledYs;
4555                     if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4556                         BigInteger rb = bigMultiplyPowerTen(ys,raise);
4557                         quotient = divideAndRound(BigInteger.valueOf(xs),
4558                                                   rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4559                     } else {
4560                         quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4561                     }
4562                 }
4563             }
4564         } else {
4565             // abs(scaledX) <= abs(ys)
4566             // result is "scaledX * 10^msp / ys"
4567             int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4568             if(cmp==0) {
4569                 // abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign
4570                 quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));
4571             } else {
4572                 // abs(scaledX) < abs(ys)
4573                 long scaledXs;
4574                 if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {
4575                     quotient = null;
4576                     if(mcp<LONG_TEN_POWERS_TABLE.length) {
4577                         quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4578                     }
4579                     if(quotient==null) {
4580                         BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);
4581                         quotient = divideAndRound(rb, ys,
4582                                                   scl, roundingMode, checkScaleNonZero(preferredScale));
4583                     }
4584                 } else {
4585                     quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4586                 }
4587             }
4588         }
4589         // doRound, here, only affects 1000000000 case.
4590         return doRound(quotient,mc);
4591     }
4592 
4593     /**
4594      * Returns a {@code BigDecimal} whose value is {@code (xs /
4595      * ys)}, with rounding according to the context settings.
4596      */
4597     private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {
4598         int mcp = mc.precision;
4599         if(xscale <= yscale && yscale < 18 && mcp<18) {
4600             return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);
4601         }
4602         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4603             yscale -= 1; // [that is, divisor *= 10]
4604         }
4605         int roundingMode = mc.roundingMode.oldMode;
4606         // In order to find out whether the divide generates the exact result,
4607         // we avoid calling the above divide method. 'quotient' holds the
4608         // return BigDecimal object whose scale will be set to 'scl'.
4609         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4610         BigDecimal quotient;
4611         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4612             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4613             long scaledXs;
4614             if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {
4615                 BigInteger rb = bigMultiplyPowerTen(xs,raise);
4616                 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4617             } else {
4618                 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4619             }
4620         } else {
4621             int newScale = checkScaleNonZero((long) xscale - mcp);
4622             // assert newScale >= yscale
4623             if (newScale == yscale) { // easy case
4624                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4625             } else {
4626                 int raise = checkScaleNonZero((long) newScale - yscale);
4627                 long scaledYs;
4628                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4629                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4630                     quotient = divideAndRound(BigInteger.valueOf(xs),
4631                                               rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4632                 } else {
4633                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4634                 }
4635             }
4636         }
4637         // doRound, here, only affects 1000000000 case.
4638         return doRound(quotient,mc);
4639     }
4640 
4641     /**
4642      * Returns a {@code BigDecimal} whose value is {@code (xs /
4643      * ys)}, with rounding according to the context settings.
4644      */
4645     private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {
4646         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4647         if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)
4648             yscale -= 1; // [that is, divisor *= 10]
4649         }
4650         int mcp = mc.precision;
4651         int roundingMode = mc.roundingMode.oldMode;
4652 
4653         // In order to find out whether the divide generates the exact result,
4654         // we avoid calling the above divide method. 'quotient' holds the
4655         // return BigDecimal object whose scale will be set to 'scl'.
4656         BigDecimal quotient;
4657         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4658         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4659             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4660             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4661             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4662         } else {
4663             int newScale = checkScaleNonZero((long) xscale - mcp);
4664             // assert newScale >= yscale
4665             if (newScale == yscale) { // easy case
4666                 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));
4667             } else {
4668                 int raise = checkScaleNonZero((long) newScale - yscale);
4669                 long scaledYs;
4670                 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {
4671                     BigInteger rb = bigMultiplyPowerTen(ys,raise);
4672                     quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4673                 } else {
4674                     quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));
4675                 }
4676             }
4677         }
4678         // doRound, here, only affects 1000000000 case.
4679         return doRound(quotient, mc);
4680     }
4681 
4682     /**
4683      * Returns a {@code BigDecimal} whose value is {@code (xs /
4684      * ys)}, with rounding according to the context settings.
4685      */
4686     private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4687         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4688         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4689             yscale -= 1; // [that is, divisor *= 10]
4690         }
4691         int mcp = mc.precision;
4692         int roundingMode = mc.roundingMode.oldMode;
4693 
4694         // In order to find out whether the divide generates the exact result,
4695         // we avoid calling the above divide method. 'quotient' holds the
4696         // return BigDecimal object whose scale will be set to 'scl'.
4697         BigDecimal quotient;
4698         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4699         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4700             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4701             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4702             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4703         } else {
4704             int newScale = checkScaleNonZero((long) xscale - mcp);
4705             int raise = checkScaleNonZero((long) newScale - yscale);
4706             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4707             quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4708         }
4709         // doRound, here, only affects 1000000000 case.
4710         return doRound(quotient, mc);
4711     }
4712 
4713     /**
4714      * Returns a {@code BigDecimal} whose value is {@code (xs /
4715      * ys)}, with rounding according to the context settings.
4716      */
4717     private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {
4718         // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4719         if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)
4720             yscale -= 1; // [that is, divisor *= 10]
4721         }
4722         int mcp = mc.precision;
4723         int roundingMode = mc.roundingMode.oldMode;
4724 
4725         // In order to find out whether the divide generates the exact result,
4726         // we avoid calling the above divide method. 'quotient' holds the
4727         // return BigDecimal object whose scale will be set to 'scl'.
4728         BigDecimal quotient;
4729         int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);
4730         if (checkScaleNonZero((long) mcp + yscale) > xscale) {
4731             int raise = checkScaleNonZero((long) mcp + yscale - xscale);
4732             BigInteger rb = bigMultiplyPowerTen(xs,raise);
4733             quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));
4734         } else {
4735             int newScale = checkScaleNonZero((long) xscale - mcp);
4736             int raise = checkScaleNonZero((long) newScale - yscale);
4737             BigInteger rb = bigMultiplyPowerTen(ys,raise);
4738             quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));
4739         }
4740         // doRound, here, only affects 1000000000 case.
4741         return doRound(quotient, mc);
4742     }
4743 
4744     /*
4745      * performs divideAndRound for (dividend0*dividend1, divisor)
4746      * returns null if quotient can't fit into long value;
4747      */
4748     private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,
4749                                                      int preferredScale) {
4750         int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);
4751         dividend0 = Math.abs(dividend0);
4752         dividend1 = Math.abs(dividend1);
4753         divisor = Math.abs(divisor);
4754         // multiply dividend0 * dividend1
4755         long d0_hi = dividend0 >>> 32;
4756         long d0_lo = dividend0 & LONG_MASK;
4757         long d1_hi = dividend1 >>> 32;
4758         long d1_lo = dividend1 & LONG_MASK;
4759         long product = d0_lo * d1_lo;
4760         long d0 = product & LONG_MASK;
4761         long d1 = product >>> 32;
4762         product = d0_hi * d1_lo + d1;
4763         d1 = product & LONG_MASK;
4764         long d2 = product >>> 32;
4765         product = d0_lo * d1_hi + d1;
4766         d1 = product & LONG_MASK;
4767         d2 += product >>> 32;
4768         long d3 = d2>>>32;
4769         d2 &= LONG_MASK;
4770         product = d0_hi*d1_hi + d2;
4771         d2 = product & LONG_MASK;
4772         d3 = ((product>>>32) + d3) & LONG_MASK;
4773         final long dividendHi = make64(d3,d2);
4774         final long dividendLo = make64(d1,d0);
4775         // divide
4776         return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);
4777     }
4778 
4779     private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).
4780 
4781     /*
4782      * divideAndRound 128-bit value by long divisor.
4783      * returns null if quotient can't fit into long value;
4784      * Specialized version of Knuth's division
4785      */
4786     private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,
4787                                                 int scale, int roundingMode, int preferredScale) {
4788         if (dividendHi >= divisor) {
4789             return null;
4790         }
4791         final int shift = Long.numberOfLeadingZeros(divisor);
4792         divisor <<= shift;
4793 
4794         final long v1 = divisor >>> 32;
4795         final long v0 = divisor & LONG_MASK;
4796 
4797         long q1, q0;
4798         long r_tmp;
4799 
4800         long tmp = dividendLo << shift;
4801         long u1 = tmp >>> 32;
4802         long u0 = tmp & LONG_MASK;
4803 
4804         tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);
4805         long u2 = tmp & LONG_MASK;
4806         tmp = divWord(tmp,v1);
4807         q1 = tmp & LONG_MASK;
4808         r_tmp = tmp >>> 32;
4809         while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {
4810             q1--;
4811             r_tmp += v1;
4812             if (r_tmp >= DIV_NUM_BASE)
4813                 break;
4814         }
4815         tmp = mulsub(u2,u1,v1,v0,q1);
4816         u1 = tmp & LONG_MASK;
4817         tmp = divWord(tmp,v1);
4818         q0 = tmp & LONG_MASK;
4819         r_tmp = tmp >>> 32;
4820         while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {
4821             q0--;
4822             r_tmp += v1;
4823             if (r_tmp >= DIV_NUM_BASE)
4824                 break;
4825         }
4826         if((int)q1 < 0) {
4827             // result (which is positive and unsigned here)
4828             // can't fit into long due to sign bit is used for value
4829             MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});
4830             if (roundingMode == ROUND_DOWN && scale == preferredScale) {
4831                 return mq.toBigDecimal(sign, scale);
4832             }
4833             long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4834             if (r != 0) {
4835                 if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){
4836                     mq.add(MutableBigInteger.ONE);
4837                 }
4838                 return mq.toBigDecimal(sign, scale);
4839             } else {
4840                 if (preferredScale != scale) {
4841                     BigInteger intVal =  mq.toBigInteger(sign);
4842                     return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4843                 } else {
4844                     return mq.toBigDecimal(sign, scale);
4845                 }
4846             }
4847         }
4848         long q = make64(q1,q0);
4849         q*=sign;
4850         if (roundingMode == ROUND_DOWN && scale == preferredScale)
4851             return valueOf(q, scale);
4852         long r = mulsub(u1, u0, v1, v0, q0) >>> shift;
4853         if (r != 0) {
4854             boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);
4855             return valueOf((increment ? q + sign : q), scale);
4856         } else {
4857             if (preferredScale != scale) {
4858                 return createAndStripZerosToMatchScale(q, scale, preferredScale);
4859             } else {
4860                 return valueOf(q, scale);
4861             }
4862         }
4863     }
4864 
4865     /*
4866      * calculate divideAndRound for ldividend*10^raise / divisor
4867      * when abs(dividend)==abs(divisor);
4868      */
4869     private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {
4870         if (scale > preferredScale) {
4871             int diff = scale - preferredScale;
4872             if(diff < raise) {
4873                 return scaledTenPow(raise - diff, qsign, preferredScale);
4874             } else {
4875                 return valueOf(qsign,scale-raise);
4876             }
4877         } else {
4878             return scaledTenPow(raise, qsign, scale);
4879         }
4880     }
4881 
4882     static BigDecimal scaledTenPow(int n, int sign, int scale) {
4883         if (n < LONG_TEN_POWERS_TABLE.length)
4884             return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);
4885         else {
4886             BigInteger unscaledVal = bigTenToThe(n);
4887             if(sign==-1) {
4888                 unscaledVal = unscaledVal.negate();
4889             }
4890             return new BigDecimal(unscaledVal, INFLATED, scale, n+1);
4891         }
4892     }
4893 
4894     private static long divWord(long n, long dLong) {
4895         long r;
4896         long q;
4897         if (dLong == 1) {
4898             q = (int)n;
4899             return (q & LONG_MASK);
4900         }
4901         // Approximate the quotient and remainder
4902         q = (n >>> 1) / (dLong >>> 1);
4903         r = n - q*dLong;
4904 
4905         // Correct the approximation
4906         while (r < 0) {
4907             r += dLong;
4908             q--;
4909         }
4910         while (r >= dLong) {
4911             r -= dLong;
4912             q++;
4913         }
4914         // n - q*dlong == r && 0 <= r <dLong, hence we're done.
4915         return (r << 32) | (q & LONG_MASK);
4916     }
4917 
4918     private static long make64(long hi, long lo) {
4919         return hi<<32 | lo;
4920     }
4921 
4922     private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {
4923         long tmp = u0 - q0*v0;
4924         return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);
4925     }
4926 
4927     private static boolean unsignedLongCompare(long one, long two) {
4928         return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
4929     }
4930 
4931     private static boolean unsignedLongCompareEq(long one, long two) {
4932         return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);
4933     }
4934 
4935 
4936     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4937     private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {
4938         // assert xs!=0 && ys!=0
4939         int sdiff = xscale - yscale;
4940         if (sdiff != 0) {
4941             if (sdiff < 0) {
4942                 xs = longMultiplyPowerTen(xs, -sdiff);
4943             } else { // sdiff > 0
4944                 ys = longMultiplyPowerTen(ys, sdiff);
4945             }
4946         }
4947         if (xs != INFLATED)
4948             return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
4949         else
4950             return 1;
4951     }
4952 
4953     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4954     private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {
4955         // assert "ys can't be represented as long"
4956         if (xs == 0)
4957             return -1;
4958         int sdiff = xscale - yscale;
4959         if (sdiff < 0) {
4960             if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {
4961                 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
4962             }
4963         }
4964         return -1;
4965     }
4966 
4967     // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]
4968     private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {
4969         int sdiff = xscale - yscale;
4970         if (sdiff < 0) {
4971             return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);
4972         } else { // sdiff >= 0
4973             return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));
4974         }
4975     }
4976 
4977     private static long multiply(long x, long y){
4978                 long product = x * y;
4979         long ax = Math.abs(x);
4980         long ay = Math.abs(y);
4981         if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){
4982                         return product;
4983                 }
4984         return INFLATED;
4985     }
4986 
4987     private static BigDecimal multiply(long x, long y, int scale) {
4988         long product = multiply(x, y);
4989         if(product!=INFLATED) {
4990             return valueOf(product,scale);
4991         }
4992         return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);
4993     }
4994 
4995     private static BigDecimal multiply(long x, BigInteger y, int scale) {
4996         if(x==0) {
4997             return zeroValueOf(scale);
4998         }
4999         return new BigDecimal(y.multiply(x),INFLATED,scale,0);
5000     }
5001 
5002     private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {
5003         return new BigDecimal(x.multiply(y),INFLATED,scale,0);
5004     }
5005 
5006     /**
5007      * Multiplies two long values and rounds according {@code MathContext}
5008      */
5009     private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {
5010         long product = multiply(x, y);
5011         if(product!=INFLATED) {
5012             return doRound(product, scale, mc);
5013         }
5014         // attempt to do it in 128 bits
5015         int rsign = 1;
5016         if(x < 0) {
5017             x = -x;
5018             rsign = -1;
5019         }
5020         if(y < 0) {
5021             y = -y;
5022             rsign *= -1;
5023         }
5024         // multiply dividend0 * dividend1
5025         long m0_hi = x >>> 32;
5026         long m0_lo = x & LONG_MASK;
5027         long m1_hi = y >>> 32;
5028         long m1_lo = y & LONG_MASK;
5029         product = m0_lo * m1_lo;
5030         long m0 = product & LONG_MASK;
5031         long m1 = product >>> 32;
5032         product = m0_hi * m1_lo + m1;
5033         m1 = product & LONG_MASK;
5034         long m2 = product >>> 32;
5035         product = m0_lo * m1_hi + m1;
5036         m1 = product & LONG_MASK;
5037         m2 += product >>> 32;
5038         long m3 = m2>>>32;
5039         m2 &= LONG_MASK;
5040         product = m0_hi*m1_hi + m2;
5041         m2 = product & LONG_MASK;
5042         m3 = ((product>>>32) + m3) & LONG_MASK;
5043         final long mHi = make64(m3,m2);
5044         final long mLo = make64(m1,m0);
5045         BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);
5046         if(res!=null) {
5047             return res;
5048         }
5049         res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);
5050         return doRound(res,mc);
5051     }
5052 
5053     private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {
5054         if(x==0) {
5055             return zeroValueOf(scale);
5056         }
5057         return doRound(y.multiply(x), scale, mc);
5058     }
5059 
5060     private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {
5061         return doRound(x.multiply(y), scale, mc);
5062     }
5063 
5064     /**
5065      * rounds 128-bit value according {@code MathContext}
5066      * returns null if result can't be repsented as compact BigDecimal.
5067      */
5068     private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
5069         int mcp = mc.precision;
5070         int drop;
5071         BigDecimal res = null;
5072         if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
5073             scale = checkScaleNonZero((long)scale - drop);
5074             res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
5075         }
5076         if(res!=null) {
5077             return doRound(res,mc);
5078         }
5079         return null;
5080     }
5081 
5082     private static final long[][] LONGLONG_TEN_POWERS_TABLE = {
5083         {   0L, 0x8AC7230489E80000L },  //10^19
5084         {       0x5L, 0x6bc75e2d63100000L },  //10^20
5085         {       0x36L, 0x35c9adc5dea00000L },  //10^21
5086         {       0x21eL, 0x19e0c9bab2400000L  },  //10^22
5087         {       0x152dL, 0x02c7e14af6800000L  },  //10^23
5088         {       0xd3c2L, 0x1bcecceda1000000L  },  //10^24
5089         {       0x84595L, 0x161401484a000000L  },  //10^25
5090         {       0x52b7d2L, 0xdcc80cd2e4000000L  },  //10^26
5091         {       0x33b2e3cL, 0x9fd0803ce8000000L  },  //10^27
5092         {       0x204fce5eL, 0x3e25026110000000L  },  //10^28
5093         {       0x1431e0faeL, 0x6d7217caa0000000L  },  //10^29
5094         {       0xc9f2c9cd0L, 0x4674edea40000000L  },  //10^30
5095         {       0x7e37be2022L, 0xc0914b2680000000L  },  //10^31
5096         {       0x4ee2d6d415bL, 0x85acef8100000000L  },  //10^32
5097         {       0x314dc6448d93L, 0x38c15b0a00000000L  },  //10^33
5098         {       0x1ed09bead87c0L, 0x378d8e6400000000L  },  //10^34
5099         {       0x13426172c74d82L, 0x2b878fe800000000L  },  //10^35
5100         {       0xc097ce7bc90715L, 0xb34b9f1000000000L  },  //10^36
5101         {       0x785ee10d5da46d9L, 0x00f436a000000000L  },  //10^37
5102         {       0x4b3b4ca85a86c47aL, 0x098a224000000000L  },  //10^38
5103     };
5104 
5105     /*
5106      * returns precision of 128-bit value
5107      */
5108     private static int precision(long hi, long lo){
5109         if(hi==0) {
5110             if(lo>=0) {
5111                 return longDigitLength(lo);
5112             }
5113             return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;
5114             // 0x8AC7230489E80000L  = unsigned 2^19
5115         }
5116         int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;
5117         int idx = r-19;
5118         return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,
5119                                                                                     LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;
5120     }
5121 
5122     /*
5123      * returns true if 128 bit number <hi0,lo0> is less then <hi1,lo1>
5124      * hi0 & hi1 should be non-negative
5125      */
5126     private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {
5127         if(hi0!=hi1) {
5128             return hi0<hi1;
5129         }
5130         return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);
5131     }
5132 
5133     private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5134         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5135             int newScale = scale + divisorScale;
5136             int raise = newScale - dividendScale;
5137             if(raise<LONG_TEN_POWERS_TABLE.length) {
5138                 long xs = dividend;
5139                 if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {
5140                     return divideAndRound(xs, divisor, scale, roundingMode, scale);
5141                 }
5142                 BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);
5143                 if(q!=null) {
5144                     return q;
5145                 }
5146             }
5147             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5148             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5149         } else {
5150             int newScale = checkScale(divisor,(long)dividendScale - scale);
5151             int raise = newScale - divisorScale;
5152             if(raise<LONG_TEN_POWERS_TABLE.length) {
5153                 long ys = divisor;
5154                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5155                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5156                 }
5157             }
5158             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5159             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5160         }
5161     }
5162 
5163     private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {
5164         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5165             int newScale = scale + divisorScale;
5166             int raise = newScale - dividendScale;
5167             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5168             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5169         } else {
5170             int newScale = checkScale(divisor,(long)dividendScale - scale);
5171             int raise = newScale - divisorScale;
5172             if(raise<LONG_TEN_POWERS_TABLE.length) {
5173                 long ys = divisor;
5174                 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {
5175                     return divideAndRound(dividend, ys, scale, roundingMode, scale);
5176                 }
5177             }
5178             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5179             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5180         }
5181     }
5182 
5183     private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5184         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5185             int newScale = scale + divisorScale;
5186             int raise = newScale - dividendScale;
5187             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5188             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5189         } else {
5190             int newScale = checkScale(divisor,(long)dividendScale - scale);
5191             int raise = newScale - divisorScale;
5192             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5193             return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);
5194         }
5195     }
5196 
5197     private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {
5198         if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {
5199             int newScale = scale + divisorScale;
5200             int raise = newScale - dividendScale;
5201             BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);
5202             return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);
5203         } else {
5204             int newScale = checkScale(divisor,(long)dividendScale - scale);
5205             int raise = newScale - divisorScale;
5206             BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);
5207             return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);
5208         }
5209     }
5210 
5211 }