Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/math/BigDecimal.java
38829 views
/*1* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* Portions Copyright IBM Corporation, 2001. All Rights Reserved.27*/2829package java.math;3031import static java.math.BigInteger.LONG_MASK;32import java.util.Arrays;3334/**35* Immutable, arbitrary-precision signed decimal numbers. A36* {@code BigDecimal} consists of an arbitrary precision integer37* <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero38* or positive, the scale is the number of digits to the right of the39* decimal point. If negative, the unscaled value of the number is40* multiplied by ten to the power of the negation of the scale. The41* value of the number represented by the {@code BigDecimal} is42* therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.43*44* <p>The {@code BigDecimal} class provides operations for45* arithmetic, scale manipulation, rounding, comparison, hashing, and46* format conversion. The {@link #toString} method provides a47* canonical representation of a {@code BigDecimal}.48*49* <p>The {@code BigDecimal} class gives its user complete control50* over rounding behavior. If no rounding mode is specified and the51* exact result cannot be represented, an exception is thrown;52* otherwise, calculations can be carried out to a chosen precision53* and rounding mode by supplying an appropriate {@link MathContext}54* object to the operation. In either case, eight <em>rounding55* modes</em> are provided for the control of rounding. Using the56* integer fields in this class (such as {@link #ROUND_HALF_UP}) to57* represent rounding mode is largely obsolete; the enumeration values58* of the {@code RoundingMode} {@code enum}, (such as {@link59* RoundingMode#HALF_UP}) should be used instead.60*61* <p>When a {@code MathContext} object is supplied with a precision62* setting of 0 (for example, {@link MathContext#UNLIMITED}),63* arithmetic operations are exact, as are the arithmetic methods64* which take no {@code MathContext} object. (This is the only65* behavior that was supported in releases prior to 5.) As a66* corollary of computing the exact result, the rounding mode setting67* of a {@code MathContext} object with a precision setting of 0 is68* not used and thus irrelevant. In the case of divide, the exact69* quotient could have an infinitely long decimal expansion; for70* example, 1 divided by 3. If the quotient has a nonterminating71* decimal expansion and the operation is specified to return an exact72* result, an {@code ArithmeticException} is thrown. Otherwise, the73* exact result of the division is returned, as done for other74* operations.75*76* <p>When the precision setting is not 0, the rules of77* {@code BigDecimal} arithmetic are broadly compatible with selected78* modes of operation of the arithmetic defined in ANSI X3.274-199679* and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those80* standards, {@code BigDecimal} includes many rounding modes, which81* were mandatory for division in {@code BigDecimal} releases prior82* to 5. Any conflicts between these ANSI standards and the83* {@code BigDecimal} specification are resolved in favor of84* {@code BigDecimal}.85*86* <p>Since the same numerical value can have different87* representations (with different scales), the rules of arithmetic88* and rounding must specify both the numerical result and the scale89* used in the result's representation.90*91*92* <p>In general the rounding modes and precision setting determine93* how operations return results with a limited number of digits when94* the exact result has more digits (perhaps infinitely many in the95* case of division) than the number of digits returned.96*97* First, the98* total number of digits to return is specified by the99* {@code MathContext}'s {@code precision} setting; this determines100* the result's <i>precision</i>. The digit count starts from the101* leftmost nonzero digit of the exact result. The rounding mode102* determines how any discarded trailing digits affect the returned103* result.104*105* <p>For all arithmetic operators , the operation is carried out as106* though an exact intermediate result were first calculated and then107* rounded to the number of digits specified by the precision setting108* (if necessary), using the selected rounding mode. If the exact109* result is not returned, some digit positions of the exact result110* are discarded. When rounding increases the magnitude of the111* returned result, it is possible for a new digit position to be112* created by a carry propagating to a leading {@literal "9"} digit.113* For example, rounding the value 999.9 to three digits rounding up114* would be numerically equal to one thousand, represented as115* 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is116* the leading digit position of the returned result.117*118* <p>Besides a logical exact result, each arithmetic operation has a119* preferred scale for representing a result. The preferred120* scale for each operation is listed in the table below.121*122* <table border>123* <caption><b>Preferred Scales for Results of Arithmetic Operations124* </b></caption>125* <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>126* <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>127* <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>128* <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>129* <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>130* </table>131*132* These scales are the ones used by the methods which return exact133* arithmetic results; except that an exact divide may have to use a134* larger scale since the exact result may have more digits. For135* example, {@code 1/32} is {@code 0.03125}.136*137* <p>Before rounding, the scale of the logical exact intermediate138* result is the preferred scale for that operation. If the exact139* numerical result cannot be represented in {@code precision}140* digits, rounding selects the set of digits to return and the scale141* of the result is reduced from the scale of the intermediate result142* to the least scale which can represent the {@code precision}143* digits actually returned. If the exact result can be represented144* with at most {@code precision} digits, the representation145* of the result with the scale closest to the preferred scale is146* returned. In particular, an exactly representable quotient may be147* represented in fewer than {@code precision} digits by removing148* trailing zeros and decreasing the scale. For example, rounding to149* three digits using the {@linkplain RoundingMode#FLOOR floor}150* rounding mode, <br>151*152* {@code 19/100 = 0.19 // integer=19, scale=2} <br>153*154* but<br>155*156* {@code 21/110 = 0.190 // integer=190, scale=3} <br>157*158* <p>Note that for add, subtract, and multiply, the reduction in159* scale will equal the number of digit positions of the exact result160* which are discarded. If the rounding causes a carry propagation to161* create a new high-order digit position, an additional digit of the162* result is discarded than when no new digit position is created.163*164* <p>Other methods may have slightly different rounding semantics.165* For example, the result of the {@code pow} method using the166* {@linkplain #pow(int, MathContext) specified algorithm} can167* occasionally differ from the rounded mathematical result by more168* than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.169*170* <p>Two types of operations are provided for manipulating the scale171* of a {@code BigDecimal}: scaling/rounding operations and decimal172* point motion operations. Scaling/rounding operations ({@link173* #setScale setScale} and {@link #round round}) return a174* {@code BigDecimal} whose value is approximately (or exactly) equal175* to that of the operand, but whose scale or precision is the176* specified value; that is, they increase or decrease the precision177* of the stored number with minimal effect on its value. Decimal178* point motion operations ({@link #movePointLeft movePointLeft} and179* {@link #movePointRight movePointRight}) return a180* {@code BigDecimal} created from the operand by moving the decimal181* point a specified distance in the specified direction.182*183* <p>For the sake of brevity and clarity, pseudo-code is used184* throughout the descriptions of {@code BigDecimal} methods. The185* pseudo-code expression {@code (i + j)} is shorthand for "a186* {@code BigDecimal} whose value is that of the {@code BigDecimal}187* {@code i} added to that of the {@code BigDecimal}188* {@code j}." The pseudo-code expression {@code (i == j)} is189* shorthand for "{@code true} if and only if the190* {@code BigDecimal} {@code i} represents the same value as the191* {@code BigDecimal} {@code j}." Other pseudo-code expressions192* are interpreted similarly. Square brackets are used to represent193* the particular {@code BigInteger} and scale pair defining a194* {@code BigDecimal} value; for example [19, 2] is the195* {@code BigDecimal} numerically equal to 0.19 having a scale of 2.196*197* <p>Note: care should be exercised if {@code BigDecimal} objects198* are used as keys in a {@link java.util.SortedMap SortedMap} or199* elements in a {@link java.util.SortedSet SortedSet} since200* {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent201* with equals</i>. See {@link Comparable}, {@link202* java.util.SortedMap} or {@link java.util.SortedSet} for more203* information.204*205* <p>All methods and constructors for this class throw206* {@code NullPointerException} when passed a {@code null} object207* reference for any input parameter.208*209* @see BigInteger210* @see MathContext211* @see RoundingMode212* @see java.util.SortedMap213* @see java.util.SortedSet214* @author Josh Bloch215* @author Mike Cowlishaw216* @author Joseph D. Darcy217* @author Sergey V. Kuksenko218*/219public class BigDecimal extends Number implements Comparable<BigDecimal> {220/**221* The unscaled value of this BigDecimal, as returned by {@link222* #unscaledValue}.223*224* @serial225* @see #unscaledValue226*/227private final BigInteger intVal;228229/**230* The scale of this BigDecimal, as returned by {@link #scale}.231*232* @serial233* @see #scale234*/235private final int scale; // Note: this may have any value, so236// calculations must be done in longs237238/**239* The number of decimal digits in this BigDecimal, or 0 if the240* number of digits are not known (lookaside information). If241* nonzero, the value is guaranteed correct. Use the precision()242* method to obtain and set the value if it might be 0. This243* field is mutable until set nonzero.244*245* @since 1.5246*/247private transient int precision;248249/**250* Used to store the canonical string representation, if computed.251*/252private transient String stringCache;253254/**255* Sentinel value for {@link #intCompact} indicating the256* significand information is only available from {@code intVal}.257*/258static final long INFLATED = Long.MIN_VALUE;259260private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);261262/**263* If the absolute value of the significand of this BigDecimal is264* less than or equal to {@code Long.MAX_VALUE}, the value can be265* compactly stored in this field and used in computations.266*/267private final transient long intCompact;268269// All 18-digit base ten strings fit into a long; not all 19-digit270// strings will271private static final int MAX_COMPACT_DIGITS = 18;272273/* Appease the serialization gods */274private static final long serialVersionUID = 6108874887143696463L;275276private static final ThreadLocal<StringBuilderHelper>277threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {278@Override279protected StringBuilderHelper initialValue() {280return new StringBuilderHelper();281}282};283284// Cache of common small BigDecimal values.285private static final BigDecimal zeroThroughTen[] = {286new BigDecimal(BigInteger.ZERO, 0, 0, 1),287new BigDecimal(BigInteger.ONE, 1, 0, 1),288new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),289new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),290new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),291new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),292new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),293new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),294new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),295new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),296new BigDecimal(BigInteger.TEN, 10, 0, 2),297};298299// Cache of zero scaled by 0 - 15300private static final BigDecimal[] ZERO_SCALED_BY = {301zeroThroughTen[0],302new BigDecimal(BigInteger.ZERO, 0, 1, 1),303new BigDecimal(BigInteger.ZERO, 0, 2, 1),304new BigDecimal(BigInteger.ZERO, 0, 3, 1),305new BigDecimal(BigInteger.ZERO, 0, 4, 1),306new BigDecimal(BigInteger.ZERO, 0, 5, 1),307new BigDecimal(BigInteger.ZERO, 0, 6, 1),308new BigDecimal(BigInteger.ZERO, 0, 7, 1),309new BigDecimal(BigInteger.ZERO, 0, 8, 1),310new BigDecimal(BigInteger.ZERO, 0, 9, 1),311new BigDecimal(BigInteger.ZERO, 0, 10, 1),312new BigDecimal(BigInteger.ZERO, 0, 11, 1),313new BigDecimal(BigInteger.ZERO, 0, 12, 1),314new BigDecimal(BigInteger.ZERO, 0, 13, 1),315new BigDecimal(BigInteger.ZERO, 0, 14, 1),316new BigDecimal(BigInteger.ZERO, 0, 15, 1),317};318319// Half of Long.MIN_VALUE & Long.MAX_VALUE.320private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;321private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;322323// Constants324/**325* The value 0, with a scale of 0.326*327* @since 1.5328*/329public static final BigDecimal ZERO =330zeroThroughTen[0];331332/**333* The value 1, with a scale of 0.334*335* @since 1.5336*/337public static final BigDecimal ONE =338zeroThroughTen[1];339340/**341* The value 10, with a scale of 0.342*343* @since 1.5344*/345public static final BigDecimal TEN =346zeroThroughTen[10];347348// Constructors349350/**351* Trusted package private constructor.352* Trusted simply means if val is INFLATED, intVal could not be null and353* if intVal is null, val could not be INFLATED.354*/355BigDecimal(BigInteger intVal, long val, int scale, int prec) {356this.scale = scale;357this.precision = prec;358this.intCompact = val;359this.intVal = intVal;360}361362/**363* Translates a character array representation of a364* {@code BigDecimal} into a {@code BigDecimal}, accepting the365* same sequence of characters as the {@link #BigDecimal(String)}366* constructor, while allowing a sub-array to be specified.367*368* <p>Note that if the sequence of characters is already available369* within a character array, using this constructor is faster than370* converting the {@code char} array to string and using the371* {@code BigDecimal(String)} constructor .372*373* @param in {@code char} array that is the source of characters.374* @param offset first character in the array to inspect.375* @param len number of characters to consider.376* @throws NumberFormatException if {@code in} is not a valid377* representation of a {@code BigDecimal} or the defined subarray378* is not wholly within {@code in}.379* @since 1.5380*/381public BigDecimal(char[] in, int offset, int len) {382this(in,offset,len,MathContext.UNLIMITED);383}384385/**386* Translates a character array representation of a387* {@code BigDecimal} into a {@code BigDecimal}, accepting the388* same sequence of characters as the {@link #BigDecimal(String)}389* constructor, while allowing a sub-array to be specified and390* with rounding according to the context settings.391*392* <p>Note that if the sequence of characters is already available393* within a character array, using this constructor is faster than394* converting the {@code char} array to string and using the395* {@code BigDecimal(String)} constructor .396*397* @param in {@code char} array that is the source of characters.398* @param offset first character in the array to inspect.399* @param len number of characters to consider..400* @param mc the context to use.401* @throws ArithmeticException if the result is inexact but the402* rounding mode is {@code UNNECESSARY}.403* @throws NumberFormatException if {@code in} is not a valid404* representation of a {@code BigDecimal} or the defined subarray405* is not wholly within {@code in}.406* @since 1.5407*/408public BigDecimal(char[] in, int offset, int len, MathContext mc) {409// protect against huge length, negative values, and integer overflow410if ((in.length | len | offset) < 0 || len > in.length - offset) {411throw new NumberFormatException412("Bad offset or len arguments for char[] input.");413}414415// This is the primary string to BigDecimal constructor; all416// incoming strings end up here; it uses explicit (inline)417// parsing for speed and generates at most one intermediate418// (temporary) object (a char[] array) for non-compact case.419420// Use locals for all fields values until completion421int prec = 0; // record precision value422int scl = 0; // record scale value423long rs = 0; // the compact value in long424BigInteger rb = null; // the inflated value in BigInteger425// use array bounds checking to handle too-long, len == 0,426// bad offset, etc.427try {428// handle the sign429boolean isneg = false; // assume positive430if (in[offset] == '-') {431isneg = true; // leading minus means negative432offset++;433len--;434} else if (in[offset] == '+') { // leading + allowed435offset++;436len--;437}438439// should now be at numeric part of the significand440boolean dot = false; // true when there is a '.'441long exp = 0; // exponent442char c; // current character443boolean isCompact = (len <= MAX_COMPACT_DIGITS);444// integer significand array & idx is the index to it. The array445// is ONLY used when we can't use a compact representation.446int idx = 0;447if (isCompact) {448// First compact case, we need not to preserve the character449// and we can just compute the value in place.450for (; len > 0; offset++, len--) {451c = in[offset];452if ((c == '0')) { // have zero453if (prec == 0)454prec = 1;455else if (rs != 0) {456rs *= 10;457++prec;458} // else digit is a redundant leading zero459if (dot)460++scl;461} else if ((c >= '1' && c <= '9')) { // have digit462int digit = c - '0';463if (prec != 1 || rs != 0)464++prec; // prec unchanged if preceded by 0s465rs = rs * 10 + digit;466if (dot)467++scl;468} else if (c == '.') { // have dot469// have dot470if (dot) // two dots471throw new NumberFormatException();472dot = true;473} else if (Character.isDigit(c)) { // slow path474int digit = Character.digit(c, 10);475if (digit == 0) {476if (prec == 0)477prec = 1;478else if (rs != 0) {479rs *= 10;480++prec;481} // else digit is a redundant leading zero482} else {483if (prec != 1 || rs != 0)484++prec; // prec unchanged if preceded by 0s485rs = rs * 10 + digit;486}487if (dot)488++scl;489} else if ((c == 'e') || (c == 'E')) {490exp = parseExp(in, offset, len);491// Next test is required for backwards compatibility492if ((int) exp != exp) // overflow493throw new NumberFormatException();494break; // [saves a test]495} else {496throw new NumberFormatException();497}498}499if (prec == 0) // no digits found500throw new NumberFormatException();501// Adjust scale if exp is not zero.502if (exp != 0) { // had significant exponent503scl = adjustScale(scl, exp);504}505rs = isneg ? -rs : rs;506int mcp = mc.precision;507int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];508// therefore, this subtract cannot overflow509if (mcp > 0 && drop > 0) { // do rounding510while (drop > 0) {511scl = checkScaleNonZero((long) scl - drop);512rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);513prec = longDigitLength(rs);514drop = prec - mcp;515}516}517} else {518char coeff[] = new char[len];519for (; len > 0; offset++, len--) {520c = in[offset];521// have digit522if ((c >= '0' && c <= '9') || Character.isDigit(c)) {523// First compact case, we need not to preserve the character524// and we can just compute the value in place.525if (c == '0' || Character.digit(c, 10) == 0) {526if (prec == 0) {527coeff[idx] = c;528prec = 1;529} else if (idx != 0) {530coeff[idx++] = c;531++prec;532} // else c must be a redundant leading zero533} else {534if (prec != 1 || idx != 0)535++prec; // prec unchanged if preceded by 0s536coeff[idx++] = c;537}538if (dot)539++scl;540continue;541}542// have dot543if (c == '.') {544// have dot545if (dot) // two dots546throw new NumberFormatException();547dot = true;548continue;549}550// exponent expected551if ((c != 'e') && (c != 'E'))552throw new NumberFormatException();553exp = parseExp(in, offset, len);554// Next test is required for backwards compatibility555if ((int) exp != exp) // overflow556throw new NumberFormatException();557break; // [saves a test]558}559// here when no characters left560if (prec == 0) // no digits found561throw new NumberFormatException();562// Adjust scale if exp is not zero.563if (exp != 0) { // had significant exponent564scl = adjustScale(scl, exp);565}566// Remove leading zeros from precision (digits count)567rb = new BigInteger(coeff, isneg ? -1 : 1, prec);568rs = compactValFor(rb);569int mcp = mc.precision;570if (mcp > 0 && (prec > mcp)) {571if (rs == INFLATED) {572int drop = prec - mcp;573while (drop > 0) {574scl = checkScaleNonZero((long) scl - drop);575rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);576rs = compactValFor(rb);577if (rs != INFLATED) {578prec = longDigitLength(rs);579break;580}581prec = bigDigitLength(rb);582drop = prec - mcp;583}584}585if (rs != INFLATED) {586int drop = prec - mcp;587while (drop > 0) {588scl = checkScaleNonZero((long) scl - drop);589rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);590prec = longDigitLength(rs);591drop = prec - mcp;592}593rb = null;594}595}596}597} catch (ArrayIndexOutOfBoundsException e) {598throw new NumberFormatException();599} catch (NegativeArraySizeException e) {600throw new NumberFormatException();601}602this.scale = scl;603this.precision = prec;604this.intCompact = rs;605this.intVal = rb;606}607608private int adjustScale(int scl, long exp) {609long adjustedScale = scl - exp;610if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)611throw new NumberFormatException("Scale out of range.");612scl = (int) adjustedScale;613return scl;614}615616/*617* parse exponent618*/619private static long parseExp(char[] in, int offset, int len){620long exp = 0;621offset++;622char c = in[offset];623len--;624boolean negexp = (c == '-');625// optional sign626if (negexp || c == '+') {627offset++;628c = in[offset];629len--;630}631if (len <= 0) // no exponent digits632throw new NumberFormatException();633// skip leading zeros in the exponent634while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {635offset++;636c = in[offset];637len--;638}639if (len > 10) // too many nonzero exponent digits640throw new NumberFormatException();641// c now holds first digit of exponent642for (;; len--) {643int v;644if (c >= '0' && c <= '9') {645v = c - '0';646} else {647v = Character.digit(c, 10);648if (v < 0) // not a digit649throw new NumberFormatException();650}651exp = exp * 10 + v;652if (len == 1)653break; // that was final character654offset++;655c = in[offset];656}657if (negexp) // apply sign658exp = -exp;659return exp;660}661662/**663* Translates a character array representation of a664* {@code BigDecimal} into a {@code BigDecimal}, accepting the665* same sequence of characters as the {@link #BigDecimal(String)}666* constructor.667*668* <p>Note that if the sequence of characters is already available669* as a character array, using this constructor is faster than670* converting the {@code char} array to string and using the671* {@code BigDecimal(String)} constructor .672*673* @param in {@code char} array that is the source of characters.674* @throws NumberFormatException if {@code in} is not a valid675* representation of a {@code BigDecimal}.676* @since 1.5677*/678public BigDecimal(char[] in) {679this(in, 0, in.length);680}681682/**683* Translates a character array representation of a684* {@code BigDecimal} into a {@code BigDecimal}, accepting the685* same sequence of characters as the {@link #BigDecimal(String)}686* constructor and with rounding according to the context687* settings.688*689* <p>Note that if the sequence of characters is already available690* as a character array, using this constructor is faster than691* converting the {@code char} array to string and using the692* {@code BigDecimal(String)} constructor .693*694* @param in {@code char} array that is the source of characters.695* @param mc the context to use.696* @throws ArithmeticException if the result is inexact but the697* rounding mode is {@code UNNECESSARY}.698* @throws NumberFormatException if {@code in} is not a valid699* representation of a {@code BigDecimal}.700* @since 1.5701*/702public BigDecimal(char[] in, MathContext mc) {703this(in, 0, in.length, mc);704}705706/**707* Translates the string representation of a {@code BigDecimal}708* into a {@code BigDecimal}. The string representation consists709* of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or710* {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of711* zero or more decimal digits ("the integer"), optionally712* followed by a fraction, optionally followed by an exponent.713*714* <p>The fraction consists of a decimal point followed by zero715* or more decimal digits. The string must contain at least one716* digit in either the integer or the fraction. The number formed717* by the sign, the integer and the fraction is referred to as the718* <i>significand</i>.719*720* <p>The exponent consists of the character {@code 'e'}721* (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>)722* followed by one or more decimal digits. The value of the723* exponent must lie between -{@link Integer#MAX_VALUE} ({@link724* Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.725*726* <p>More formally, the strings this constructor accepts are727* described by the following grammar:728* <blockquote>729* <dl>730* <dt><i>BigDecimalString:</i>731* <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>732* <dt><i>Sign:</i>733* <dd>{@code +}734* <dd>{@code -}735* <dt><i>Significand:</i>736* <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>737* <dd>{@code .} <i>FractionPart</i>738* <dd><i>IntegerPart</i>739* <dt><i>IntegerPart:</i>740* <dd><i>Digits</i>741* <dt><i>FractionPart:</i>742* <dd><i>Digits</i>743* <dt><i>Exponent:</i>744* <dd><i>ExponentIndicator SignedInteger</i>745* <dt><i>ExponentIndicator:</i>746* <dd>{@code e}747* <dd>{@code E}748* <dt><i>SignedInteger:</i>749* <dd><i>Sign<sub>opt</sub> Digits</i>750* <dt><i>Digits:</i>751* <dd><i>Digit</i>752* <dd><i>Digits Digit</i>753* <dt><i>Digit:</i>754* <dd>any character for which {@link Character#isDigit}755* returns {@code true}, including 0, 1, 2 ...756* </dl>757* </blockquote>758*759* <p>The scale of the returned {@code BigDecimal} will be the760* number of digits in the fraction, or zero if the string761* contains no decimal point, subject to adjustment for any762* exponent; if the string contains an exponent, the exponent is763* subtracted from the scale. The value of the resulting scale764* must lie between {@code Integer.MIN_VALUE} and765* {@code Integer.MAX_VALUE}, inclusive.766*767* <p>The character-to-digit mapping is provided by {@link768* java.lang.Character#digit} set to convert to radix 10. The769* String may not contain any extraneous characters (whitespace,770* for example).771*772* <p><b>Examples:</b><br>773* The value of the returned {@code BigDecimal} is equal to774* <i>significand</i> × 10<sup> <i>exponent</i></sup>.775* For each string on the left, the resulting representation776* [{@code BigInteger}, {@code scale}] is shown on the right.777* <pre>778* "0" [0,0]779* "0.00" [0,2]780* "123" [123,0]781* "-123" [-123,0]782* "1.23E3" [123,-1]783* "1.23E+3" [123,-1]784* "12.3E+7" [123,-6]785* "12.0" [120,1]786* "12.3" [123,1]787* "0.00123" [123,5]788* "-1.23E-12" [-123,14]789* "1234.5E-4" [12345,5]790* "0E+7" [0,-7]791* "-0" [0,0]792* </pre>793*794* <p>Note: For values other than {@code float} and795* {@code double} NaN and ±Infinity, this constructor is796* compatible with the values returned by {@link Float#toString}797* and {@link Double#toString}. This is generally the preferred798* way to convert a {@code float} or {@code double} into a799* BigDecimal, as it doesn't suffer from the unpredictability of800* the {@link #BigDecimal(double)} constructor.801*802* @param val String representation of {@code BigDecimal}.803*804* @throws NumberFormatException if {@code val} is not a valid805* representation of a {@code BigDecimal}.806*/807public BigDecimal(String val) {808this(val.toCharArray(), 0, val.length());809}810811/**812* Translates the string representation of a {@code BigDecimal}813* into a {@code BigDecimal}, accepting the same strings as the814* {@link #BigDecimal(String)} constructor, with rounding815* according to the context settings.816*817* @param val string representation of a {@code BigDecimal}.818* @param mc the context to use.819* @throws ArithmeticException if the result is inexact but the820* rounding mode is {@code UNNECESSARY}.821* @throws NumberFormatException if {@code val} is not a valid822* representation of a BigDecimal.823* @since 1.5824*/825public BigDecimal(String val, MathContext mc) {826this(val.toCharArray(), 0, val.length(), mc);827}828829/**830* Translates a {@code double} into a {@code BigDecimal} which831* is the exact decimal representation of the {@code double}'s832* binary floating-point value. The scale of the returned833* {@code BigDecimal} is the smallest value such that834* <tt>(10<sup>scale</sup> × val)</tt> is an integer.835* <p>836* <b>Notes:</b>837* <ol>838* <li>839* The results of this constructor can be somewhat unpredictable.840* One might assume that writing {@code new BigDecimal(0.1)} in841* Java creates a {@code BigDecimal} which is exactly equal to842* 0.1 (an unscaled value of 1, with a scale of 1), but it is843* actually equal to844* 0.1000000000000000055511151231257827021181583404541015625.845* This is because 0.1 cannot be represented exactly as a846* {@code double} (or, for that matter, as a binary fraction of847* any finite length). Thus, the value that is being passed848* <i>in</i> to the constructor is not exactly equal to 0.1,849* appearances notwithstanding.850*851* <li>852* The {@code String} constructor, on the other hand, is853* perfectly predictable: writing {@code new BigDecimal("0.1")}854* creates a {@code BigDecimal} which is <i>exactly</i> equal to855* 0.1, as one would expect. Therefore, it is generally856* recommended that the {@linkplain #BigDecimal(String)857* <tt>String</tt> constructor} be used in preference to this one.858*859* <li>860* When a {@code double} must be used as a source for a861* {@code BigDecimal}, note that this constructor provides an862* exact conversion; it does not give the same result as863* converting the {@code double} to a {@code String} using the864* {@link Double#toString(double)} method and then using the865* {@link #BigDecimal(String)} constructor. To get that result,866* use the {@code static} {@link #valueOf(double)} method.867* </ol>868*869* @param val {@code double} value to be converted to870* {@code BigDecimal}.871* @throws NumberFormatException if {@code val} is infinite or NaN.872*/873public BigDecimal(double val) {874this(val,MathContext.UNLIMITED);875}876877/**878* Translates a {@code double} into a {@code BigDecimal}, with879* rounding according to the context settings. The scale of the880* {@code BigDecimal} is the smallest value such that881* <tt>(10<sup>scale</sup> × val)</tt> is an integer.882*883* <p>The results of this constructor can be somewhat unpredictable884* and its use is generally not recommended; see the notes under885* the {@link #BigDecimal(double)} constructor.886*887* @param val {@code double} value to be converted to888* {@code BigDecimal}.889* @param mc the context to use.890* @throws ArithmeticException if the result is inexact but the891* RoundingMode is UNNECESSARY.892* @throws NumberFormatException if {@code val} is infinite or NaN.893* @since 1.5894*/895public BigDecimal(double val, MathContext mc) {896if (Double.isInfinite(val) || Double.isNaN(val))897throw new NumberFormatException("Infinite or NaN");898// Translate the double into sign, exponent and significand, according899// to the formulae in JLS, Section 20.10.22.900long valBits = Double.doubleToLongBits(val);901int sign = ((valBits >> 63) == 0 ? 1 : -1);902int exponent = (int) ((valBits >> 52) & 0x7ffL);903long significand = (exponent == 0904? (valBits & ((1L << 52) - 1)) << 1905: (valBits & ((1L << 52) - 1)) | (1L << 52));906exponent -= 1075;907// At this point, val == sign * significand * 2**exponent.908909/*910* Special case zero to supress nonterminating normalization and bogus911* scale calculation.912*/913if (significand == 0) {914this.intVal = BigInteger.ZERO;915this.scale = 0;916this.intCompact = 0;917this.precision = 1;918return;919}920// Normalize921while ((significand & 1) == 0) { // i.e., significand is even922significand >>= 1;923exponent++;924}925int scale = 0;926// Calculate intVal and scale927BigInteger intVal;928long compactVal = sign * significand;929if (exponent == 0) {930intVal = (compactVal == INFLATED) ? INFLATED_BIGINT : null;931} else {932if (exponent < 0) {933intVal = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);934scale = -exponent;935} else { // (exponent > 0)936intVal = BigInteger.valueOf(2).pow(exponent).multiply(compactVal);937}938compactVal = compactValFor(intVal);939}940int prec = 0;941int mcp = mc.precision;942if (mcp > 0) { // do rounding943int mode = mc.roundingMode.oldMode;944int drop;945if (compactVal == INFLATED) {946prec = bigDigitLength(intVal);947drop = prec - mcp;948while (drop > 0) {949scale = checkScaleNonZero((long) scale - drop);950intVal = divideAndRoundByTenPow(intVal, drop, mode);951compactVal = compactValFor(intVal);952if (compactVal != INFLATED) {953break;954}955prec = bigDigitLength(intVal);956drop = prec - mcp;957}958}959if (compactVal != INFLATED) {960prec = longDigitLength(compactVal);961drop = prec - mcp;962while (drop > 0) {963scale = checkScaleNonZero((long) scale - drop);964compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);965prec = longDigitLength(compactVal);966drop = prec - mcp;967}968intVal = null;969}970}971this.intVal = intVal;972this.intCompact = compactVal;973this.scale = scale;974this.precision = prec;975}976977/**978* Translates a {@code BigInteger} into a {@code BigDecimal}.979* The scale of the {@code BigDecimal} is zero.980*981* @param val {@code BigInteger} value to be converted to982* {@code BigDecimal}.983*/984public BigDecimal(BigInteger val) {985scale = 0;986intVal = val;987intCompact = compactValFor(val);988}989990/**991* Translates a {@code BigInteger} into a {@code BigDecimal}992* rounding according to the context settings. The scale of the993* {@code BigDecimal} is zero.994*995* @param val {@code BigInteger} value to be converted to996* {@code BigDecimal}.997* @param mc the context to use.998* @throws ArithmeticException if the result is inexact but the999* rounding mode is {@code UNNECESSARY}.1000* @since 1.51001*/1002public BigDecimal(BigInteger val, MathContext mc) {1003this(val,0,mc);1004}10051006/**1007* Translates a {@code BigInteger} unscaled value and an1008* {@code int} scale into a {@code BigDecimal}. The value of1009* the {@code BigDecimal} is1010* <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.1011*1012* @param unscaledVal unscaled value of the {@code BigDecimal}.1013* @param scale scale of the {@code BigDecimal}.1014*/1015public BigDecimal(BigInteger unscaledVal, int scale) {1016// Negative scales are now allowed1017this.intVal = unscaledVal;1018this.intCompact = compactValFor(unscaledVal);1019this.scale = scale;1020}10211022/**1023* Translates a {@code BigInteger} unscaled value and an1024* {@code int} scale into a {@code BigDecimal}, with rounding1025* according to the context settings. The value of the1026* {@code BigDecimal} is <tt>(unscaledVal ×1027* 10<sup>-scale</sup>)</tt>, rounded according to the1028* {@code precision} and rounding mode settings.1029*1030* @param unscaledVal unscaled value of the {@code BigDecimal}.1031* @param scale scale of the {@code BigDecimal}.1032* @param mc the context to use.1033* @throws ArithmeticException if the result is inexact but the1034* rounding mode is {@code UNNECESSARY}.1035* @since 1.51036*/1037public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {1038long compactVal = compactValFor(unscaledVal);1039int mcp = mc.precision;1040int prec = 0;1041if (mcp > 0) { // do rounding1042int mode = mc.roundingMode.oldMode;1043if (compactVal == INFLATED) {1044prec = bigDigitLength(unscaledVal);1045int drop = prec - mcp;1046while (drop > 0) {1047scale = checkScaleNonZero((long) scale - drop);1048unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);1049compactVal = compactValFor(unscaledVal);1050if (compactVal != INFLATED) {1051break;1052}1053prec = bigDigitLength(unscaledVal);1054drop = prec - mcp;1055}1056}1057if (compactVal != INFLATED) {1058prec = longDigitLength(compactVal);1059int drop = prec - mcp; // drop can't be more than 181060while (drop > 0) {1061scale = checkScaleNonZero((long) scale - drop);1062compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);1063prec = longDigitLength(compactVal);1064drop = prec - mcp;1065}1066unscaledVal = null;1067}1068}1069this.intVal = unscaledVal;1070this.intCompact = compactVal;1071this.scale = scale;1072this.precision = prec;1073}10741075/**1076* Translates an {@code int} into a {@code BigDecimal}. The1077* scale of the {@code BigDecimal} is zero.1078*1079* @param val {@code int} value to be converted to1080* {@code BigDecimal}.1081* @since 1.51082*/1083public BigDecimal(int val) {1084this.intCompact = val;1085this.scale = 0;1086this.intVal = null;1087}10881089/**1090* Translates an {@code int} into a {@code BigDecimal}, with1091* rounding according to the context settings. The scale of the1092* {@code BigDecimal}, before any rounding, is zero.1093*1094* @param val {@code int} value to be converted to {@code BigDecimal}.1095* @param mc the context to use.1096* @throws ArithmeticException if the result is inexact but the1097* rounding mode is {@code UNNECESSARY}.1098* @since 1.51099*/1100public BigDecimal(int val, MathContext mc) {1101int mcp = mc.precision;1102long compactVal = val;1103int scale = 0;1104int prec = 0;1105if (mcp > 0) { // do rounding1106prec = longDigitLength(compactVal);1107int drop = prec - mcp; // drop can't be more than 181108while (drop > 0) {1109scale = checkScaleNonZero((long) scale - drop);1110compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);1111prec = longDigitLength(compactVal);1112drop = prec - mcp;1113}1114}1115this.intVal = null;1116this.intCompact = compactVal;1117this.scale = scale;1118this.precision = prec;1119}11201121/**1122* Translates a {@code long} into a {@code BigDecimal}. The1123* scale of the {@code BigDecimal} is zero.1124*1125* @param val {@code long} value to be converted to {@code BigDecimal}.1126* @since 1.51127*/1128public BigDecimal(long val) {1129this.intCompact = val;1130this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;1131this.scale = 0;1132}11331134/**1135* Translates a {@code long} into a {@code BigDecimal}, with1136* rounding according to the context settings. The scale of the1137* {@code BigDecimal}, before any rounding, is zero.1138*1139* @param val {@code long} value to be converted to {@code BigDecimal}.1140* @param mc the context to use.1141* @throws ArithmeticException if the result is inexact but the1142* rounding mode is {@code UNNECESSARY}.1143* @since 1.51144*/1145public BigDecimal(long val, MathContext mc) {1146int mcp = mc.precision;1147int mode = mc.roundingMode.oldMode;1148int prec = 0;1149int scale = 0;1150BigInteger intVal = (val == INFLATED) ? INFLATED_BIGINT : null;1151if (mcp > 0) { // do rounding1152if (val == INFLATED) {1153prec = 19;1154int drop = prec - mcp;1155while (drop > 0) {1156scale = checkScaleNonZero((long) scale - drop);1157intVal = divideAndRoundByTenPow(intVal, drop, mode);1158val = compactValFor(intVal);1159if (val != INFLATED) {1160break;1161}1162prec = bigDigitLength(intVal);1163drop = prec - mcp;1164}1165}1166if (val != INFLATED) {1167prec = longDigitLength(val);1168int drop = prec - mcp;1169while (drop > 0) {1170scale = checkScaleNonZero((long) scale - drop);1171val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);1172prec = longDigitLength(val);1173drop = prec - mcp;1174}1175intVal = null;1176}1177}1178this.intVal = intVal;1179this.intCompact = val;1180this.scale = scale;1181this.precision = prec;1182}11831184// Static Factory Methods11851186/**1187* Translates a {@code long} unscaled value and an1188* {@code int} scale into a {@code BigDecimal}. This1189* {@literal "static factory method"} is provided in preference to1190* a ({@code long}, {@code int}) constructor because it1191* allows for reuse of frequently used {@code BigDecimal} values..1192*1193* @param unscaledVal unscaled value of the {@code BigDecimal}.1194* @param scale scale of the {@code BigDecimal}.1195* @return a {@code BigDecimal} whose value is1196* <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.1197*/1198public static BigDecimal valueOf(long unscaledVal, int scale) {1199if (scale == 0)1200return valueOf(unscaledVal);1201else if (unscaledVal == 0) {1202return zeroValueOf(scale);1203}1204return new BigDecimal(unscaledVal == INFLATED ?1205INFLATED_BIGINT : null,1206unscaledVal, scale, 0);1207}12081209/**1210* Translates a {@code long} value into a {@code BigDecimal}1211* with a scale of zero. This {@literal "static factory method"}1212* is provided in preference to a ({@code long}) constructor1213* because it allows for reuse of frequently used1214* {@code BigDecimal} values.1215*1216* @param val value of the {@code BigDecimal}.1217* @return a {@code BigDecimal} whose value is {@code val}.1218*/1219public static BigDecimal valueOf(long val) {1220if (val >= 0 && val < zeroThroughTen.length)1221return zeroThroughTen[(int)val];1222else if (val != INFLATED)1223return new BigDecimal(null, val, 0, 0);1224return new BigDecimal(INFLATED_BIGINT, val, 0, 0);1225}12261227static BigDecimal valueOf(long unscaledVal, int scale, int prec) {1228if (scale == 0 && unscaledVal >= 0 && unscaledVal < zeroThroughTen.length) {1229return zeroThroughTen[(int) unscaledVal];1230} else if (unscaledVal == 0) {1231return zeroValueOf(scale);1232}1233return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,1234unscaledVal, scale, prec);1235}12361237static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {1238long val = compactValFor(intVal);1239if (val == 0) {1240return zeroValueOf(scale);1241} else if (scale == 0 && val >= 0 && val < zeroThroughTen.length) {1242return zeroThroughTen[(int) val];1243}1244return new BigDecimal(intVal, val, scale, prec);1245}12461247static BigDecimal zeroValueOf(int scale) {1248if (scale >= 0 && scale < ZERO_SCALED_BY.length)1249return ZERO_SCALED_BY[scale];1250else1251return new BigDecimal(BigInteger.ZERO, 0, scale, 1);1252}12531254/**1255* Translates a {@code double} into a {@code BigDecimal}, using1256* the {@code double}'s canonical string representation provided1257* by the {@link Double#toString(double)} method.1258*1259* <p><b>Note:</b> This is generally the preferred way to convert1260* a {@code double} (or {@code float}) into a1261* {@code BigDecimal}, as the value returned is equal to that1262* resulting from constructing a {@code BigDecimal} from the1263* result of using {@link Double#toString(double)}.1264*1265* @param val {@code double} to convert to a {@code BigDecimal}.1266* @return a {@code BigDecimal} whose value is equal to or approximately1267* equal to the value of {@code val}.1268* @throws NumberFormatException if {@code val} is infinite or NaN.1269* @since 1.51270*/1271public static BigDecimal valueOf(double val) {1272// Reminder: a zero double returns '0.0', so we cannot fastpath1273// to use the constant ZERO. This might be important enough to1274// justify a factory approach, a cache, or a few private1275// constants, later.1276return new BigDecimal(Double.toString(val));1277}12781279// Arithmetic Operations1280/**1281* Returns a {@code BigDecimal} whose value is {@code (this +1282* augend)}, and whose scale is {@code max(this.scale(),1283* augend.scale())}.1284*1285* @param augend value to be added to this {@code BigDecimal}.1286* @return {@code this + augend}1287*/1288public BigDecimal add(BigDecimal augend) {1289if (this.intCompact != INFLATED) {1290if ((augend.intCompact != INFLATED)) {1291return add(this.intCompact, this.scale, augend.intCompact, augend.scale);1292} else {1293return add(this.intCompact, this.scale, augend.intVal, augend.scale);1294}1295} else {1296if ((augend.intCompact != INFLATED)) {1297return add(augend.intCompact, augend.scale, this.intVal, this.scale);1298} else {1299return add(this.intVal, this.scale, augend.intVal, augend.scale);1300}1301}1302}13031304/**1305* Returns a {@code BigDecimal} whose value is {@code (this + augend)},1306* with rounding according to the context settings.1307*1308* If either number is zero and the precision setting is nonzero then1309* the other number, rounded if necessary, is used as the result.1310*1311* @param augend value to be added to this {@code BigDecimal}.1312* @param mc the context to use.1313* @return {@code this + augend}, rounded as necessary.1314* @throws ArithmeticException if the result is inexact but the1315* rounding mode is {@code UNNECESSARY}.1316* @since 1.51317*/1318public BigDecimal add(BigDecimal augend, MathContext mc) {1319if (mc.precision == 0)1320return add(augend);1321BigDecimal lhs = this;13221323// If either number is zero then the other number, rounded and1324// scaled if necessary, is used as the result.1325{1326boolean lhsIsZero = lhs.signum() == 0;1327boolean augendIsZero = augend.signum() == 0;13281329if (lhsIsZero || augendIsZero) {1330int preferredScale = Math.max(lhs.scale(), augend.scale());1331BigDecimal result;13321333if (lhsIsZero && augendIsZero)1334return zeroValueOf(preferredScale);1335result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);13361337if (result.scale() == preferredScale)1338return result;1339else if (result.scale() > preferredScale) {1340return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);1341} else { // result.scale < preferredScale1342int precisionDiff = mc.precision - result.precision();1343int scaleDiff = preferredScale - result.scale();13441345if (precisionDiff >= scaleDiff)1346return result.setScale(preferredScale); // can achieve target scale1347else1348return result.setScale(result.scale() + precisionDiff);1349}1350}1351}13521353long padding = (long) lhs.scale - augend.scale;1354if (padding != 0) { // scales differ; alignment needed1355BigDecimal arg[] = preAlign(lhs, augend, padding, mc);1356matchScale(arg);1357lhs = arg[0];1358augend = arg[1];1359}1360return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);1361}13621363/**1364* Returns an array of length two, the sum of whose entries is1365* equal to the rounded sum of the {@code BigDecimal} arguments.1366*1367* <p>If the digit positions of the arguments have a sufficient1368* gap between them, the value smaller in magnitude can be1369* condensed into a {@literal "sticky bit"} and the end result will1370* round the same way <em>if</em> the precision of the final1371* result does not include the high order digit of the small1372* magnitude operand.1373*1374* <p>Note that while strictly speaking this is an optimization,1375* it makes a much wider range of additions practical.1376*1377* <p>This corresponds to a pre-shift operation in a fixed1378* precision floating-point adder; this method is complicated by1379* variable precision of the result as determined by the1380* MathContext. A more nuanced operation could implement a1381* {@literal "right shift"} on the smaller magnitude operand so1382* that the number of digits of the smaller operand could be1383* reduced even though the significands partially overlapped.1384*/1385private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {1386assert padding != 0;1387BigDecimal big;1388BigDecimal small;13891390if (padding < 0) { // lhs is big; augend is small1391big = lhs;1392small = augend;1393} else { // lhs is small; augend is big1394big = augend;1395small = lhs;1396}13971398/*1399* This is the estimated scale of an ulp of the result; it assumes that1400* the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>1401* 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>1402* 98.8)1403*/1404long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;14051406/*1407* The low-order digit position of big is big.scale(). This1408* is true regardless of whether big has a positive or1409* negative scale. The high-order digit position of small is1410* small.scale - (small.precision() - 1). To do the full1411* condensation, the digit positions of big and small must be1412* disjoint *and* the digit positions of small should not be1413* directly visible in the result.1414*/1415long smallHighDigitPos = (long) small.scale - small.precision() + 1;1416if (smallHighDigitPos > big.scale + 2 && // big and small disjoint1417smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible1418small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));1419}14201421// Since addition is symmetric, preserving input order in1422// returned operands doesn't matter1423BigDecimal[] result = {big, small};1424return result;1425}14261427/**1428* Returns a {@code BigDecimal} whose value is {@code (this -1429* subtrahend)}, and whose scale is {@code max(this.scale(),1430* subtrahend.scale())}.1431*1432* @param subtrahend value to be subtracted from this {@code BigDecimal}.1433* @return {@code this - subtrahend}1434*/1435public BigDecimal subtract(BigDecimal subtrahend) {1436if (this.intCompact != INFLATED) {1437if ((subtrahend.intCompact != INFLATED)) {1438return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);1439} else {1440return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);1441}1442} else {1443if ((subtrahend.intCompact != INFLATED)) {1444// Pair of subtrahend values given before pair of1445// values from this BigDecimal to avoid need for1446// method overloading on the specialized add method1447return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);1448} else {1449return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);1450}1451}1452}14531454/**1455* Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},1456* with rounding according to the context settings.1457*1458* If {@code subtrahend} is zero then this, rounded if necessary, is used as the1459* result. If this is zero then the result is {@code subtrahend.negate(mc)}.1460*1461* @param subtrahend value to be subtracted from this {@code BigDecimal}.1462* @param mc the context to use.1463* @return {@code this - subtrahend}, rounded as necessary.1464* @throws ArithmeticException if the result is inexact but the1465* rounding mode is {@code UNNECESSARY}.1466* @since 1.51467*/1468public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {1469if (mc.precision == 0)1470return subtract(subtrahend);1471// share the special rounding code in add()1472return add(subtrahend.negate(), mc);1473}14741475/**1476* Returns a {@code BigDecimal} whose value is <tt>(this ×1477* multiplicand)</tt>, and whose scale is {@code (this.scale() +1478* multiplicand.scale())}.1479*1480* @param multiplicand value to be multiplied by this {@code BigDecimal}.1481* @return {@code this * multiplicand}1482*/1483public BigDecimal multiply(BigDecimal multiplicand) {1484int productScale = checkScale((long) scale + multiplicand.scale);1485if (this.intCompact != INFLATED) {1486if ((multiplicand.intCompact != INFLATED)) {1487return multiply(this.intCompact, multiplicand.intCompact, productScale);1488} else {1489return multiply(this.intCompact, multiplicand.intVal, productScale);1490}1491} else {1492if ((multiplicand.intCompact != INFLATED)) {1493return multiply(multiplicand.intCompact, this.intVal, productScale);1494} else {1495return multiply(this.intVal, multiplicand.intVal, productScale);1496}1497}1498}14991500/**1501* Returns a {@code BigDecimal} whose value is <tt>(this ×1502* multiplicand)</tt>, with rounding according to the context settings.1503*1504* @param multiplicand value to be multiplied by this {@code BigDecimal}.1505* @param mc the context to use.1506* @return {@code this * multiplicand}, rounded as necessary.1507* @throws ArithmeticException if the result is inexact but the1508* rounding mode is {@code UNNECESSARY}.1509* @since 1.51510*/1511public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {1512if (mc.precision == 0)1513return multiply(multiplicand);1514int productScale = checkScale((long) scale + multiplicand.scale);1515if (this.intCompact != INFLATED) {1516if ((multiplicand.intCompact != INFLATED)) {1517return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);1518} else {1519return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);1520}1521} else {1522if ((multiplicand.intCompact != INFLATED)) {1523return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);1524} else {1525return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);1526}1527}1528}15291530/**1531* Returns a {@code BigDecimal} whose value is {@code (this /1532* divisor)}, and whose scale is as specified. If rounding must1533* be performed to generate a result with the specified scale, the1534* specified rounding mode is applied.1535*1536* <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method1537* should be used in preference to this legacy method.1538*1539* @param divisor value by which this {@code BigDecimal} is to be divided.1540* @param scale scale of the {@code BigDecimal} quotient to be returned.1541* @param roundingMode rounding mode to apply.1542* @return {@code this / divisor}1543* @throws ArithmeticException if {@code divisor} is zero,1544* {@code roundingMode==ROUND_UNNECESSARY} and1545* the specified scale is insufficient to represent the result1546* of the division exactly.1547* @throws IllegalArgumentException if {@code roundingMode} does not1548* represent a valid rounding mode.1549* @see #ROUND_UP1550* @see #ROUND_DOWN1551* @see #ROUND_CEILING1552* @see #ROUND_FLOOR1553* @see #ROUND_HALF_UP1554* @see #ROUND_HALF_DOWN1555* @see #ROUND_HALF_EVEN1556* @see #ROUND_UNNECESSARY1557*/1558public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {1559if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)1560throw new IllegalArgumentException("Invalid rounding mode");1561if (this.intCompact != INFLATED) {1562if ((divisor.intCompact != INFLATED)) {1563return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);1564} else {1565return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);1566}1567} else {1568if ((divisor.intCompact != INFLATED)) {1569return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);1570} else {1571return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);1572}1573}1574}15751576/**1577* Returns a {@code BigDecimal} whose value is {@code (this /1578* divisor)}, and whose scale is as specified. If rounding must1579* be performed to generate a result with the specified scale, the1580* specified rounding mode is applied.1581*1582* @param divisor value by which this {@code BigDecimal} is to be divided.1583* @param scale scale of the {@code BigDecimal} quotient to be returned.1584* @param roundingMode rounding mode to apply.1585* @return {@code this / divisor}1586* @throws ArithmeticException if {@code divisor} is zero,1587* {@code roundingMode==RoundingMode.UNNECESSARY} and1588* the specified scale is insufficient to represent the result1589* of the division exactly.1590* @since 1.51591*/1592public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {1593return divide(divisor, scale, roundingMode.oldMode);1594}15951596/**1597* Returns a {@code BigDecimal} whose value is {@code (this /1598* divisor)}, and whose scale is {@code this.scale()}. If1599* rounding must be performed to generate a result with the given1600* scale, the specified rounding mode is applied.1601*1602* <p>The new {@link #divide(BigDecimal, RoundingMode)} method1603* should be used in preference to this legacy method.1604*1605* @param divisor value by which this {@code BigDecimal} is to be divided.1606* @param roundingMode rounding mode to apply.1607* @return {@code this / divisor}1608* @throws ArithmeticException if {@code divisor==0}, or1609* {@code roundingMode==ROUND_UNNECESSARY} and1610* {@code this.scale()} is insufficient to represent the result1611* of the division exactly.1612* @throws IllegalArgumentException if {@code roundingMode} does not1613* represent a valid rounding mode.1614* @see #ROUND_UP1615* @see #ROUND_DOWN1616* @see #ROUND_CEILING1617* @see #ROUND_FLOOR1618* @see #ROUND_HALF_UP1619* @see #ROUND_HALF_DOWN1620* @see #ROUND_HALF_EVEN1621* @see #ROUND_UNNECESSARY1622*/1623public BigDecimal divide(BigDecimal divisor, int roundingMode) {1624return this.divide(divisor, scale, roundingMode);1625}16261627/**1628* Returns a {@code BigDecimal} whose value is {@code (this /1629* divisor)}, and whose scale is {@code this.scale()}. If1630* rounding must be performed to generate a result with the given1631* scale, the specified rounding mode is applied.1632*1633* @param divisor value by which this {@code BigDecimal} is to be divided.1634* @param roundingMode rounding mode to apply.1635* @return {@code this / divisor}1636* @throws ArithmeticException if {@code divisor==0}, or1637* {@code roundingMode==RoundingMode.UNNECESSARY} and1638* {@code this.scale()} is insufficient to represent the result1639* of the division exactly.1640* @since 1.51641*/1642public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {1643return this.divide(divisor, scale, roundingMode.oldMode);1644}16451646/**1647* Returns a {@code BigDecimal} whose value is {@code (this /1648* divisor)}, and whose preferred scale is {@code (this.scale() -1649* divisor.scale())}; if the exact quotient cannot be1650* represented (because it has a non-terminating decimal1651* expansion) an {@code ArithmeticException} is thrown.1652*1653* @param divisor value by which this {@code BigDecimal} is to be divided.1654* @throws ArithmeticException if the exact quotient does not have a1655* terminating decimal expansion1656* @return {@code this / divisor}1657* @since 1.51658* @author Joseph D. Darcy1659*/1660public BigDecimal divide(BigDecimal divisor) {1661/*1662* Handle zero cases first.1663*/1664if (divisor.signum() == 0) { // x/01665if (this.signum() == 0) // 0/01666throw new ArithmeticException("Division undefined"); // NaN1667throw new ArithmeticException("Division by zero");1668}16691670// Calculate preferred scale1671int preferredScale = saturateLong((long) this.scale - divisor.scale);16721673if (this.signum() == 0) // 0/y1674return zeroValueOf(preferredScale);1675else {1676/*1677* If the quotient this/divisor has a terminating decimal1678* expansion, the expansion can have no more than1679* (a.precision() + ceil(10*b.precision)/3) digits.1680* Therefore, create a MathContext object with this1681* precision and do a divide with the UNNECESSARY rounding1682* mode.1683*/1684MathContext mc = new MathContext( (int)Math.min(this.precision() +1685(long)Math.ceil(10.0*divisor.precision()/3.0),1686Integer.MAX_VALUE),1687RoundingMode.UNNECESSARY);1688BigDecimal quotient;1689try {1690quotient = this.divide(divisor, mc);1691} catch (ArithmeticException e) {1692throw new ArithmeticException("Non-terminating decimal expansion; " +1693"no exact representable decimal result.");1694}16951696int quotientScale = quotient.scale();16971698// divide(BigDecimal, mc) tries to adjust the quotient to1699// the desired one by removing trailing zeros; since the1700// exact divide method does not have an explicit digit1701// limit, we can add zeros too.1702if (preferredScale > quotientScale)1703return quotient.setScale(preferredScale, ROUND_UNNECESSARY);17041705return quotient;1706}1707}17081709/**1710* Returns a {@code BigDecimal} whose value is {@code (this /1711* divisor)}, with rounding according to the context settings.1712*1713* @param divisor value by which this {@code BigDecimal} is to be divided.1714* @param mc the context to use.1715* @return {@code this / divisor}, rounded as necessary.1716* @throws ArithmeticException if the result is inexact but the1717* rounding mode is {@code UNNECESSARY} or1718* {@code mc.precision == 0} and the quotient has a1719* non-terminating decimal expansion.1720* @since 1.51721*/1722public BigDecimal divide(BigDecimal divisor, MathContext mc) {1723int mcp = mc.precision;1724if (mcp == 0)1725return divide(divisor);17261727BigDecimal dividend = this;1728long preferredScale = (long)dividend.scale - divisor.scale;1729// Now calculate the answer. We use the existing1730// divide-and-round method, but as this rounds to scale we have1731// to normalize the values here to achieve the desired result.1732// For x/y we first handle y=0 and x=0, and then normalize x and1733// y to give x' and y' with the following constraints:1734// (a) 0.1 <= x' < 11735// (b) x' <= y' < 10*x'1736// Dividing x'/y' with the required scale set to mc.precision then1737// will give a result in the range 0.1 to 1 rounded to exactly1738// the right number of digits (except in the case of a result of1739// 1.000... which can arise when x=y, or when rounding overflows1740// The 1.000... case will reduce properly to 1.1741if (divisor.signum() == 0) { // x/01742if (dividend.signum() == 0) // 0/01743throw new ArithmeticException("Division undefined"); // NaN1744throw new ArithmeticException("Division by zero");1745}1746if (dividend.signum() == 0) // 0/y1747return zeroValueOf(saturateLong(preferredScale));1748int xscale = dividend.precision();1749int yscale = divisor.precision();1750if(dividend.intCompact!=INFLATED) {1751if(divisor.intCompact!=INFLATED) {1752return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);1753} else {1754return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);1755}1756} else {1757if(divisor.intCompact!=INFLATED) {1758return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);1759} else {1760return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);1761}1762}1763}17641765/**1766* Returns a {@code BigDecimal} whose value is the integer part1767* of the quotient {@code (this / divisor)} rounded down. The1768* preferred scale of the result is {@code (this.scale() -1769* divisor.scale())}.1770*1771* @param divisor value by which this {@code BigDecimal} is to be divided.1772* @return The integer part of {@code this / divisor}.1773* @throws ArithmeticException if {@code divisor==0}1774* @since 1.51775*/1776public BigDecimal divideToIntegralValue(BigDecimal divisor) {1777// Calculate preferred scale1778int preferredScale = saturateLong((long) this.scale - divisor.scale);1779if (this.compareMagnitude(divisor) < 0) {1780// much faster when this << divisor1781return zeroValueOf(preferredScale);1782}17831784if (this.signum() == 0 && divisor.signum() != 0)1785return this.setScale(preferredScale, ROUND_UNNECESSARY);17861787// Perform a divide with enough digits to round to a correct1788// integer value; then remove any fractional digits17891790int maxDigits = (int)Math.min(this.precision() +1791(long)Math.ceil(10.0*divisor.precision()/3.0) +1792Math.abs((long)this.scale() - divisor.scale()) + 2,1793Integer.MAX_VALUE);1794BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,1795RoundingMode.DOWN));1796if (quotient.scale > 0) {1797quotient = quotient.setScale(0, RoundingMode.DOWN);1798quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);1799}18001801if (quotient.scale < preferredScale) {1802// pad with zeros if necessary1803quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);1804}18051806return quotient;1807}18081809/**1810* Returns a {@code BigDecimal} whose value is the integer part1811* of {@code (this / divisor)}. Since the integer part of the1812* exact quotient does not depend on the rounding mode, the1813* rounding mode does not affect the values returned by this1814* method. The preferred scale of the result is1815* {@code (this.scale() - divisor.scale())}. An1816* {@code ArithmeticException} is thrown if the integer part of1817* the exact quotient needs more than {@code mc.precision}1818* digits.1819*1820* @param divisor value by which this {@code BigDecimal} is to be divided.1821* @param mc the context to use.1822* @return The integer part of {@code this / divisor}.1823* @throws ArithmeticException if {@code divisor==0}1824* @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result1825* requires a precision of more than {@code mc.precision} digits.1826* @since 1.51827* @author Joseph D. Darcy1828*/1829public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {1830if (mc.precision == 0 || // exact result1831(this.compareMagnitude(divisor) < 0)) // zero result1832return divideToIntegralValue(divisor);18331834// Calculate preferred scale1835int preferredScale = saturateLong((long)this.scale - divisor.scale);18361837/*1838* Perform a normal divide to mc.precision digits. If the1839* remainder has absolute value less than the divisor, the1840* integer portion of the quotient fits into mc.precision1841* digits. Next, remove any fractional digits from the1842* quotient and adjust the scale to the preferred value.1843*/1844BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));18451846if (result.scale() < 0) {1847/*1848* Result is an integer. See if quotient represents the1849* full integer portion of the exact quotient; if it does,1850* the computed remainder will be less than the divisor.1851*/1852BigDecimal product = result.multiply(divisor);1853// If the quotient is the full integer value,1854// |dividend-product| < |divisor|.1855if (this.subtract(product).compareMagnitude(divisor) >= 0) {1856throw new ArithmeticException("Division impossible");1857}1858} else if (result.scale() > 0) {1859/*1860* Integer portion of quotient will fit into precision1861* digits; recompute quotient to scale 0 to avoid double1862* rounding and then try to adjust, if necessary.1863*/1864result = result.setScale(0, RoundingMode.DOWN);1865}1866// else result.scale() == 0;18671868int precisionDiff;1869if ((preferredScale > result.scale()) &&1870(precisionDiff = mc.precision - result.precision()) > 0) {1871return result.setScale(result.scale() +1872Math.min(precisionDiff, preferredScale - result.scale) );1873} else {1874return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);1875}1876}18771878/**1879* Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.1880*1881* <p>The remainder is given by1882* {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.1883* Note that this is not the modulo operation (the result can be1884* negative).1885*1886* @param divisor value by which this {@code BigDecimal} is to be divided.1887* @return {@code this % divisor}.1888* @throws ArithmeticException if {@code divisor==0}1889* @since 1.51890*/1891public BigDecimal remainder(BigDecimal divisor) {1892BigDecimal divrem[] = this.divideAndRemainder(divisor);1893return divrem[1];1894}189518961897/**1898* Returns a {@code BigDecimal} whose value is {@code (this %1899* divisor)}, with rounding according to the context settings.1900* The {@code MathContext} settings affect the implicit divide1901* used to compute the remainder. The remainder computation1902* itself is by definition exact. Therefore, the remainder may1903* contain more than {@code mc.getPrecision()} digits.1904*1905* <p>The remainder is given by1906* {@code this.subtract(this.divideToIntegralValue(divisor,1907* mc).multiply(divisor))}. Note that this is not the modulo1908* operation (the result can be negative).1909*1910* @param divisor value by which this {@code BigDecimal} is to be divided.1911* @param mc the context to use.1912* @return {@code this % divisor}, rounded as necessary.1913* @throws ArithmeticException if {@code divisor==0}1914* @throws ArithmeticException if the result is inexact but the1915* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}1916* {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would1917* require a precision of more than {@code mc.precision} digits.1918* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)1919* @since 1.51920*/1921public BigDecimal remainder(BigDecimal divisor, MathContext mc) {1922BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);1923return divrem[1];1924}19251926/**1927* Returns a two-element {@code BigDecimal} array containing the1928* result of {@code divideToIntegralValue} followed by the result of1929* {@code remainder} on the two operands.1930*1931* <p>Note that if both the integer quotient and remainder are1932* needed, this method is faster than using the1933* {@code divideToIntegralValue} and {@code remainder} methods1934* separately because the division need only be carried out once.1935*1936* @param divisor value by which this {@code BigDecimal} is to be divided,1937* and the remainder computed.1938* @return a two element {@code BigDecimal} array: the quotient1939* (the result of {@code divideToIntegralValue}) is the initial element1940* and the remainder is the final element.1941* @throws ArithmeticException if {@code divisor==0}1942* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)1943* @see #remainder(java.math.BigDecimal, java.math.MathContext)1944* @since 1.51945*/1946public BigDecimal[] divideAndRemainder(BigDecimal divisor) {1947// we use the identity x = i * y + r to determine r1948BigDecimal[] result = new BigDecimal[2];19491950result[0] = this.divideToIntegralValue(divisor);1951result[1] = this.subtract(result[0].multiply(divisor));1952return result;1953}19541955/**1956* Returns a two-element {@code BigDecimal} array containing the1957* result of {@code divideToIntegralValue} followed by the result of1958* {@code remainder} on the two operands calculated with rounding1959* according to the context settings.1960*1961* <p>Note that if both the integer quotient and remainder are1962* needed, this method is faster than using the1963* {@code divideToIntegralValue} and {@code remainder} methods1964* separately because the division need only be carried out once.1965*1966* @param divisor value by which this {@code BigDecimal} is to be divided,1967* and the remainder computed.1968* @param mc the context to use.1969* @return a two element {@code BigDecimal} array: the quotient1970* (the result of {@code divideToIntegralValue}) is the1971* initial element and the remainder is the final element.1972* @throws ArithmeticException if {@code divisor==0}1973* @throws ArithmeticException if the result is inexact but the1974* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}1975* {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would1976* require a precision of more than {@code mc.precision} digits.1977* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)1978* @see #remainder(java.math.BigDecimal, java.math.MathContext)1979* @since 1.51980*/1981public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {1982if (mc.precision == 0)1983return divideAndRemainder(divisor);19841985BigDecimal[] result = new BigDecimal[2];1986BigDecimal lhs = this;19871988result[0] = lhs.divideToIntegralValue(divisor, mc);1989result[1] = lhs.subtract(result[0].multiply(divisor));1990return result;1991}19921993/**1994* Returns a {@code BigDecimal} whose value is1995* <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to1996* unlimited precision.1997*1998* <p>The parameter {@code n} must be in the range 0 through1999* 999999999, inclusive. {@code ZERO.pow(0)} returns {@link2000* #ONE}.2001*2002* Note that future releases may expand the allowable exponent2003* range of this method.2004*2005* @param n power to raise this {@code BigDecimal} to.2006* @return <tt>this<sup>n</sup></tt>2007* @throws ArithmeticException if {@code n} is out of range.2008* @since 1.52009*/2010public BigDecimal pow(int n) {2011if (n < 0 || n > 999999999)2012throw new ArithmeticException("Invalid operation");2013// No need to calculate pow(n) if result will over/underflow.2014// Don't attempt to support "supernormal" numbers.2015int newScale = checkScale((long)scale * n);2016return new BigDecimal(this.inflated().pow(n), newScale);2017}201820192020/**2021* Returns a {@code BigDecimal} whose value is2022* <tt>(this<sup>n</sup>)</tt>. The current implementation uses2023* the core algorithm defined in ANSI standard X3.274-1996 with2024* rounding according to the context settings. In general, the2025* returned numerical value is within two ulps of the exact2026* numerical value for the chosen precision. Note that future2027* releases may use a different algorithm with a decreased2028* allowable error bound and increased allowable exponent range.2029*2030* <p>The X3.274-1996 algorithm is:2031*2032* <ul>2033* <li> An {@code ArithmeticException} exception is thrown if2034* <ul>2035* <li>{@code abs(n) > 999999999}2036* <li>{@code mc.precision == 0} and {@code n < 0}2037* <li>{@code mc.precision > 0} and {@code n} has more than2038* {@code mc.precision} decimal digits2039* </ul>2040*2041* <li> if {@code n} is zero, {@link #ONE} is returned even if2042* {@code this} is zero, otherwise2043* <ul>2044* <li> if {@code n} is positive, the result is calculated via2045* the repeated squaring technique into a single accumulator.2046* The individual multiplications with the accumulator use the2047* same math context settings as in {@code mc} except for a2048* precision increased to {@code mc.precision + elength + 1}2049* where {@code elength} is the number of decimal digits in2050* {@code n}.2051*2052* <li> if {@code n} is negative, the result is calculated as if2053* {@code n} were positive; this value is then divided into one2054* using the working precision specified above.2055*2056* <li> The final value from either the positive or negative case2057* is then rounded to the destination precision.2058* </ul>2059* </ul>2060*2061* @param n power to raise this {@code BigDecimal} to.2062* @param mc the context to use.2063* @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-19962064* algorithm2065* @throws ArithmeticException if the result is inexact but the2066* rounding mode is {@code UNNECESSARY}, or {@code n} is out2067* of range.2068* @since 1.52069*/2070public BigDecimal pow(int n, MathContext mc) {2071if (mc.precision == 0)2072return pow(n);2073if (n < -999999999 || n > 999999999)2074throw new ArithmeticException("Invalid operation");2075if (n == 0)2076return ONE; // x**0 == 1 in X3.2742077BigDecimal lhs = this;2078MathContext workmc = mc; // working settings2079int mag = Math.abs(n); // magnitude of n2080if (mc.precision > 0) {2081int elength = longDigitLength(mag); // length of n in digits2082if (elength > mc.precision) // X3.274 rule2083throw new ArithmeticException("Invalid operation");2084workmc = new MathContext(mc.precision + elength + 1,2085mc.roundingMode);2086}2087// ready to carry out power calculation...2088BigDecimal acc = ONE; // accumulator2089boolean seenbit = false; // set once we've seen a 1-bit2090for (int i=1;;i++) { // for each bit [top bit ignored]2091mag += mag; // shift left 1 bit2092if (mag < 0) { // top bit is set2093seenbit = true; // OK, we're off2094acc = acc.multiply(lhs, workmc); // acc=acc*x2095}2096if (i == 31)2097break; // that was the last bit2098if (seenbit)2099acc=acc.multiply(acc, workmc); // acc=acc*acc [square]2100// else (!seenbit) no point in squaring ONE2101}2102// if negative n, calculate the reciprocal using working precision2103if (n < 0) // [hence mc.precision>0]2104acc=ONE.divide(acc, workmc);2105// round to final precision and strip zeros2106return doRound(acc, mc);2107}21082109/**2110* Returns a {@code BigDecimal} whose value is the absolute value2111* of this {@code BigDecimal}, and whose scale is2112* {@code this.scale()}.2113*2114* @return {@code abs(this)}2115*/2116public BigDecimal abs() {2117return (signum() < 0 ? negate() : this);2118}21192120/**2121* Returns a {@code BigDecimal} whose value is the absolute value2122* of this {@code BigDecimal}, with rounding according to the2123* context settings.2124*2125* @param mc the context to use.2126* @return {@code abs(this)}, rounded as necessary.2127* @throws ArithmeticException if the result is inexact but the2128* rounding mode is {@code UNNECESSARY}.2129* @since 1.52130*/2131public BigDecimal abs(MathContext mc) {2132return (signum() < 0 ? negate(mc) : plus(mc));2133}21342135/**2136* Returns a {@code BigDecimal} whose value is {@code (-this)},2137* and whose scale is {@code this.scale()}.2138*2139* @return {@code -this}.2140*/2141public BigDecimal negate() {2142if (intCompact == INFLATED) {2143return new BigDecimal(intVal.negate(), INFLATED, scale, precision);2144} else {2145return valueOf(-intCompact, scale, precision);2146}2147}21482149/**2150* Returns a {@code BigDecimal} whose value is {@code (-this)},2151* with rounding according to the context settings.2152*2153* @param mc the context to use.2154* @return {@code -this}, rounded as necessary.2155* @throws ArithmeticException if the result is inexact but the2156* rounding mode is {@code UNNECESSARY}.2157* @since 1.52158*/2159public BigDecimal negate(MathContext mc) {2160return negate().plus(mc);2161}21622163/**2164* Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose2165* scale is {@code this.scale()}.2166*2167* <p>This method, which simply returns this {@code BigDecimal}2168* is included for symmetry with the unary minus method {@link2169* #negate()}.2170*2171* @return {@code this}.2172* @see #negate()2173* @since 1.52174*/2175public BigDecimal plus() {2176return this;2177}21782179/**2180* Returns a {@code BigDecimal} whose value is {@code (+this)},2181* with rounding according to the context settings.2182*2183* <p>The effect of this method is identical to that of the {@link2184* #round(MathContext)} method.2185*2186* @param mc the context to use.2187* @return {@code this}, rounded as necessary. A zero result will2188* have a scale of 0.2189* @throws ArithmeticException if the result is inexact but the2190* rounding mode is {@code UNNECESSARY}.2191* @see #round(MathContext)2192* @since 1.52193*/2194public BigDecimal plus(MathContext mc) {2195if (mc.precision == 0) // no rounding please2196return this;2197return doRound(this, mc);2198}21992200/**2201* Returns the signum function of this {@code BigDecimal}.2202*2203* @return -1, 0, or 1 as the value of this {@code BigDecimal}2204* is negative, zero, or positive.2205*/2206public int signum() {2207return (intCompact != INFLATED)?2208Long.signum(intCompact):2209intVal.signum();2210}22112212/**2213* Returns the <i>scale</i> of this {@code BigDecimal}. If zero2214* or positive, the scale is the number of digits to the right of2215* the decimal point. If negative, the unscaled value of the2216* number is multiplied by ten to the power of the negation of the2217* scale. For example, a scale of {@code -3} means the unscaled2218* value is multiplied by 1000.2219*2220* @return the scale of this {@code BigDecimal}.2221*/2222public int scale() {2223return scale;2224}22252226/**2227* Returns the <i>precision</i> of this {@code BigDecimal}. (The2228* precision is the number of digits in the unscaled value.)2229*2230* <p>The precision of a zero value is 1.2231*2232* @return the precision of this {@code BigDecimal}.2233* @since 1.52234*/2235public int precision() {2236int result = precision;2237if (result == 0) {2238long s = intCompact;2239if (s != INFLATED)2240result = longDigitLength(s);2241else2242result = bigDigitLength(intVal);2243precision = result;2244}2245return result;2246}224722482249/**2250* Returns a {@code BigInteger} whose value is the <i>unscaled2251* value</i> of this {@code BigDecimal}. (Computes <tt>(this *2252* 10<sup>this.scale()</sup>)</tt>.)2253*2254* @return the unscaled value of this {@code BigDecimal}.2255* @since 1.22256*/2257public BigInteger unscaledValue() {2258return this.inflated();2259}22602261// Rounding Modes22622263/**2264* Rounding mode to round away from zero. Always increments the2265* digit prior to a nonzero discarded fraction. Note that this rounding2266* mode never decreases the magnitude of the calculated value.2267*/2268public final static int ROUND_UP = 0;22692270/**2271* Rounding mode to round towards zero. Never increments the digit2272* prior to a discarded fraction (i.e., truncates). Note that this2273* rounding mode never increases the magnitude of the calculated value.2274*/2275public final static int ROUND_DOWN = 1;22762277/**2278* Rounding mode to round towards positive infinity. If the2279* {@code BigDecimal} is positive, behaves as for2280* {@code ROUND_UP}; if negative, behaves as for2281* {@code ROUND_DOWN}. Note that this rounding mode never2282* decreases the calculated value.2283*/2284public final static int ROUND_CEILING = 2;22852286/**2287* Rounding mode to round towards negative infinity. If the2288* {@code BigDecimal} is positive, behave as for2289* {@code ROUND_DOWN}; if negative, behave as for2290* {@code ROUND_UP}. Note that this rounding mode never2291* increases the calculated value.2292*/2293public final static int ROUND_FLOOR = 3;22942295/**2296* Rounding mode to round towards {@literal "nearest neighbor"}2297* unless both neighbors are equidistant, in which case round up.2298* Behaves as for {@code ROUND_UP} if the discarded fraction is2299* ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note2300* that this is the rounding mode that most of us were taught in2301* grade school.2302*/2303public final static int ROUND_HALF_UP = 4;23042305/**2306* Rounding mode to round towards {@literal "nearest neighbor"}2307* unless both neighbors are equidistant, in which case round2308* down. Behaves as for {@code ROUND_UP} if the discarded2309* fraction is {@literal >} 0.5; otherwise, behaves as for2310* {@code ROUND_DOWN}.2311*/2312public final static int ROUND_HALF_DOWN = 5;23132314/**2315* Rounding mode to round towards the {@literal "nearest neighbor"}2316* unless both neighbors are equidistant, in which case, round2317* towards the even neighbor. Behaves as for2318* {@code ROUND_HALF_UP} if the digit to the left of the2319* discarded fraction is odd; behaves as for2320* {@code ROUND_HALF_DOWN} if it's even. Note that this is the2321* rounding mode that minimizes cumulative error when applied2322* repeatedly over a sequence of calculations.2323*/2324public final static int ROUND_HALF_EVEN = 6;23252326/**2327* Rounding mode to assert that the requested operation has an exact2328* result, hence no rounding is necessary. If this rounding mode is2329* specified on an operation that yields an inexact result, an2330* {@code ArithmeticException} is thrown.2331*/2332public final static int ROUND_UNNECESSARY = 7;233323342335// Scaling/Rounding Operations23362337/**2338* Returns a {@code BigDecimal} rounded according to the2339* {@code MathContext} settings. If the precision setting is 0 then2340* no rounding takes place.2341*2342* <p>The effect of this method is identical to that of the2343* {@link #plus(MathContext)} method.2344*2345* @param mc the context to use.2346* @return a {@code BigDecimal} rounded according to the2347* {@code MathContext} settings.2348* @throws ArithmeticException if the rounding mode is2349* {@code UNNECESSARY} and the2350* {@code BigDecimal} operation would require rounding.2351* @see #plus(MathContext)2352* @since 1.52353*/2354public BigDecimal round(MathContext mc) {2355return plus(mc);2356}23572358/**2359* Returns a {@code BigDecimal} whose scale is the specified2360* value, and whose unscaled value is determined by multiplying or2361* dividing this {@code BigDecimal}'s unscaled value by the2362* appropriate power of ten to maintain its overall value. If the2363* scale is reduced by the operation, the unscaled value must be2364* divided (rather than multiplied), and the value may be changed;2365* in this case, the specified rounding mode is applied to the2366* division.2367*2368* <p>Note that since BigDecimal objects are immutable, calls of2369* this method do <i>not</i> result in the original object being2370* modified, contrary to the usual convention of having methods2371* named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.2372* Instead, {@code setScale} returns an object with the proper2373* scale; the returned object may or may not be newly allocated.2374*2375* @param newScale scale of the {@code BigDecimal} value to be returned.2376* @param roundingMode The rounding mode to apply.2377* @return a {@code BigDecimal} whose scale is the specified value,2378* and whose unscaled value is determined by multiplying or2379* dividing this {@code BigDecimal}'s unscaled value by the2380* appropriate power of ten to maintain its overall value.2381* @throws ArithmeticException if {@code roundingMode==UNNECESSARY}2382* and the specified scaling operation would require2383* rounding.2384* @see RoundingMode2385* @since 1.52386*/2387public BigDecimal setScale(int newScale, RoundingMode roundingMode) {2388return setScale(newScale, roundingMode.oldMode);2389}23902391/**2392* Returns a {@code BigDecimal} whose scale is the specified2393* value, and whose unscaled value is determined by multiplying or2394* dividing this {@code BigDecimal}'s unscaled value by the2395* appropriate power of ten to maintain its overall value. If the2396* scale is reduced by the operation, the unscaled value must be2397* divided (rather than multiplied), and the value may be changed;2398* in this case, the specified rounding mode is applied to the2399* division.2400*2401* <p>Note that since BigDecimal objects are immutable, calls of2402* this method do <i>not</i> result in the original object being2403* modified, contrary to the usual convention of having methods2404* named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.2405* Instead, {@code setScale} returns an object with the proper2406* scale; the returned object may or may not be newly allocated.2407*2408* <p>The new {@link #setScale(int, RoundingMode)} method should2409* be used in preference to this legacy method.2410*2411* @param newScale scale of the {@code BigDecimal} value to be returned.2412* @param roundingMode The rounding mode to apply.2413* @return a {@code BigDecimal} whose scale is the specified value,2414* and whose unscaled value is determined by multiplying or2415* dividing this {@code BigDecimal}'s unscaled value by the2416* appropriate power of ten to maintain its overall value.2417* @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}2418* and the specified scaling operation would require2419* rounding.2420* @throws IllegalArgumentException if {@code roundingMode} does not2421* represent a valid rounding mode.2422* @see #ROUND_UP2423* @see #ROUND_DOWN2424* @see #ROUND_CEILING2425* @see #ROUND_FLOOR2426* @see #ROUND_HALF_UP2427* @see #ROUND_HALF_DOWN2428* @see #ROUND_HALF_EVEN2429* @see #ROUND_UNNECESSARY2430*/2431public BigDecimal setScale(int newScale, int roundingMode) {2432if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)2433throw new IllegalArgumentException("Invalid rounding mode");24342435int oldScale = this.scale;2436if (newScale == oldScale) // easy case2437return this;2438if (this.signum() == 0) // zero can have any scale2439return zeroValueOf(newScale);2440if(this.intCompact!=INFLATED) {2441long rs = this.intCompact;2442if (newScale > oldScale) {2443int raise = checkScale((long) newScale - oldScale);2444if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {2445return valueOf(rs,newScale);2446}2447BigInteger rb = bigMultiplyPowerTen(raise);2448return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);2449} else {2450// newScale < oldScale -- drop some digits2451// Can't predict the precision due to the effect of rounding.2452int drop = checkScale((long) oldScale - newScale);2453if (drop < LONG_TEN_POWERS_TABLE.length) {2454return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);2455} else {2456return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);2457}2458}2459} else {2460if (newScale > oldScale) {2461int raise = checkScale((long) newScale - oldScale);2462BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);2463return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);2464} else {2465// newScale < oldScale -- drop some digits2466// Can't predict the precision due to the effect of rounding.2467int drop = checkScale((long) oldScale - newScale);2468if (drop < LONG_TEN_POWERS_TABLE.length)2469return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,2470newScale);2471else2472return divideAndRound(this.intVal, bigTenToThe(drop), newScale, roundingMode, newScale);2473}2474}2475}24762477/**2478* Returns a {@code BigDecimal} whose scale is the specified2479* value, and whose value is numerically equal to this2480* {@code BigDecimal}'s. Throws an {@code ArithmeticException}2481* if this is not possible.2482*2483* <p>This call is typically used to increase the scale, in which2484* case it is guaranteed that there exists a {@code BigDecimal}2485* of the specified scale and the correct value. The call can2486* also be used to reduce the scale if the caller knows that the2487* {@code BigDecimal} has sufficiently many zeros at the end of2488* its fractional part (i.e., factors of ten in its integer value)2489* to allow for the rescaling without changing its value.2490*2491* <p>This method returns the same result as the two-argument2492* versions of {@code setScale}, but saves the caller the trouble2493* of specifying a rounding mode in cases where it is irrelevant.2494*2495* <p>Note that since {@code BigDecimal} objects are immutable,2496* calls of this method do <i>not</i> result in the original2497* object being modified, contrary to the usual convention of2498* having methods named <tt>set<i>X</i></tt> mutate field2499* <i>{@code X}</i>. Instead, {@code setScale} returns an2500* object with the proper scale; the returned object may or may2501* not be newly allocated.2502*2503* @param newScale scale of the {@code BigDecimal} value to be returned.2504* @return a {@code BigDecimal} whose scale is the specified value, and2505* whose unscaled value is determined by multiplying or dividing2506* this {@code BigDecimal}'s unscaled value by the appropriate2507* power of ten to maintain its overall value.2508* @throws ArithmeticException if the specified scaling operation would2509* require rounding.2510* @see #setScale(int, int)2511* @see #setScale(int, RoundingMode)2512*/2513public BigDecimal setScale(int newScale) {2514return setScale(newScale, ROUND_UNNECESSARY);2515}25162517// Decimal Point Motion Operations25182519/**2520* Returns a {@code BigDecimal} which is equivalent to this one2521* with the decimal point moved {@code n} places to the left. If2522* {@code n} is non-negative, the call merely adds {@code n} to2523* the scale. If {@code n} is negative, the call is equivalent2524* to {@code movePointRight(-n)}. The {@code BigDecimal}2525* returned by this call has value <tt>(this ×2526* 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,2527* 0)}.2528*2529* @param n number of places to move the decimal point to the left.2530* @return a {@code BigDecimal} which is equivalent to this one with the2531* decimal point moved {@code n} places to the left.2532* @throws ArithmeticException if scale overflows.2533*/2534public BigDecimal movePointLeft(int n) {2535// Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE2536int newScale = checkScale((long)scale + n);2537BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);2538return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;2539}25402541/**2542* Returns a {@code BigDecimal} which is equivalent to this one2543* with the decimal point moved {@code n} places to the right.2544* If {@code n} is non-negative, the call merely subtracts2545* {@code n} from the scale. If {@code n} is negative, the call2546* is equivalent to {@code movePointLeft(-n)}. The2547* {@code BigDecimal} returned by this call has value <tt>(this2548* × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,2549* 0)}.2550*2551* @param n number of places to move the decimal point to the right.2552* @return a {@code BigDecimal} which is equivalent to this one2553* with the decimal point moved {@code n} places to the right.2554* @throws ArithmeticException if scale overflows.2555*/2556public BigDecimal movePointRight(int n) {2557// Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE2558int newScale = checkScale((long)scale - n);2559BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);2560return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;2561}25622563/**2564* Returns a BigDecimal whose numerical value is equal to2565* ({@code this} * 10<sup>n</sup>). The scale of2566* the result is {@code (this.scale() - n)}.2567*2568* @param n the exponent power of ten to scale by2569* @return a BigDecimal whose numerical value is equal to2570* ({@code this} * 10<sup>n</sup>)2571* @throws ArithmeticException if the scale would be2572* outside the range of a 32-bit integer.2573*2574* @since 1.52575*/2576public BigDecimal scaleByPowerOfTen(int n) {2577return new BigDecimal(intVal, intCompact,2578checkScale((long)scale - n), precision);2579}25802581/**2582* Returns a {@code BigDecimal} which is numerically equal to2583* this one but with any trailing zeros removed from the2584* representation. For example, stripping the trailing zeros from2585* the {@code BigDecimal} value {@code 600.0}, which has2586* [{@code BigInteger}, {@code scale}] components equals to2587* [6000, 1], yields {@code 6E2} with [{@code BigInteger},2588* {@code scale}] components equals to [6, -2]. If2589* this BigDecimal is numerically equal to zero, then2590* {@code BigDecimal.ZERO} is returned.2591*2592* @return a numerically equal {@code BigDecimal} with any2593* trailing zeros removed.2594* @since 1.52595*/2596public BigDecimal stripTrailingZeros() {2597if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {2598return BigDecimal.ZERO;2599} else if (intCompact != INFLATED) {2600return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);2601} else {2602return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);2603}2604}26052606// Comparison Operations26072608/**2609* Compares this {@code BigDecimal} with the specified2610* {@code BigDecimal}. Two {@code BigDecimal} objects that are2611* equal in value but have a different scale (like 2.0 and 2.00)2612* are considered equal by this method. This method is provided2613* in preference to individual methods for each of the six boolean2614* comparison operators ({@literal <}, ==,2615* {@literal >}, {@literal >=}, !=, {@literal <=}). The2616* suggested idiom for performing these comparisons is:2617* {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where2618* <<i>op</i>> is one of the six comparison operators.2619*2620* @param val {@code BigDecimal} to which this {@code BigDecimal} is2621* to be compared.2622* @return -1, 0, or 1 as this {@code BigDecimal} is numerically2623* less than, equal to, or greater than {@code val}.2624*/2625public int compareTo(BigDecimal val) {2626// Quick path for equal scale and non-inflated case.2627if (scale == val.scale) {2628long xs = intCompact;2629long ys = val.intCompact;2630if (xs != INFLATED && ys != INFLATED)2631return xs != ys ? ((xs > ys) ? 1 : -1) : 0;2632}2633int xsign = this.signum();2634int ysign = val.signum();2635if (xsign != ysign)2636return (xsign > ysign) ? 1 : -1;2637if (xsign == 0)2638return 0;2639int cmp = compareMagnitude(val);2640return (xsign > 0) ? cmp : -cmp;2641}26422643/**2644* Version of compareTo that ignores sign.2645*/2646private int compareMagnitude(BigDecimal val) {2647// Match scales, avoid unnecessary inflation2648long ys = val.intCompact;2649long xs = this.intCompact;2650if (xs == 0)2651return (ys == 0) ? 0 : -1;2652if (ys == 0)2653return 1;26542655long sdiff = (long)this.scale - val.scale;2656if (sdiff != 0) {2657// Avoid matching scales if the (adjusted) exponents differ2658long xae = (long)this.precision() - this.scale; // [-1]2659long yae = (long)val.precision() - val.scale; // [-1]2660if (xae < yae)2661return -1;2662if (xae > yae)2663return 1;2664BigInteger rb = null;2665if (sdiff < 0) {2666// The cases sdiff <= Integer.MIN_VALUE intentionally fall through.2667if ( sdiff > Integer.MIN_VALUE &&2668(xs == INFLATED ||2669(xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&2670ys == INFLATED) {2671rb = bigMultiplyPowerTen((int)-sdiff);2672return rb.compareMagnitude(val.intVal);2673}2674} else { // sdiff > 02675// The cases sdiff > Integer.MAX_VALUE intentionally fall through.2676if ( sdiff <= Integer.MAX_VALUE &&2677(ys == INFLATED ||2678(ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&2679xs == INFLATED) {2680rb = val.bigMultiplyPowerTen((int)sdiff);2681return this.intVal.compareMagnitude(rb);2682}2683}2684}2685if (xs != INFLATED)2686return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;2687else if (ys != INFLATED)2688return 1;2689else2690return this.intVal.compareMagnitude(val.intVal);2691}26922693/**2694* Compares this {@code BigDecimal} with the specified2695* {@code Object} for equality. Unlike {@link2696* #compareTo(BigDecimal) compareTo}, this method considers two2697* {@code BigDecimal} objects equal only if they are equal in2698* value and scale (thus 2.0 is not equal to 2.00 when compared by2699* this method).2700*2701* @param x {@code Object} to which this {@code BigDecimal} is2702* to be compared.2703* @return {@code true} if and only if the specified {@code Object} is a2704* {@code BigDecimal} whose value and scale are equal to this2705* {@code BigDecimal}'s.2706* @see #compareTo(java.math.BigDecimal)2707* @see #hashCode2708*/2709@Override2710public boolean equals(Object x) {2711if (!(x instanceof BigDecimal))2712return false;2713BigDecimal xDec = (BigDecimal) x;2714if (x == this)2715return true;2716if (scale != xDec.scale)2717return false;2718long s = this.intCompact;2719long xs = xDec.intCompact;2720if (s != INFLATED) {2721if (xs == INFLATED)2722xs = compactValFor(xDec.intVal);2723return xs == s;2724} else if (xs != INFLATED)2725return xs == compactValFor(this.intVal);27262727return this.inflated().equals(xDec.inflated());2728}27292730/**2731* Returns the minimum of this {@code BigDecimal} and2732* {@code val}.2733*2734* @param val value with which the minimum is to be computed.2735* @return the {@code BigDecimal} whose value is the lesser of this2736* {@code BigDecimal} and {@code val}. If they are equal,2737* as defined by the {@link #compareTo(BigDecimal) compareTo}2738* method, {@code this} is returned.2739* @see #compareTo(java.math.BigDecimal)2740*/2741public BigDecimal min(BigDecimal val) {2742return (compareTo(val) <= 0 ? this : val);2743}27442745/**2746* Returns the maximum of this {@code BigDecimal} and {@code val}.2747*2748* @param val value with which the maximum is to be computed.2749* @return the {@code BigDecimal} whose value is the greater of this2750* {@code BigDecimal} and {@code val}. If they are equal,2751* as defined by the {@link #compareTo(BigDecimal) compareTo}2752* method, {@code this} is returned.2753* @see #compareTo(java.math.BigDecimal)2754*/2755public BigDecimal max(BigDecimal val) {2756return (compareTo(val) >= 0 ? this : val);2757}27582759// Hash Function27602761/**2762* Returns the hash code for this {@code BigDecimal}. Note that2763* two {@code BigDecimal} objects that are numerically equal but2764* differ in scale (like 2.0 and 2.00) will generally <i>not</i>2765* have the same hash code.2766*2767* @return hash code for this {@code BigDecimal}.2768* @see #equals(Object)2769*/2770@Override2771public int hashCode() {2772if (intCompact != INFLATED) {2773long val2 = (intCompact < 0)? -intCompact : intCompact;2774int temp = (int)( ((int)(val2 >>> 32)) * 31 +2775(val2 & LONG_MASK));2776return 31*((intCompact < 0) ?-temp:temp) + scale;2777} else2778return 31*intVal.hashCode() + scale;2779}27802781// Format Converters27822783/**2784* Returns the string representation of this {@code BigDecimal},2785* using scientific notation if an exponent is needed.2786*2787* <p>A standard canonical string form of the {@code BigDecimal}2788* is created as though by the following steps: first, the2789* absolute value of the unscaled value of the {@code BigDecimal}2790* is converted to a string in base ten using the characters2791* {@code '0'} through {@code '9'} with no leading zeros (except2792* if its value is zero, in which case a single {@code '0'}2793* character is used).2794*2795* <p>Next, an <i>adjusted exponent</i> is calculated; this is the2796* negated scale, plus the number of characters in the converted2797* unscaled value, less one. That is,2798* {@code -scale+(ulength-1)}, where {@code ulength} is the2799* length of the absolute value of the unscaled value in decimal2800* digits (its <i>precision</i>).2801*2802* <p>If the scale is greater than or equal to zero and the2803* adjusted exponent is greater than or equal to {@code -6}, the2804* number will be converted to a character form without using2805* exponential notation. In this case, if the scale is zero then2806* no decimal point is added and if the scale is positive a2807* decimal point will be inserted with the scale specifying the2808* number of characters to the right of the decimal point.2809* {@code '0'} characters are added to the left of the converted2810* unscaled value as necessary. If no character precedes the2811* decimal point after this insertion then a conventional2812* {@code '0'} character is prefixed.2813*2814* <p>Otherwise (that is, if the scale is negative, or the2815* adjusted exponent is less than {@code -6}), the number will be2816* converted to a character form using exponential notation. In2817* this case, if the converted {@code BigInteger} has more than2818* one digit a decimal point is inserted after the first digit.2819* An exponent in character form is then suffixed to the converted2820* unscaled value (perhaps with inserted decimal point); this2821* comprises the letter {@code 'E'} followed immediately by the2822* adjusted exponent converted to a character form. The latter is2823* in base ten, using the characters {@code '0'} through2824* {@code '9'} with no leading zeros, and is always prefixed by a2825* sign character {@code '-'} (<tt>'\u002D'</tt>) if the2826* adjusted exponent is negative, {@code '+'}2827* (<tt>'\u002B'</tt>) otherwise).2828*2829* <p>Finally, the entire string is prefixed by a minus sign2830* character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled2831* value is less than zero. No sign character is prefixed if the2832* unscaled value is zero or positive.2833*2834* <p><b>Examples:</b>2835* <p>For each representation [<i>unscaled value</i>, <i>scale</i>]2836* on the left, the resulting string is shown on the right.2837* <pre>2838* [123,0] "123"2839* [-123,0] "-123"2840* [123,-1] "1.23E+3"2841* [123,-3] "1.23E+5"2842* [123,1] "12.3"2843* [123,5] "0.00123"2844* [123,10] "1.23E-8"2845* [-123,12] "-1.23E-10"2846* </pre>2847*2848* <b>Notes:</b>2849* <ol>2850*2851* <li>There is a one-to-one mapping between the distinguishable2852* {@code BigDecimal} values and the result of this conversion.2853* That is, every distinguishable {@code BigDecimal} value2854* (unscaled value and scale) has a unique string representation2855* as a result of using {@code toString}. If that string2856* representation is converted back to a {@code BigDecimal} using2857* the {@link #BigDecimal(String)} constructor, then the original2858* value will be recovered.2859*2860* <li>The string produced for a given number is always the same;2861* it is not affected by locale. This means that it can be used2862* as a canonical string representation for exchanging decimal2863* data, or as a key for a Hashtable, etc. Locale-sensitive2864* number formatting and parsing is handled by the {@link2865* java.text.NumberFormat} class and its subclasses.2866*2867* <li>The {@link #toEngineeringString} method may be used for2868* presenting numbers with exponents in engineering notation, and the2869* {@link #setScale(int,RoundingMode) setScale} method may be used for2870* rounding a {@code BigDecimal} so it has a known number of digits after2871* the decimal point.2872*2873* <li>The digit-to-character mapping provided by2874* {@code Character.forDigit} is used.2875*2876* </ol>2877*2878* @return string representation of this {@code BigDecimal}.2879* @see Character#forDigit2880* @see #BigDecimal(java.lang.String)2881*/2882@Override2883public String toString() {2884String sc = stringCache;2885if (sc == null)2886stringCache = sc = layoutChars(true);2887return sc;2888}28892890/**2891* Returns a string representation of this {@code BigDecimal},2892* using engineering notation if an exponent is needed.2893*2894* <p>Returns a string that represents the {@code BigDecimal} as2895* described in the {@link #toString()} method, except that if2896* exponential notation is used, the power of ten is adjusted to2897* be a multiple of three (engineering notation) such that the2898* integer part of nonzero values will be in the range 1 through2899* 999. If exponential notation is used for zero values, a2900* decimal point and one or two fractional zero digits are used so2901* that the scale of the zero value is preserved. Note that2902* unlike the output of {@link #toString()}, the output of this2903* method is <em>not</em> guaranteed to recover the same [integer,2904* scale] pair of this {@code BigDecimal} if the output string is2905* converting back to a {@code BigDecimal} using the {@linkplain2906* #BigDecimal(String) string constructor}. The result of this method meets2907* the weaker constraint of always producing a numerically equal2908* result from applying the string constructor to the method's output.2909*2910* @return string representation of this {@code BigDecimal}, using2911* engineering notation if an exponent is needed.2912* @since 1.52913*/2914public String toEngineeringString() {2915return layoutChars(false);2916}29172918/**2919* Returns a string representation of this {@code BigDecimal}2920* without an exponent field. For values with a positive scale,2921* the number of digits to the right of the decimal point is used2922* to indicate scale. For values with a zero or negative scale,2923* the resulting string is generated as if the value were2924* converted to a numerically equal value with zero scale and as2925* if all the trailing zeros of the zero scale value were present2926* in the result.2927*2928* The entire string is prefixed by a minus sign character '-'2929* (<tt>'\u002D'</tt>) if the unscaled value is less than2930* zero. No sign character is prefixed if the unscaled value is2931* zero or positive.2932*2933* Note that if the result of this method is passed to the2934* {@linkplain #BigDecimal(String) string constructor}, only the2935* numerical value of this {@code BigDecimal} will necessarily be2936* recovered; the representation of the new {@code BigDecimal}2937* may have a different scale. In particular, if this2938* {@code BigDecimal} has a negative scale, the string resulting2939* from this method will have a scale of zero when processed by2940* the string constructor.2941*2942* (This method behaves analogously to the {@code toString}2943* method in 1.4 and earlier releases.)2944*2945* @return a string representation of this {@code BigDecimal}2946* without an exponent field.2947* @since 1.52948* @see #toString()2949* @see #toEngineeringString()2950*/2951public String toPlainString() {2952if(scale==0) {2953if(intCompact!=INFLATED) {2954return Long.toString(intCompact);2955} else {2956return intVal.toString();2957}2958}2959if(this.scale<0) { // No decimal point2960if(signum()==0) {2961return "0";2962}2963int tailingZeros = checkScaleNonZero((-(long)scale));2964StringBuilder buf;2965if(intCompact!=INFLATED) {2966buf = new StringBuilder(20+tailingZeros);2967buf.append(intCompact);2968} else {2969String str = intVal.toString();2970buf = new StringBuilder(str.length()+tailingZeros);2971buf.append(str);2972}2973for (int i = 0; i < tailingZeros; i++)2974buf.append('0');2975return buf.toString();2976}2977String str ;2978if(intCompact!=INFLATED) {2979str = Long.toString(Math.abs(intCompact));2980} else {2981str = intVal.abs().toString();2982}2983return getValueString(signum(), str, scale);2984}29852986/* Returns a digit.digit string */2987private String getValueString(int signum, String intString, int scale) {2988/* Insert decimal point */2989StringBuilder buf;2990int insertionPoint = intString.length() - scale;2991if (insertionPoint == 0) { /* Point goes right before intVal */2992return (signum<0 ? "-0." : "0.") + intString;2993} else if (insertionPoint > 0) { /* Point goes inside intVal */2994buf = new StringBuilder(intString);2995buf.insert(insertionPoint, '.');2996if (signum < 0)2997buf.insert(0, '-');2998} else { /* We must insert zeros between point and intVal */2999buf = new StringBuilder(3-insertionPoint + intString.length());3000buf.append(signum<0 ? "-0." : "0.");3001for (int i=0; i<-insertionPoint; i++)3002buf.append('0');3003buf.append(intString);3004}3005return buf.toString();3006}30073008/**3009* Converts this {@code BigDecimal} to a {@code BigInteger}.3010* This conversion is analogous to the3011* <i>narrowing primitive conversion</i> from {@code double} to3012* {@code long} as defined in section 5.1.3 of3013* <cite>The Java™ Language Specification</cite>:3014* any fractional part of this3015* {@code BigDecimal} will be discarded. Note that this3016* conversion can lose information about the precision of the3017* {@code BigDecimal} value.3018* <p>3019* To have an exception thrown if the conversion is inexact (in3020* other words if a nonzero fractional part is discarded), use the3021* {@link #toBigIntegerExact()} method.3022*3023* @return this {@code BigDecimal} converted to a {@code BigInteger}.3024*/3025public BigInteger toBigInteger() {3026// force to an integer, quietly3027return this.setScale(0, ROUND_DOWN).inflated();3028}30293030/**3031* Converts this {@code BigDecimal} to a {@code BigInteger},3032* checking for lost information. An exception is thrown if this3033* {@code BigDecimal} has a nonzero fractional part.3034*3035* @return this {@code BigDecimal} converted to a {@code BigInteger}.3036* @throws ArithmeticException if {@code this} has a nonzero3037* fractional part.3038* @since 1.53039*/3040public BigInteger toBigIntegerExact() {3041// round to an integer, with Exception if decimal part non-03042return this.setScale(0, ROUND_UNNECESSARY).inflated();3043}30443045/**3046* Converts this {@code BigDecimal} to a {@code long}.3047* This conversion is analogous to the3048* <i>narrowing primitive conversion</i> from {@code double} to3049* {@code short} as defined in section 5.1.3 of3050* <cite>The Java™ Language Specification</cite>:3051* any fractional part of this3052* {@code BigDecimal} will be discarded, and if the resulting3053* "{@code BigInteger}" is too big to fit in a3054* {@code long}, only the low-order 64 bits are returned.3055* Note that this conversion can lose information about the3056* overall magnitude and precision of this {@code BigDecimal} value as well3057* as return a result with the opposite sign.3058*3059* @return this {@code BigDecimal} converted to a {@code long}.3060*/3061public long longValue(){3062if (intCompact != INFLATED && scale == 0) {3063return intCompact;3064} else {3065// Fastpath zero and small values3066if (this.signum() == 0 || fractionOnly() ||3067// Fastpath very large-scale values that will result3068// in a truncated value of zero. If the scale is -643069// or less, there are at least 64 powers of 10 in the3070// value of the numerical result. Since 10 = 2*5, in3071// that case there would also be 64 powers of 2 in the3072// result, meaning all 64 bits of a long will be zero.3073scale <= -64) {3074return 0;3075} else {3076return toBigInteger().longValue();3077}3078}3079}30803081/**3082* Return true if a nonzero BigDecimal has an absolute value less3083* than one; i.e. only has fraction digits.3084*/3085private boolean fractionOnly() {3086assert this.signum() != 0;3087return (this.precision() - this.scale) <= 0;3088}30893090/**3091* Converts this {@code BigDecimal} to a {@code long}, checking3092* for lost information. If this {@code BigDecimal} has a3093* nonzero fractional part or is out of the possible range for a3094* {@code long} result then an {@code ArithmeticException} is3095* thrown.3096*3097* @return this {@code BigDecimal} converted to a {@code long}.3098* @throws ArithmeticException if {@code this} has a nonzero3099* fractional part, or will not fit in a {@code long}.3100* @since 1.53101*/3102public long longValueExact() {3103if (intCompact != INFLATED && scale == 0)3104return intCompact;31053106// Fastpath zero3107if (this.signum() == 0)3108return 0;31093110// Fastpath numbers less than 1.0 (the latter can be very slow3111// to round if very small)3112if (fractionOnly())3113throw new ArithmeticException("Rounding necessary");31143115// If more than 19 digits in integer part it cannot possibly fit3116if ((precision() - scale) > 19) // [OK for negative scale too]3117throw new java.lang.ArithmeticException("Overflow");31183119// round to an integer, with Exception if decimal part non-03120BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);3121if (num.precision() >= 19) // need to check carefully3122LongOverflow.check(num);3123return num.inflated().longValue();3124}31253126private static class LongOverflow {3127/** BigInteger equal to Long.MIN_VALUE. */3128private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);31293130/** BigInteger equal to Long.MAX_VALUE. */3131private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);31323133public static void check(BigDecimal num) {3134BigInteger intVal = num.inflated();3135if (intVal.compareTo(LONGMIN) < 0 ||3136intVal.compareTo(LONGMAX) > 0)3137throw new java.lang.ArithmeticException("Overflow");3138}3139}31403141/**3142* Converts this {@code BigDecimal} to an {@code int}.3143* This conversion is analogous to the3144* <i>narrowing primitive conversion</i> from {@code double} to3145* {@code short} as defined in section 5.1.3 of3146* <cite>The Java™ Language Specification</cite>:3147* any fractional part of this3148* {@code BigDecimal} will be discarded, and if the resulting3149* "{@code BigInteger}" is too big to fit in an3150* {@code int}, only the low-order 32 bits are returned.3151* Note that this conversion can lose information about the3152* overall magnitude and precision of this {@code BigDecimal}3153* value as well as return a result with the opposite sign.3154*3155* @return this {@code BigDecimal} converted to an {@code int}.3156*/3157public int intValue() {3158return (intCompact != INFLATED && scale == 0) ?3159(int)intCompact :3160(int)longValue();3161}31623163/**3164* Converts this {@code BigDecimal} to an {@code int}, checking3165* for lost information. If this {@code BigDecimal} has a3166* nonzero fractional part or is out of the possible range for an3167* {@code int} result then an {@code ArithmeticException} is3168* thrown.3169*3170* @return this {@code BigDecimal} converted to an {@code int}.3171* @throws ArithmeticException if {@code this} has a nonzero3172* fractional part, or will not fit in an {@code int}.3173* @since 1.53174*/3175public int intValueExact() {3176long num;3177num = this.longValueExact(); // will check decimal part3178if ((int)num != num)3179throw new java.lang.ArithmeticException("Overflow");3180return (int)num;3181}31823183/**3184* Converts this {@code BigDecimal} to a {@code short}, checking3185* for lost information. If this {@code BigDecimal} has a3186* nonzero fractional part or is out of the possible range for a3187* {@code short} result then an {@code ArithmeticException} is3188* thrown.3189*3190* @return this {@code BigDecimal} converted to a {@code short}.3191* @throws ArithmeticException if {@code this} has a nonzero3192* fractional part, or will not fit in a {@code short}.3193* @since 1.53194*/3195public short shortValueExact() {3196long num;3197num = this.longValueExact(); // will check decimal part3198if ((short)num != num)3199throw new java.lang.ArithmeticException("Overflow");3200return (short)num;3201}32023203/**3204* Converts this {@code BigDecimal} to a {@code byte}, checking3205* for lost information. If this {@code BigDecimal} has a3206* nonzero fractional part or is out of the possible range for a3207* {@code byte} result then an {@code ArithmeticException} is3208* thrown.3209*3210* @return this {@code BigDecimal} converted to a {@code byte}.3211* @throws ArithmeticException if {@code this} has a nonzero3212* fractional part, or will not fit in a {@code byte}.3213* @since 1.53214*/3215public byte byteValueExact() {3216long num;3217num = this.longValueExact(); // will check decimal part3218if ((byte)num != num)3219throw new java.lang.ArithmeticException("Overflow");3220return (byte)num;3221}32223223/**3224* Converts this {@code BigDecimal} to a {@code float}.3225* This conversion is similar to the3226* <i>narrowing primitive conversion</i> from {@code double} to3227* {@code float} as defined in section 5.1.3 of3228* <cite>The Java™ Language Specification</cite>:3229* if this {@code BigDecimal} has too great a3230* magnitude to represent as a {@code float}, it will be3231* converted to {@link Float#NEGATIVE_INFINITY} or {@link3232* Float#POSITIVE_INFINITY} as appropriate. Note that even when3233* the return value is finite, this conversion can lose3234* information about the precision of the {@code BigDecimal}3235* value.3236*3237* @return this {@code BigDecimal} converted to a {@code float}.3238*/3239public float floatValue(){3240if(intCompact != INFLATED) {3241if (scale == 0) {3242return (float)intCompact;3243} else {3244/*3245* If both intCompact and the scale can be exactly3246* represented as float values, perform a single float3247* multiply or divide to compute the (properly3248* rounded) result.3249*/3250if (Math.abs(intCompact) < 1L<<22 ) {3251// Don't have too guard against3252// Math.abs(MIN_VALUE) because of outer check3253// against INFLATED.3254if (scale > 0 && scale < float10pow.length) {3255return (float)intCompact / float10pow[scale];3256} else if (scale < 0 && scale > -float10pow.length) {3257return (float)intCompact * float10pow[-scale];3258}3259}3260}3261}3262// Somewhat inefficient, but guaranteed to work.3263return Float.parseFloat(this.toString());3264}32653266/**3267* Converts this {@code BigDecimal} to a {@code double}.3268* This conversion is similar to the3269* <i>narrowing primitive conversion</i> from {@code double} to3270* {@code float} as defined in section 5.1.3 of3271* <cite>The Java™ Language Specification</cite>:3272* if this {@code BigDecimal} has too great a3273* magnitude represent as a {@code double}, it will be3274* converted to {@link Double#NEGATIVE_INFINITY} or {@link3275* Double#POSITIVE_INFINITY} as appropriate. Note that even when3276* the return value is finite, this conversion can lose3277* information about the precision of the {@code BigDecimal}3278* value.3279*3280* @return this {@code BigDecimal} converted to a {@code double}.3281*/3282public double doubleValue(){3283if(intCompact != INFLATED) {3284if (scale == 0) {3285return (double)intCompact;3286} else {3287/*3288* If both intCompact and the scale can be exactly3289* represented as double values, perform a single3290* double multiply or divide to compute the (properly3291* rounded) result.3292*/3293if (Math.abs(intCompact) < 1L<<52 ) {3294// Don't have too guard against3295// Math.abs(MIN_VALUE) because of outer check3296// against INFLATED.3297if (scale > 0 && scale < double10pow.length) {3298return (double)intCompact / double10pow[scale];3299} else if (scale < 0 && scale > -double10pow.length) {3300return (double)intCompact * double10pow[-scale];3301}3302}3303}3304}3305// Somewhat inefficient, but guaranteed to work.3306return Double.parseDouble(this.toString());3307}33083309/**3310* Powers of 10 which can be represented exactly in {@code3311* double}.3312*/3313private static final double double10pow[] = {33141.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,33151.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11,33161.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,33171.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e223318};33193320/**3321* Powers of 10 which can be represented exactly in {@code3322* float}.3323*/3324private static final float float10pow[] = {33251.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,33261.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f3327};33283329/**3330* Returns the size of an ulp, a unit in the last place, of this3331* {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}3332* value is the positive distance between this value and the3333* {@code BigDecimal} value next larger in magnitude with the3334* same number of digits. An ulp of a zero value is numerically3335* equal to 1 with the scale of {@code this}. The result is3336* stored with the same scale as {@code this} so the result3337* for zero and nonzero values is equal to {@code [1,3338* this.scale()]}.3339*3340* @return the size of an ulp of {@code this}3341* @since 1.53342*/3343public BigDecimal ulp() {3344return BigDecimal.valueOf(1, this.scale(), 1);3345}33463347// Private class to build a string representation for BigDecimal object.3348// "StringBuilderHelper" is constructed as a thread local variable so it is3349// thread safe. The StringBuilder field acts as a buffer to hold the temporary3350// representation of BigDecimal. The cmpCharArray holds all the characters for3351// the compact representation of BigDecimal (except for '-' sign' if it is3352// negative) if its intCompact field is not INFLATED. It is shared by all3353// calls to toString() and its variants in that particular thread.3354static class StringBuilderHelper {3355final StringBuilder sb; // Placeholder for BigDecimal string3356final char[] cmpCharArray; // character array to place the intCompact33573358StringBuilderHelper() {3359sb = new StringBuilder();3360// All non negative longs can be made to fit into 19 character array.3361cmpCharArray = new char[19];3362}33633364// Accessors.3365StringBuilder getStringBuilder() {3366sb.setLength(0);3367return sb;3368}33693370char[] getCompactCharArray() {3371return cmpCharArray;3372}33733374/**3375* Places characters representing the intCompact in {@code long} into3376* cmpCharArray and returns the offset to the array where the3377* representation starts.3378*3379* @param intCompact the number to put into the cmpCharArray.3380* @return offset to the array where the representation starts.3381* Note: intCompact must be greater or equal to zero.3382*/3383int putIntCompact(long intCompact) {3384assert intCompact >= 0;33853386long q;3387int r;3388// since we start from the least significant digit, charPos points to3389// the last character in cmpCharArray.3390int charPos = cmpCharArray.length;33913392// Get 2 digits/iteration using longs until quotient fits into an int3393while (intCompact > Integer.MAX_VALUE) {3394q = intCompact / 100;3395r = (int)(intCompact - q * 100);3396intCompact = q;3397cmpCharArray[--charPos] = DIGIT_ONES[r];3398cmpCharArray[--charPos] = DIGIT_TENS[r];3399}34003401// Get 2 digits/iteration using ints when i2 >= 1003402int q2;3403int i2 = (int)intCompact;3404while (i2 >= 100) {3405q2 = i2 / 100;3406r = i2 - q2 * 100;3407i2 = q2;3408cmpCharArray[--charPos] = DIGIT_ONES[r];3409cmpCharArray[--charPos] = DIGIT_TENS[r];3410}34113412cmpCharArray[--charPos] = DIGIT_ONES[i2];3413if (i2 >= 10)3414cmpCharArray[--charPos] = DIGIT_TENS[i2];34153416return charPos;3417}34183419final static char[] DIGIT_TENS = {3420'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',3421'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',3422'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',3423'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',3424'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',3425'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',3426'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',3427'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',3428'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',3429'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',3430};34313432final static char[] DIGIT_ONES = {3433'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3434'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3435'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3436'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3437'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3438'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3439'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3440'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3441'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3442'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3443};3444}34453446/**3447* Lay out this {@code BigDecimal} into a {@code char[]} array.3448* The Java 1.2 equivalent to this was called {@code getValueString}.3449*3450* @param sci {@code true} for Scientific exponential notation;3451* {@code false} for Engineering3452* @return string with canonical string representation of this3453* {@code BigDecimal}3454*/3455private String layoutChars(boolean sci) {3456if (scale == 0) // zero scale is trivial3457return (intCompact != INFLATED) ?3458Long.toString(intCompact):3459intVal.toString();3460if (scale == 2 &&3461intCompact >= 0 && intCompact < Integer.MAX_VALUE) {3462// currency fast path3463int lowInt = (int)intCompact % 100;3464int highInt = (int)intCompact / 100;3465return (Integer.toString(highInt) + '.' +3466StringBuilderHelper.DIGIT_TENS[lowInt] +3467StringBuilderHelper.DIGIT_ONES[lowInt]) ;3468}34693470StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();3471char[] coeff;3472int offset; // offset is the starting index for coeff array3473// Get the significand as an absolute value3474if (intCompact != INFLATED) {3475offset = sbHelper.putIntCompact(Math.abs(intCompact));3476coeff = sbHelper.getCompactCharArray();3477} else {3478offset = 0;3479coeff = intVal.abs().toString().toCharArray();3480}34813482// Construct a buffer, with sufficient capacity for all cases.3483// If E-notation is needed, length will be: +1 if negative, +13484// if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.3485// Otherwise it could have +1 if negative, plus leading "0.00000"3486StringBuilder buf = sbHelper.getStringBuilder();3487if (signum() < 0) // prefix '-' if negative3488buf.append('-');3489int coeffLen = coeff.length - offset;3490long adjusted = -(long)scale + (coeffLen -1);3491if ((scale >= 0) && (adjusted >= -6)) { // plain number3492int pad = scale - coeffLen; // count of padding zeros3493if (pad >= 0) { // 0.xxx form3494buf.append('0');3495buf.append('.');3496for (; pad>0; pad--) {3497buf.append('0');3498}3499buf.append(coeff, offset, coeffLen);3500} else { // xx.xx form3501buf.append(coeff, offset, -pad);3502buf.append('.');3503buf.append(coeff, -pad + offset, scale);3504}3505} else { // E-notation is needed3506if (sci) { // Scientific notation3507buf.append(coeff[offset]); // first character3508if (coeffLen > 1) { // more to come3509buf.append('.');3510buf.append(coeff, offset + 1, coeffLen - 1);3511}3512} else { // Engineering notation3513int sig = (int)(adjusted % 3);3514if (sig < 0)3515sig += 3; // [adjusted was negative]3516adjusted -= sig; // now a multiple of 33517sig++;3518if (signum() == 0) {3519switch (sig) {3520case 1:3521buf.append('0'); // exponent is a multiple of three3522break;3523case 2:3524buf.append("0.00");3525adjusted += 3;3526break;3527case 3:3528buf.append("0.0");3529adjusted += 3;3530break;3531default:3532throw new AssertionError("Unexpected sig value " + sig);3533}3534} else if (sig >= coeffLen) { // significand all in integer3535buf.append(coeff, offset, coeffLen);3536// may need some zeros, too3537for (int i = sig - coeffLen; i > 0; i--)3538buf.append('0');3539} else { // xx.xxE form3540buf.append(coeff, offset, sig);3541buf.append('.');3542buf.append(coeff, offset + sig, coeffLen - sig);3543}3544}3545if (adjusted != 0) { // [!sci could have made 0]3546buf.append('E');3547if (adjusted > 0) // force sign for positive3548buf.append('+');3549buf.append(adjusted);3550}3551}3552return buf.toString();3553}35543555/**3556* Return 10 to the power n, as a {@code BigInteger}.3557*3558* @param n the power of ten to be returned (>=0)3559* @return a {@code BigInteger} with the value (10<sup>n</sup>)3560*/3561private static BigInteger bigTenToThe(int n) {3562if (n < 0)3563return BigInteger.ZERO;35643565if (n < BIG_TEN_POWERS_TABLE_MAX) {3566BigInteger[] pows = BIG_TEN_POWERS_TABLE;3567if (n < pows.length)3568return pows[n];3569else3570return expandBigIntegerTenPowers(n);3571}35723573return BigInteger.TEN.pow(n);3574}35753576/**3577* Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.3578*3579* @param n the power of ten to be returned (>=0)3580* @return a {@code BigDecimal} with the value (10<sup>n</sup>) and3581* in the meantime, the BIG_TEN_POWERS_TABLE array gets3582* expanded to the size greater than n.3583*/3584private static BigInteger expandBigIntegerTenPowers(int n) {3585synchronized(BigDecimal.class) {3586BigInteger[] pows = BIG_TEN_POWERS_TABLE;3587int curLen = pows.length;3588// The following comparison and the above synchronized statement is3589// to prevent multiple threads from expanding the same array.3590if (curLen <= n) {3591int newLen = curLen << 1;3592while (newLen <= n)3593newLen <<= 1;3594pows = Arrays.copyOf(pows, newLen);3595for (int i = curLen; i < newLen; i++)3596pows[i] = pows[i - 1].multiply(BigInteger.TEN);3597// Based on the following facts:3598// 1. pows is a private local varible;3599// 2. the following store is a volatile store.3600// the newly created array elements can be safely published.3601BIG_TEN_POWERS_TABLE = pows;3602}3603return pows[n];3604}3605}36063607private static final long[] LONG_TEN_POWERS_TABLE = {36081, // 0 / 10^0360910, // 1 / 10^13610100, // 2 / 10^236111000, // 3 / 10^3361210000, // 4 / 10^43613100000, // 5 / 10^536141000000, // 6 / 10^6361510000000, // 7 / 10^73616100000000, // 8 / 10^836171000000000, // 9 / 10^9361810000000000L, // 10 / 10^103619100000000000L, // 11 / 10^1136201000000000000L, // 12 / 10^12362110000000000000L, // 13 / 10^133622100000000000000L, // 14 / 10^1436231000000000000000L, // 15 / 10^15362410000000000000000L, // 16 / 10^163625100000000000000000L, // 17 / 10^1736261000000000000000000L // 18 / 10^183627};36283629private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {3630BigInteger.ONE,3631BigInteger.valueOf(10),3632BigInteger.valueOf(100),3633BigInteger.valueOf(1000),3634BigInteger.valueOf(10000),3635BigInteger.valueOf(100000),3636BigInteger.valueOf(1000000),3637BigInteger.valueOf(10000000),3638BigInteger.valueOf(100000000),3639BigInteger.valueOf(1000000000),3640BigInteger.valueOf(10000000000L),3641BigInteger.valueOf(100000000000L),3642BigInteger.valueOf(1000000000000L),3643BigInteger.valueOf(10000000000000L),3644BigInteger.valueOf(100000000000000L),3645BigInteger.valueOf(1000000000000000L),3646BigInteger.valueOf(10000000000000000L),3647BigInteger.valueOf(100000000000000000L),3648BigInteger.valueOf(1000000000000000000L)3649};36503651private static final int BIG_TEN_POWERS_TABLE_INITLEN =3652BIG_TEN_POWERS_TABLE.length;3653private static final int BIG_TEN_POWERS_TABLE_MAX =365416 * BIG_TEN_POWERS_TABLE_INITLEN;36553656private static final long THRESHOLDS_TABLE[] = {3657Long.MAX_VALUE, // 03658Long.MAX_VALUE/10L, // 13659Long.MAX_VALUE/100L, // 23660Long.MAX_VALUE/1000L, // 33661Long.MAX_VALUE/10000L, // 43662Long.MAX_VALUE/100000L, // 53663Long.MAX_VALUE/1000000L, // 63664Long.MAX_VALUE/10000000L, // 73665Long.MAX_VALUE/100000000L, // 83666Long.MAX_VALUE/1000000000L, // 93667Long.MAX_VALUE/10000000000L, // 103668Long.MAX_VALUE/100000000000L, // 113669Long.MAX_VALUE/1000000000000L, // 123670Long.MAX_VALUE/10000000000000L, // 133671Long.MAX_VALUE/100000000000000L, // 143672Long.MAX_VALUE/1000000000000000L, // 153673Long.MAX_VALUE/10000000000000000L, // 163674Long.MAX_VALUE/100000000000000000L, // 173675Long.MAX_VALUE/1000000000000000000L // 183676};36773678/**3679* Compute val * 10 ^ n; return this product if it is3680* representable as a long, INFLATED otherwise.3681*/3682private static long longMultiplyPowerTen(long val, int n) {3683if (val == 0 || n <= 0)3684return val;3685long[] tab = LONG_TEN_POWERS_TABLE;3686long[] bounds = THRESHOLDS_TABLE;3687if (n < tab.length && n < bounds.length) {3688long tenpower = tab[n];3689if (val == 1)3690return tenpower;3691if (Math.abs(val) <= bounds[n])3692return val * tenpower;3693}3694return INFLATED;3695}36963697/**3698* Compute this * 10 ^ n.3699* Needed mainly to allow special casing to trap zero value3700*/3701private BigInteger bigMultiplyPowerTen(int n) {3702if (n <= 0)3703return this.inflated();37043705if (intCompact != INFLATED)3706return bigTenToThe(n).multiply(intCompact);3707else3708return intVal.multiply(bigTenToThe(n));3709}37103711/**3712* Returns appropriate BigInteger from intVal field if intVal is3713* null, i.e. the compact representation is in use.3714*/3715private BigInteger inflated() {3716if (intVal == null) {3717return BigInteger.valueOf(intCompact);3718}3719return intVal;3720}37213722/**3723* Match the scales of two {@code BigDecimal}s to align their3724* least significant digits.3725*3726* <p>If the scales of val[0] and val[1] differ, rescale3727* (non-destructively) the lower-scaled {@code BigDecimal} so3728* they match. That is, the lower-scaled reference will be3729* replaced by a reference to a new object with the same scale as3730* the other {@code BigDecimal}.3731*3732* @param val array of two elements referring to the two3733* {@code BigDecimal}s to be aligned.3734*/3735private static void matchScale(BigDecimal[] val) {3736if (val[0].scale == val[1].scale) {3737return;3738} else if (val[0].scale < val[1].scale) {3739val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);3740} else if (val[1].scale < val[0].scale) {3741val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);3742}3743}37443745private static class UnsafeHolder {3746private static final sun.misc.Unsafe unsafe;3747private static final long intCompactOffset;3748private static final long intValOffset;3749static {3750try {3751unsafe = sun.misc.Unsafe.getUnsafe();3752intCompactOffset = unsafe.objectFieldOffset3753(BigDecimal.class.getDeclaredField("intCompact"));3754intValOffset = unsafe.objectFieldOffset3755(BigDecimal.class.getDeclaredField("intVal"));3756} catch (Exception ex) {3757throw new ExceptionInInitializerError(ex);3758}3759}3760static void setIntCompactVolatile(BigDecimal bd, long val) {3761unsafe.putLongVolatile(bd, intCompactOffset, val);3762}37633764static void setIntValVolatile(BigDecimal bd, BigInteger val) {3765unsafe.putObjectVolatile(bd, intValOffset, val);3766}3767}37683769/**3770* Reconstitute the {@code BigDecimal} instance from a stream (that is,3771* deserialize it).3772*3773* @param s the stream being read.3774*/3775private void readObject(java.io.ObjectInputStream s)3776throws java.io.IOException, ClassNotFoundException {3777// Read in all fields3778s.defaultReadObject();3779// validate possibly bad fields3780if (intVal == null) {3781String message = "BigDecimal: null intVal in stream";3782throw new java.io.StreamCorruptedException(message);3783// [all values of scale are now allowed]3784}3785UnsafeHolder.setIntCompactVolatile(this, compactValFor(intVal));3786}37873788/**3789* Serialize this {@code BigDecimal} to the stream in question3790*3791* @param s the stream to serialize to.3792*/3793private void writeObject(java.io.ObjectOutputStream s)3794throws java.io.IOException {3795// Must inflate to maintain compatible serial form.3796if (this.intVal == null)3797UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact));3798// Could reset intVal back to null if it has to be set.3799s.defaultWriteObject();3800}38013802/**3803* Returns the length of the absolute value of a {@code long}, in decimal3804* digits.3805*3806* @param x the {@code long}3807* @return the length of the unscaled value, in deciaml digits.3808*/3809static int longDigitLength(long x) {3810/*3811* As described in "Bit Twiddling Hacks" by Sean Anderson,3812* (http://graphics.stanford.edu/~seander/bithacks.html)3813* integer log 10 of x is within 1 of (1233/4096)* (1 +3814* integer log 2 of x). The fraction 1233/4096 approximates3815* log10(2). So we first do a version of log2 (a variant of3816* Long class with pre-checks and opposite directionality) and3817* then scale and check against powers table. This is a little3818* simpler in present context than the version in Hacker's3819* Delight sec 11-4. Adding one to bit length allows comparing3820* downward from the LONG_TEN_POWERS_TABLE that we need3821* anyway.3822*/3823assert x != BigDecimal.INFLATED;3824if (x < 0)3825x = -x;3826if (x < 10) // must screen for 0, might as well 103827return 1;3828int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;3829long[] tab = LONG_TEN_POWERS_TABLE;3830// if r >= length, must have max possible digits for long3831return (r >= tab.length || x < tab[r]) ? r : r + 1;3832}38333834/**3835* Returns the length of the absolute value of a BigInteger, in3836* decimal digits.3837*3838* @param b the BigInteger3839* @return the length of the unscaled value, in decimal digits3840*/3841private static int bigDigitLength(BigInteger b) {3842/*3843* Same idea as the long version, but we need a better3844* approximation of log10(2). Using 646456993/2^313845* is accurate up to max possible reported bitLength.3846*/3847if (b.signum == 0)3848return 1;3849int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);3850return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;3851}38523853/**3854* Check a scale for Underflow or Overflow. If this BigDecimal is3855* nonzero, throw an exception if the scale is outof range. If this3856* is zero, saturate the scale to the extreme value of the right3857* sign if the scale is out of range.3858*3859* @param val The new scale.3860* @throws ArithmeticException (overflow or underflow) if the new3861* scale is out of range.3862* @return validated scale as an int.3863*/3864private int checkScale(long val) {3865int asInt = (int)val;3866if (asInt != val) {3867asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;3868BigInteger b;3869if (intCompact != 0 &&3870((b = intVal) == null || b.signum() != 0))3871throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");3872}3873return asInt;3874}38753876/**3877* Returns the compact value for given {@code BigInteger}, or3878* INFLATED if too big. Relies on internal representation of3879* {@code BigInteger}.3880*/3881private static long compactValFor(BigInteger b) {3882int[] m = b.mag;3883int len = m.length;3884if (len == 0)3885return 0;3886int d = m[0];3887if (len > 2 || (len == 2 && d < 0))3888return INFLATED;38893890long u = (len == 2)?3891(((long) m[1] & LONG_MASK) + (((long)d) << 32)) :3892(((long)d) & LONG_MASK);3893return (b.signum < 0)? -u : u;3894}38953896private static int longCompareMagnitude(long x, long y) {3897if (x < 0)3898x = -x;3899if (y < 0)3900y = -y;3901return (x < y) ? -1 : ((x == y) ? 0 : 1);3902}39033904private static int saturateLong(long s) {3905int i = (int)s;3906return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);3907}39083909/*3910* Internal printing routine3911*/3912private static void print(String name, BigDecimal bd) {3913System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",3914name,3915bd.intCompact,3916bd.intVal,3917bd.scale,3918bd.precision);3919}39203921/**3922* Check internal invariants of this BigDecimal. These invariants3923* include:3924*3925* <ul>3926*3927* <li>The object must be initialized; either intCompact must not be3928* INFLATED or intVal is non-null. Both of these conditions may3929* be true.3930*3931* <li>If both intCompact and intVal and set, their values must be3932* consistent.3933*3934* <li>If precision is nonzero, it must have the right value.3935* </ul>3936*3937* Note: Since this is an audit method, we are not supposed to change the3938* state of this BigDecimal object.3939*/3940private BigDecimal audit() {3941if (intCompact == INFLATED) {3942if (intVal == null) {3943print("audit", this);3944throw new AssertionError("null intVal");3945}3946// Check precision3947if (precision > 0 && precision != bigDigitLength(intVal)) {3948print("audit", this);3949throw new AssertionError("precision mismatch");3950}3951} else {3952if (intVal != null) {3953long val = intVal.longValue();3954if (val != intCompact) {3955print("audit", this);3956throw new AssertionError("Inconsistent state, intCompact=" +3957intCompact + "\t intVal=" + val);3958}3959}3960// Check precision3961if (precision > 0 && precision != longDigitLength(intCompact)) {3962print("audit", this);3963throw new AssertionError("precision mismatch");3964}3965}3966return this;3967}39683969/* the same as checkScale where value!=0 */3970private static int checkScaleNonZero(long val) {3971int asInt = (int)val;3972if (asInt != val) {3973throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");3974}3975return asInt;3976}39773978private static int checkScale(long intCompact, long val) {3979int asInt = (int)val;3980if (asInt != val) {3981asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;3982if (intCompact != 0)3983throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");3984}3985return asInt;3986}39873988private static int checkScale(BigInteger intVal, long val) {3989int asInt = (int)val;3990if (asInt != val) {3991asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;3992if (intVal.signum() != 0)3993throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");3994}3995return asInt;3996}39973998/**3999* Returns a {@code BigDecimal} rounded according to the MathContext4000* settings;4001* If rounding is needed a new {@code BigDecimal} is created and returned.4002*4003* @param val the value to be rounded4004* @param mc the context to use.4005* @return a {@code BigDecimal} rounded according to the MathContext4006* settings. May return {@code value}, if no rounding needed.4007* @throws ArithmeticException if the rounding mode is4008* {@code RoundingMode.UNNECESSARY} and the4009* result is inexact.4010*/4011private static BigDecimal doRound(BigDecimal val, MathContext mc) {4012int mcp = mc.precision;4013boolean wasDivided = false;4014if (mcp > 0) {4015BigInteger intVal = val.intVal;4016long compactVal = val.intCompact;4017int scale = val.scale;4018int prec = val.precision();4019int mode = mc.roundingMode.oldMode;4020int drop;4021if (compactVal == INFLATED) {4022drop = prec - mcp;4023while (drop > 0) {4024scale = checkScaleNonZero((long) scale - drop);4025intVal = divideAndRoundByTenPow(intVal, drop, mode);4026wasDivided = true;4027compactVal = compactValFor(intVal);4028if (compactVal != INFLATED) {4029prec = longDigitLength(compactVal);4030break;4031}4032prec = bigDigitLength(intVal);4033drop = prec - mcp;4034}4035}4036if (compactVal != INFLATED) {4037drop = prec - mcp; // drop can't be more than 184038while (drop > 0) {4039scale = checkScaleNonZero((long) scale - drop);4040compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4041wasDivided = true;4042prec = longDigitLength(compactVal);4043drop = prec - mcp;4044intVal = null;4045}4046}4047return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;4048}4049return val;4050}40514052/*4053* Returns a {@code BigDecimal} created from {@code long} value with4054* given scale rounded according to the MathContext settings4055*/4056private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {4057int mcp = mc.precision;4058if (mcp > 0 && mcp < 19) {4059int prec = longDigitLength(compactVal);4060int drop = prec - mcp; // drop can't be more than 184061while (drop > 0) {4062scale = checkScaleNonZero((long) scale - drop);4063compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4064prec = longDigitLength(compactVal);4065drop = prec - mcp;4066}4067return valueOf(compactVal, scale, prec);4068}4069return valueOf(compactVal, scale);4070}40714072/*4073* Returns a {@code BigDecimal} created from {@code BigInteger} value with4074* given scale rounded according to the MathContext settings4075*/4076private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {4077int mcp = mc.precision;4078int prec = 0;4079if (mcp > 0) {4080long compactVal = compactValFor(intVal);4081int mode = mc.roundingMode.oldMode;4082int drop;4083if (compactVal == INFLATED) {4084prec = bigDigitLength(intVal);4085drop = prec - mcp;4086while (drop > 0) {4087scale = checkScaleNonZero((long) scale - drop);4088intVal = divideAndRoundByTenPow(intVal, drop, mode);4089compactVal = compactValFor(intVal);4090if (compactVal != INFLATED) {4091break;4092}4093prec = bigDigitLength(intVal);4094drop = prec - mcp;4095}4096}4097if (compactVal != INFLATED) {4098prec = longDigitLength(compactVal);4099drop = prec - mcp; // drop can't be more than 184100while (drop > 0) {4101scale = checkScaleNonZero((long) scale - drop);4102compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4103prec = longDigitLength(compactVal);4104drop = prec - mcp;4105}4106return valueOf(compactVal,scale,prec);4107}4108}4109return new BigDecimal(intVal,INFLATED,scale,prec);4110}41114112/*4113* Divides {@code BigInteger} value by ten power.4114*/4115private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {4116if (tenPow < LONG_TEN_POWERS_TABLE.length)4117intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);4118else4119intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);4120return intVal;4121}41224123/**4124* Internally used for division operation for division {@code long} by4125* {@code long}.4126* The returned {@code BigDecimal} object is the quotient whose scale is set4127* to the passed in scale. If the remainder is not zero, it will be rounded4128* based on the passed in roundingMode. Also, if the remainder is zero and4129* the last parameter, i.e. preferredScale is NOT equal to scale, the4130* trailing zeros of the result is stripped to match the preferredScale.4131*/4132private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,4133int preferredScale) {41344135int qsign; // quotient sign4136long q = ldividend / ldivisor; // store quotient in long4137if (roundingMode == ROUND_DOWN && scale == preferredScale)4138return valueOf(q, scale);4139long r = ldividend % ldivisor; // store remainder in long4140qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;4141if (r != 0) {4142boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);4143return valueOf((increment ? q + qsign : q), scale);4144} else {4145if (preferredScale != scale)4146return createAndStripZerosToMatchScale(q, scale, preferredScale);4147else4148return valueOf(q, scale);4149}4150}41514152/**4153* Divides {@code long} by {@code long} and do rounding based on the4154* passed in roundingMode.4155*/4156private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {4157int qsign; // quotient sign4158long q = ldividend / ldivisor; // store quotient in long4159if (roundingMode == ROUND_DOWN)4160return q;4161long r = ldividend % ldivisor; // store remainder in long4162qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;4163if (r != 0) {4164boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);4165return increment ? q + qsign : q;4166} else {4167return q;4168}4169}41704171/**4172* Shared logic of need increment computation.4173*/4174private static boolean commonNeedIncrement(int roundingMode, int qsign,4175int cmpFracHalf, boolean oddQuot) {4176switch(roundingMode) {4177case ROUND_UNNECESSARY:4178throw new ArithmeticException("Rounding necessary");41794180case ROUND_UP: // Away from zero4181return true;41824183case ROUND_DOWN: // Towards zero4184return false;41854186case ROUND_CEILING: // Towards +infinity4187return qsign > 0;41884189case ROUND_FLOOR: // Towards -infinity4190return qsign < 0;41914192default: // Some kind of half-way rounding4193assert roundingMode >= ROUND_HALF_UP &&4194roundingMode <= ROUND_HALF_EVEN: "Unexpected rounding mode" + RoundingMode.valueOf(roundingMode);41954196if (cmpFracHalf < 0 ) // We're closer to higher digit4197return false;4198else if (cmpFracHalf > 0 ) // We're closer to lower digit4199return true;4200else { // half-way4201assert cmpFracHalf == 0;42024203switch(roundingMode) {4204case ROUND_HALF_DOWN:4205return false;42064207case ROUND_HALF_UP:4208return true;42094210case ROUND_HALF_EVEN:4211return oddQuot;42124213default:4214throw new AssertionError("Unexpected rounding mode" + roundingMode);4215}4216}4217}4218}42194220/**4221* Tests if quotient has to be incremented according the roundingMode4222*/4223private static boolean needIncrement(long ldivisor, int roundingMode,4224int qsign, long q, long r) {4225assert r != 0L;42264227int cmpFracHalf;4228if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {4229cmpFracHalf = 1; // 2 * r can't fit into long4230} else {4231cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);4232}42334234return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);4235}42364237/**4238* Divides {@code BigInteger} value by {@code long} value and4239* do rounding based on the passed in roundingMode.4240*/4241private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {4242boolean isRemainderZero; // record remainder is zero or not4243int qsign; // quotient sign4244long r = 0; // store quotient & remainder in long4245MutableBigInteger mq = null; // store quotient4246// Descend into mutables for faster remainder checks4247MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4248mq = new MutableBigInteger();4249r = mdividend.divide(ldivisor, mq);4250isRemainderZero = (r == 0);4251qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;4252if (!isRemainderZero) {4253if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {4254mq.add(MutableBigInteger.ONE);4255}4256}4257return mq.toBigInteger(qsign);4258}42594260/**4261* Internally used for division operation for division {@code BigInteger}4262* by {@code long}.4263* The returned {@code BigDecimal} object is the quotient whose scale is set4264* to the passed in scale. If the remainder is not zero, it will be rounded4265* based on the passed in roundingMode. Also, if the remainder is zero and4266* the last parameter, i.e. preferredScale is NOT equal to scale, the4267* trailing zeros of the result is stripped to match the preferredScale.4268*/4269private static BigDecimal divideAndRound(BigInteger bdividend,4270long ldivisor, int scale, int roundingMode, int preferredScale) {4271boolean isRemainderZero; // record remainder is zero or not4272int qsign; // quotient sign4273long r = 0; // store quotient & remainder in long4274MutableBigInteger mq = null; // store quotient4275// Descend into mutables for faster remainder checks4276MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4277mq = new MutableBigInteger();4278r = mdividend.divide(ldivisor, mq);4279isRemainderZero = (r == 0);4280qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;4281if (!isRemainderZero) {4282if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {4283mq.add(MutableBigInteger.ONE);4284}4285return mq.toBigDecimal(qsign, scale);4286} else {4287if (preferredScale != scale) {4288long compactVal = mq.toCompactValue(qsign);4289if(compactVal!=INFLATED) {4290return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);4291}4292BigInteger intVal = mq.toBigInteger(qsign);4293return createAndStripZerosToMatchScale(intVal,scale, preferredScale);4294} else {4295return mq.toBigDecimal(qsign, scale);4296}4297}4298}42994300/**4301* Tests if quotient has to be incremented according the roundingMode4302*/4303private static boolean needIncrement(long ldivisor, int roundingMode,4304int qsign, MutableBigInteger mq, long r) {4305assert r != 0L;43064307int cmpFracHalf;4308if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {4309cmpFracHalf = 1; // 2 * r can't fit into long4310} else {4311cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);4312}43134314return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());4315}43164317/**4318* Divides {@code BigInteger} value by {@code BigInteger} value and4319* do rounding based on the passed in roundingMode.4320*/4321private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {4322boolean isRemainderZero; // record remainder is zero or not4323int qsign; // quotient sign4324// Descend into mutables for faster remainder checks4325MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4326MutableBigInteger mq = new MutableBigInteger();4327MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);4328MutableBigInteger mr = mdividend.divide(mdivisor, mq);4329isRemainderZero = mr.isZero();4330qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;4331if (!isRemainderZero) {4332if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {4333mq.add(MutableBigInteger.ONE);4334}4335}4336return mq.toBigInteger(qsign);4337}43384339/**4340* Internally used for division operation for division {@code BigInteger}4341* by {@code BigInteger}.4342* The returned {@code BigDecimal} object is the quotient whose scale is set4343* to the passed in scale. If the remainder is not zero, it will be rounded4344* based on the passed in roundingMode. Also, if the remainder is zero and4345* the last parameter, i.e. preferredScale is NOT equal to scale, the4346* trailing zeros of the result is stripped to match the preferredScale.4347*/4348private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,4349int preferredScale) {4350boolean isRemainderZero; // record remainder is zero or not4351int qsign; // quotient sign4352// Descend into mutables for faster remainder checks4353MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4354MutableBigInteger mq = new MutableBigInteger();4355MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);4356MutableBigInteger mr = mdividend.divide(mdivisor, mq);4357isRemainderZero = mr.isZero();4358qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;4359if (!isRemainderZero) {4360if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {4361mq.add(MutableBigInteger.ONE);4362}4363return mq.toBigDecimal(qsign, scale);4364} else {4365if (preferredScale != scale) {4366long compactVal = mq.toCompactValue(qsign);4367if (compactVal != INFLATED) {4368return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);4369}4370BigInteger intVal = mq.toBigInteger(qsign);4371return createAndStripZerosToMatchScale(intVal, scale, preferredScale);4372} else {4373return mq.toBigDecimal(qsign, scale);4374}4375}4376}43774378/**4379* Tests if quotient has to be incremented according the roundingMode4380*/4381private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,4382int qsign, MutableBigInteger mq, MutableBigInteger mr) {4383assert !mr.isZero();4384int cmpFracHalf = mr.compareHalf(mdivisor);4385return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());4386}43874388/**4389* Remove insignificant trailing zeros from this4390* {@code BigInteger} value until the preferred scale is reached or no4391* more zeros can be removed. If the preferred scale is less than4392* Integer.MIN_VALUE, all the trailing zeros will be removed.4393*4394* @return new {@code BigDecimal} with a scale possibly reduced4395* to be closed to the preferred scale.4396*/4397private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {4398BigInteger qr[]; // quotient-remainder pair4399while (intVal.compareMagnitude(BigInteger.TEN) >= 04400&& scale > preferredScale) {4401if (intVal.testBit(0))4402break; // odd number cannot end in 04403qr = intVal.divideAndRemainder(BigInteger.TEN);4404if (qr[1].signum() != 0)4405break; // non-0 remainder4406intVal = qr[0];4407scale = checkScale(intVal,(long) scale - 1); // could Overflow4408}4409return valueOf(intVal, scale, 0);4410}44114412/**4413* Remove insignificant trailing zeros from this4414* {@code long} value until the preferred scale is reached or no4415* more zeros can be removed. If the preferred scale is less than4416* Integer.MIN_VALUE, all the trailing zeros will be removed.4417*4418* @return new {@code BigDecimal} with a scale possibly reduced4419* to be closed to the preferred scale.4420*/4421private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {4422while (Math.abs(compactVal) >= 10L && scale > preferredScale) {4423if ((compactVal & 1L) != 0L)4424break; // odd number cannot end in 04425long r = compactVal % 10L;4426if (r != 0L)4427break; // non-0 remainder4428compactVal /= 10;4429scale = checkScale(compactVal, (long) scale - 1); // could Overflow4430}4431return valueOf(compactVal, scale);4432}44334434private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {4435if(intCompact!=INFLATED) {4436return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);4437} else {4438return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,4439scale, preferredScale);4440}4441}44424443/*4444* returns INFLATED if oveflow4445*/4446private static long add(long xs, long ys){4447long sum = xs + ys;4448// See "Hacker's Delight" section 2-12 for explanation of4449// the overflow test.4450if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed4451return sum;4452}4453return INFLATED;4454}44554456private static BigDecimal add(long xs, long ys, int scale){4457long sum = add(xs, ys);4458if (sum!=INFLATED)4459return BigDecimal.valueOf(sum, scale);4460return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);4461}44624463private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {4464long sdiff = (long) scale1 - scale2;4465if (sdiff == 0) {4466return add(xs, ys, scale1);4467} else if (sdiff < 0) {4468int raise = checkScale(xs,-sdiff);4469long scaledX = longMultiplyPowerTen(xs, raise);4470if (scaledX != INFLATED) {4471return add(scaledX, ys, scale2);4472} else {4473BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);4474return ((xs^ys)>=0) ? // same sign test4475new BigDecimal(bigsum, INFLATED, scale2, 0)4476: valueOf(bigsum, scale2, 0);4477}4478} else {4479int raise = checkScale(ys,sdiff);4480long scaledY = longMultiplyPowerTen(ys, raise);4481if (scaledY != INFLATED) {4482return add(xs, scaledY, scale1);4483} else {4484BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);4485return ((xs^ys)>=0) ?4486new BigDecimal(bigsum, INFLATED, scale1, 0)4487: valueOf(bigsum, scale1, 0);4488}4489}4490}44914492private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {4493int rscale = scale1;4494long sdiff = (long)rscale - scale2;4495boolean sameSigns = (Long.signum(xs) == snd.signum);4496BigInteger sum;4497if (sdiff < 0) {4498int raise = checkScale(xs,-sdiff);4499rscale = scale2;4500long scaledX = longMultiplyPowerTen(xs, raise);4501if (scaledX == INFLATED) {4502sum = snd.add(bigMultiplyPowerTen(xs,raise));4503} else {4504sum = snd.add(scaledX);4505}4506} else { //if (sdiff > 0) {4507int raise = checkScale(snd,sdiff);4508snd = bigMultiplyPowerTen(snd,raise);4509sum = snd.add(xs);4510}4511return (sameSigns) ?4512new BigDecimal(sum, INFLATED, rscale, 0) :4513valueOf(sum, rscale, 0);4514}45154516private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {4517int rscale = scale1;4518long sdiff = (long)rscale - scale2;4519if (sdiff != 0) {4520if (sdiff < 0) {4521int raise = checkScale(fst,-sdiff);4522rscale = scale2;4523fst = bigMultiplyPowerTen(fst,raise);4524} else {4525int raise = checkScale(snd,sdiff);4526snd = bigMultiplyPowerTen(snd,raise);4527}4528}4529BigInteger sum = fst.add(snd);4530return (fst.signum == snd.signum) ?4531new BigDecimal(sum, INFLATED, rscale, 0) :4532valueOf(sum, rscale, 0);4533}45344535private static BigInteger bigMultiplyPowerTen(long value, int n) {4536if (n <= 0)4537return BigInteger.valueOf(value);4538return bigTenToThe(n).multiply(value);4539}45404541private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {4542if (n <= 0)4543return value;4544if(n<LONG_TEN_POWERS_TABLE.length) {4545return value.multiply(LONG_TEN_POWERS_TABLE[n]);4546}4547return value.multiply(bigTenToThe(n));4548}45494550/**4551* Returns a {@code BigDecimal} whose value is {@code (xs /4552* ys)}, with rounding according to the context settings.4553*4554* Fast path - used only when (xscale <= yscale && yscale < 184555* && mc.presision<18) {4556*/4557private static BigDecimal divideSmallFastPath(final long xs, int xscale,4558final long ys, int yscale,4559long preferredScale, MathContext mc) {4560int mcp = mc.precision;4561int roundingMode = mc.roundingMode.oldMode;45624563assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);4564int xraise = yscale - xscale; // xraise >=04565long scaledX = (xraise==0) ? xs :4566longMultiplyPowerTen(xs, xraise); // can't overflow here!4567BigDecimal quotient;45684569int cmp = longCompareMagnitude(scaledX, ys);4570if(cmp > 0) { // satisfy constraint (b)4571yscale -= 1; // [that is, divisor *= 10]4572int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4573if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {4574// assert newScale >= xscale4575int raise = checkScaleNonZero((long) mcp + yscale - xscale);4576long scaledXs;4577if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {4578quotient = null;4579if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {4580quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4581}4582if(quotient==null) {4583BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);4584quotient = divideAndRound(rb, ys,4585scl, roundingMode, checkScaleNonZero(preferredScale));4586}4587} else {4588quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4589}4590} else {4591int newScale = checkScaleNonZero((long) xscale - mcp);4592// assert newScale >= yscale4593if (newScale == yscale) { // easy case4594quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));4595} else {4596int raise = checkScaleNonZero((long) newScale - yscale);4597long scaledYs;4598if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {4599BigInteger rb = bigMultiplyPowerTen(ys,raise);4600quotient = divideAndRound(BigInteger.valueOf(xs),4601rb, scl, roundingMode,checkScaleNonZero(preferredScale));4602} else {4603quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));4604}4605}4606}4607} else {4608// abs(scaledX) <= abs(ys)4609// result is "scaledX * 10^msp / ys"4610int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4611if(cmp==0) {4612// abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign4613quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));4614} else {4615// abs(scaledX) < abs(ys)4616long scaledXs;4617if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {4618quotient = null;4619if(mcp<LONG_TEN_POWERS_TABLE.length) {4620quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4621}4622if(quotient==null) {4623BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);4624quotient = divideAndRound(rb, ys,4625scl, roundingMode, checkScaleNonZero(preferredScale));4626}4627} else {4628quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4629}4630}4631}4632// doRound, here, only affects 1000000000 case.4633return doRound(quotient,mc);4634}46354636/**4637* Returns a {@code BigDecimal} whose value is {@code (xs /4638* ys)}, with rounding according to the context settings.4639*/4640private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {4641int mcp = mc.precision;4642if(xscale <= yscale && yscale < 18 && mcp<18) {4643return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);4644}4645if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)4646yscale -= 1; // [that is, divisor *= 10]4647}4648int roundingMode = mc.roundingMode.oldMode;4649// In order to find out whether the divide generates the exact result,4650// we avoid calling the above divide method. 'quotient' holds the4651// return BigDecimal object whose scale will be set to 'scl'.4652int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4653BigDecimal quotient;4654if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {4655int raise = checkScaleNonZero((long) mcp + yscale - xscale);4656long scaledXs;4657if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {4658BigInteger rb = bigMultiplyPowerTen(xs,raise);4659quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4660} else {4661quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4662}4663} else {4664int newScale = checkScaleNonZero((long) xscale - mcp);4665// assert newScale >= yscale4666if (newScale == yscale) { // easy case4667quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));4668} else {4669int raise = checkScaleNonZero((long) newScale - yscale);4670long scaledYs;4671if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {4672BigInteger rb = bigMultiplyPowerTen(ys,raise);4673quotient = divideAndRound(BigInteger.valueOf(xs),4674rb, scl, roundingMode,checkScaleNonZero(preferredScale));4675} else {4676quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));4677}4678}4679}4680// doRound, here, only affects 1000000000 case.4681return doRound(quotient,mc);4682}46834684/**4685* Returns a {@code BigDecimal} whose value is {@code (xs /4686* ys)}, with rounding according to the context settings.4687*/4688private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {4689// Normalize dividend & divisor so that both fall into [0.1, 0.999...]4690if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)4691yscale -= 1; // [that is, divisor *= 10]4692}4693int mcp = mc.precision;4694int roundingMode = mc.roundingMode.oldMode;46954696// In order to find out whether the divide generates the exact result,4697// we avoid calling the above divide method. 'quotient' holds the4698// return BigDecimal object whose scale will be set to 'scl'.4699BigDecimal quotient;4700int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4701if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {4702int raise = checkScaleNonZero((long) mcp + yscale - xscale);4703BigInteger rb = bigMultiplyPowerTen(xs,raise);4704quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4705} else {4706int newScale = checkScaleNonZero((long) xscale - mcp);4707// assert newScale >= yscale4708if (newScale == yscale) { // easy case4709quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));4710} else {4711int raise = checkScaleNonZero((long) newScale - yscale);4712long scaledYs;4713if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {4714BigInteger rb = bigMultiplyPowerTen(ys,raise);4715quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));4716} else {4717quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));4718}4719}4720}4721// doRound, here, only affects 1000000000 case.4722return doRound(quotient, mc);4723}47244725/**4726* Returns a {@code BigDecimal} whose value is {@code (xs /4727* ys)}, with rounding according to the context settings.4728*/4729private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {4730// Normalize dividend & divisor so that both fall into [0.1, 0.999...]4731if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)4732yscale -= 1; // [that is, divisor *= 10]4733}4734int mcp = mc.precision;4735int roundingMode = mc.roundingMode.oldMode;47364737// In order to find out whether the divide generates the exact result,4738// we avoid calling the above divide method. 'quotient' holds the4739// return BigDecimal object whose scale will be set to 'scl'.4740BigDecimal quotient;4741int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4742if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {4743int raise = checkScaleNonZero((long) mcp + yscale - xscale);4744BigInteger rb = bigMultiplyPowerTen(xs,raise);4745quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4746} else {4747int newScale = checkScaleNonZero((long) xscale - mcp);4748int raise = checkScaleNonZero((long) newScale - yscale);4749BigInteger rb = bigMultiplyPowerTen(ys,raise);4750quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));4751}4752// doRound, here, only affects 1000000000 case.4753return doRound(quotient, mc);4754}47554756/**4757* Returns a {@code BigDecimal} whose value is {@code (xs /4758* ys)}, with rounding according to the context settings.4759*/4760private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {4761// Normalize dividend & divisor so that both fall into [0.1, 0.999...]4762if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)4763yscale -= 1; // [that is, divisor *= 10]4764}4765int mcp = mc.precision;4766int roundingMode = mc.roundingMode.oldMode;47674768// In order to find out whether the divide generates the exact result,4769// we avoid calling the above divide method. 'quotient' holds the4770// return BigDecimal object whose scale will be set to 'scl'.4771BigDecimal quotient;4772int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);4773if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {4774int raise = checkScaleNonZero((long) mcp + yscale - xscale);4775BigInteger rb = bigMultiplyPowerTen(xs,raise);4776quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));4777} else {4778int newScale = checkScaleNonZero((long) xscale - mcp);4779int raise = checkScaleNonZero((long) newScale - yscale);4780BigInteger rb = bigMultiplyPowerTen(ys,raise);4781quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));4782}4783// doRound, here, only affects 1000000000 case.4784return doRound(quotient, mc);4785}47864787/*4788* performs divideAndRound for (dividend0*dividend1, divisor)4789* returns null if quotient can't fit into long value;4790*/4791private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,4792int preferredScale) {4793int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);4794dividend0 = Math.abs(dividend0);4795dividend1 = Math.abs(dividend1);4796divisor = Math.abs(divisor);4797// multiply dividend0 * dividend14798long d0_hi = dividend0 >>> 32;4799long d0_lo = dividend0 & LONG_MASK;4800long d1_hi = dividend1 >>> 32;4801long d1_lo = dividend1 & LONG_MASK;4802long product = d0_lo * d1_lo;4803long d0 = product & LONG_MASK;4804long d1 = product >>> 32;4805product = d0_hi * d1_lo + d1;4806d1 = product & LONG_MASK;4807long d2 = product >>> 32;4808product = d0_lo * d1_hi + d1;4809d1 = product & LONG_MASK;4810d2 += product >>> 32;4811long d3 = d2>>>32;4812d2 &= LONG_MASK;4813product = d0_hi*d1_hi + d2;4814d2 = product & LONG_MASK;4815d3 = ((product>>>32) + d3) & LONG_MASK;4816final long dividendHi = make64(d3,d2);4817final long dividendLo = make64(d1,d0);4818// divide4819return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);4820}48214822private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).48234824/*4825* divideAndRound 128-bit value by long divisor.4826* returns null if quotient can't fit into long value;4827* Specialized version of Knuth's division4828*/4829private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,4830int scale, int roundingMode, int preferredScale) {4831if (dividendHi >= divisor) {4832return null;4833}48344835final int shift = Long.numberOfLeadingZeros(divisor);4836divisor <<= shift;48374838final long v1 = divisor >>> 32;4839final long v0 = divisor & LONG_MASK;48404841long tmp = dividendLo << shift;4842long u1 = tmp >>> 32;4843long u0 = tmp & LONG_MASK;48444845tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);4846long u2 = tmp & LONG_MASK;4847long q1, r_tmp;4848if (v1 == 1) {4849q1 = tmp;4850r_tmp = 0;4851} else if (tmp >= 0) {4852q1 = tmp / v1;4853r_tmp = tmp - q1 * v1;4854} else {4855long[] rq = divRemNegativeLong(tmp, v1);4856q1 = rq[1];4857r_tmp = rq[0];4858}48594860while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {4861q1--;4862r_tmp += v1;4863if (r_tmp >= DIV_NUM_BASE)4864break;4865}48664867tmp = mulsub(u2,u1,v1,v0,q1);4868u1 = tmp & LONG_MASK;4869long q0;4870if (v1 == 1) {4871q0 = tmp;4872r_tmp = 0;4873} else if (tmp >= 0) {4874q0 = tmp / v1;4875r_tmp = tmp - q0 * v1;4876} else {4877long[] rq = divRemNegativeLong(tmp, v1);4878q0 = rq[1];4879r_tmp = rq[0];4880}48814882while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {4883q0--;4884r_tmp += v1;4885if (r_tmp >= DIV_NUM_BASE)4886break;4887}48884889if((int)q1 < 0) {4890// result (which is positive and unsigned here)4891// can't fit into long due to sign bit is used for value4892MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});4893if (roundingMode == ROUND_DOWN && scale == preferredScale) {4894return mq.toBigDecimal(sign, scale);4895}4896long r = mulsub(u1, u0, v1, v0, q0) >>> shift;4897if (r != 0) {4898if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){4899mq.add(MutableBigInteger.ONE);4900}4901return mq.toBigDecimal(sign, scale);4902} else {4903if (preferredScale != scale) {4904BigInteger intVal = mq.toBigInteger(sign);4905return createAndStripZerosToMatchScale(intVal,scale, preferredScale);4906} else {4907return mq.toBigDecimal(sign, scale);4908}4909}4910}49114912long q = make64(q1,q0);4913q*=sign;49144915if (roundingMode == ROUND_DOWN && scale == preferredScale)4916return valueOf(q, scale);49174918long r = mulsub(u1, u0, v1, v0, q0) >>> shift;4919if (r != 0) {4920boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);4921return valueOf((increment ? q + sign : q), scale);4922} else {4923if (preferredScale != scale) {4924return createAndStripZerosToMatchScale(q, scale, preferredScale);4925} else {4926return valueOf(q, scale);4927}4928}4929}49304931/*4932* calculate divideAndRound for ldividend*10^raise / divisor4933* when abs(dividend)==abs(divisor);4934*/4935private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {4936if (scale > preferredScale) {4937int diff = scale - preferredScale;4938if(diff < raise) {4939return scaledTenPow(raise - diff, qsign, preferredScale);4940} else {4941return valueOf(qsign,scale-raise);4942}4943} else {4944return scaledTenPow(raise, qsign, scale);4945}4946}49474948static BigDecimal scaledTenPow(int n, int sign, int scale) {4949if (n < LONG_TEN_POWERS_TABLE.length)4950return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);4951else {4952BigInteger unscaledVal = bigTenToThe(n);4953if(sign==-1) {4954unscaledVal = unscaledVal.negate();4955}4956return new BigDecimal(unscaledVal, INFLATED, scale, n+1);4957}4958}49594960/**4961* Calculate the quotient and remainder of dividing a negative long by4962* another long.4963*4964* @param n the numerator; must be negative4965* @param d the denominator; must not be unity4966* @return a two-element {@long} array with the remainder and quotient in4967* the initial and final elements, respectively4968*/4969private static long[] divRemNegativeLong(long n, long d) {4970assert n < 0 : "Non-negative numerator " + n;4971assert d != 1 : "Unity denominator";49724973// Approximate the quotient and remainder4974long q = (n >>> 1) / (d >>> 1);4975long r = n - q * d;49764977// Correct the approximation4978while (r < 0) {4979r += d;4980q--;4981}4982while (r >= d) {4983r -= d;4984q++;4985}49864987// n - q*d == r && 0 <= r < d, hence we're done.4988return new long[] {r, q};4989}49904991private static long make64(long hi, long lo) {4992return hi<<32 | lo;4993}49944995private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {4996long tmp = u0 - q0*v0;4997return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);4998}49995000private static boolean unsignedLongCompare(long one, long two) {5001return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);5002}50035004private static boolean unsignedLongCompareEq(long one, long two) {5005return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);5006}500750085009// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5010private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {5011// assert xs!=0 && ys!=05012int sdiff = xscale - yscale;5013if (sdiff != 0) {5014if (sdiff < 0) {5015xs = longMultiplyPowerTen(xs, -sdiff);5016} else { // sdiff > 05017ys = longMultiplyPowerTen(ys, sdiff);5018}5019}5020if (xs != INFLATED)5021return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;5022else5023return 1;5024}50255026// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5027private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {5028// assert "ys can't be represented as long"5029if (xs == 0)5030return -1;5031int sdiff = xscale - yscale;5032if (sdiff < 0) {5033if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {5034return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);5035}5036}5037return -1;5038}50395040// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5041private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {5042int sdiff = xscale - yscale;5043if (sdiff < 0) {5044return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);5045} else { // sdiff >= 05046return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));5047}5048}50495050private static long multiply(long x, long y){5051long product = x * y;5052long ax = Math.abs(x);5053long ay = Math.abs(y);5054if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){5055return product;5056}5057return INFLATED;5058}50595060private static BigDecimal multiply(long x, long y, int scale) {5061long product = multiply(x, y);5062if(product!=INFLATED) {5063return valueOf(product,scale);5064}5065return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);5066}50675068private static BigDecimal multiply(long x, BigInteger y, int scale) {5069if(x==0) {5070return zeroValueOf(scale);5071}5072return new BigDecimal(y.multiply(x),INFLATED,scale,0);5073}50745075private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {5076return new BigDecimal(x.multiply(y),INFLATED,scale,0);5077}50785079/**5080* Multiplies two long values and rounds according {@code MathContext}5081*/5082private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {5083long product = multiply(x, y);5084if(product!=INFLATED) {5085return doRound(product, scale, mc);5086}5087// attempt to do it in 128 bits5088int rsign = 1;5089if(x < 0) {5090x = -x;5091rsign = -1;5092}5093if(y < 0) {5094y = -y;5095rsign *= -1;5096}5097// multiply dividend0 * dividend15098long m0_hi = x >>> 32;5099long m0_lo = x & LONG_MASK;5100long m1_hi = y >>> 32;5101long m1_lo = y & LONG_MASK;5102product = m0_lo * m1_lo;5103long m0 = product & LONG_MASK;5104long m1 = product >>> 32;5105product = m0_hi * m1_lo + m1;5106m1 = product & LONG_MASK;5107long m2 = product >>> 32;5108product = m0_lo * m1_hi + m1;5109m1 = product & LONG_MASK;5110m2 += product >>> 32;5111long m3 = m2>>>32;5112m2 &= LONG_MASK;5113product = m0_hi*m1_hi + m2;5114m2 = product & LONG_MASK;5115m3 = ((product>>>32) + m3) & LONG_MASK;5116final long mHi = make64(m3,m2);5117final long mLo = make64(m1,m0);5118BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);5119if(res!=null) {5120return res;5121}5122res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);5123return doRound(res,mc);5124}51255126private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {5127if(x==0) {5128return zeroValueOf(scale);5129}5130return doRound(y.multiply(x), scale, mc);5131}51325133private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {5134return doRound(x.multiply(y), scale, mc);5135}51365137/**5138* rounds 128-bit value according {@code MathContext}5139* returns null if result can't be repsented as compact BigDecimal.5140*/5141private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {5142int mcp = mc.precision;5143int drop;5144BigDecimal res = null;5145if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {5146scale = checkScaleNonZero((long)scale - drop);5147res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);5148}5149if(res!=null) {5150return doRound(res,mc);5151}5152return null;5153}51545155private static final long[][] LONGLONG_TEN_POWERS_TABLE = {5156{ 0L, 0x8AC7230489E80000L }, //10^195157{ 0x5L, 0x6bc75e2d63100000L }, //10^205158{ 0x36L, 0x35c9adc5dea00000L }, //10^215159{ 0x21eL, 0x19e0c9bab2400000L }, //10^225160{ 0x152dL, 0x02c7e14af6800000L }, //10^235161{ 0xd3c2L, 0x1bcecceda1000000L }, //10^245162{ 0x84595L, 0x161401484a000000L }, //10^255163{ 0x52b7d2L, 0xdcc80cd2e4000000L }, //10^265164{ 0x33b2e3cL, 0x9fd0803ce8000000L }, //10^275165{ 0x204fce5eL, 0x3e25026110000000L }, //10^285166{ 0x1431e0faeL, 0x6d7217caa0000000L }, //10^295167{ 0xc9f2c9cd0L, 0x4674edea40000000L }, //10^305168{ 0x7e37be2022L, 0xc0914b2680000000L }, //10^315169{ 0x4ee2d6d415bL, 0x85acef8100000000L }, //10^325170{ 0x314dc6448d93L, 0x38c15b0a00000000L }, //10^335171{ 0x1ed09bead87c0L, 0x378d8e6400000000L }, //10^345172{ 0x13426172c74d82L, 0x2b878fe800000000L }, //10^355173{ 0xc097ce7bc90715L, 0xb34b9f1000000000L }, //10^365174{ 0x785ee10d5da46d9L, 0x00f436a000000000L }, //10^375175{ 0x4b3b4ca85a86c47aL, 0x098a224000000000L }, //10^385176};51775178/*5179* returns precision of 128-bit value5180*/5181private static int precision(long hi, long lo){5182if(hi==0) {5183if(lo>=0) {5184return longDigitLength(lo);5185}5186return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;5187// 0x8AC7230489E80000L = unsigned 2^195188}5189int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;5190int idx = r-19;5191return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,5192LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;5193}51945195/*5196* returns true if 128 bit number <hi0,lo0> is less then <hi1,lo1>5197* hi0 & hi1 should be non-negative5198*/5199private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {5200if(hi0!=hi1) {5201return hi0<hi1;5202}5203return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);5204}52055206private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {5207if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5208int newScale = scale + divisorScale;5209int raise = newScale - dividendScale;5210if(raise<LONG_TEN_POWERS_TABLE.length) {5211long xs = dividend;5212if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {5213return divideAndRound(xs, divisor, scale, roundingMode, scale);5214}5215BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);5216if(q!=null) {5217return q;5218}5219}5220BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5221return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5222} else {5223int newScale = checkScale(divisor,(long)dividendScale - scale);5224int raise = newScale - divisorScale;5225if(raise<LONG_TEN_POWERS_TABLE.length) {5226long ys = divisor;5227if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {5228return divideAndRound(dividend, ys, scale, roundingMode, scale);5229}5230}5231BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5232return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);5233}5234}52355236private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {5237if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5238int newScale = scale + divisorScale;5239int raise = newScale - dividendScale;5240BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5241return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5242} else {5243int newScale = checkScale(divisor,(long)dividendScale - scale);5244int raise = newScale - divisorScale;5245if(raise<LONG_TEN_POWERS_TABLE.length) {5246long ys = divisor;5247if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {5248return divideAndRound(dividend, ys, scale, roundingMode, scale);5249}5250}5251BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5252return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);5253}5254}52555256private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {5257if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5258int newScale = scale + divisorScale;5259int raise = newScale - dividendScale;5260BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5261return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5262} else {5263int newScale = checkScale(divisor,(long)dividendScale - scale);5264int raise = newScale - divisorScale;5265BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5266return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);5267}5268}52695270private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {5271if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5272int newScale = scale + divisorScale;5273int raise = newScale - dividendScale;5274BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5275return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5276} else {5277int newScale = checkScale(divisor,(long)dividendScale - scale);5278int raise = newScale - divisorScale;5279BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5280return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);5281}5282}52835284}528552865287