Path: blob/master/src/java.base/share/classes/java/math/BigDecimal.java
41152 views
/*1* Copyright (c) 1996, 2021, 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.io.IOException;33import java.util.Arrays;34import java.util.Objects;3536/**37* Immutable, arbitrary-precision signed decimal numbers. A {@code38* BigDecimal} consists of an arbitrary precision integer39* <i>{@linkplain unscaledValue() unscaled value}</i> and a 32-bit40* integer <i>{@linkplain scale() scale}</i>. If zero or positive,41* the scale is the number of digits to the right of the decimal42* point. If negative, the unscaled value of the number is multiplied43* by ten to the power of the negation of the scale. The value of the44* number represented by the {@code BigDecimal} is therefore45* <code>(unscaledValue × 10<sup>-scale</sup>)</code>.46*47* <p>The {@code BigDecimal} class provides operations for48* arithmetic, scale manipulation, rounding, comparison, hashing, and49* format conversion. The {@link #toString} method provides a50* canonical representation of a {@code BigDecimal}.51*52* <p>The {@code BigDecimal} class gives its user complete control53* over rounding behavior. If no rounding mode is specified and the54* exact result cannot be represented, an {@code ArithmeticException}55* is thrown; otherwise, calculations can be carried out to a chosen56* precision and rounding mode by supplying an appropriate {@link57* MathContext} object to the operation. In either case, eight58* <em>rounding modes</em> are provided for the control of rounding.59* Using the integer fields in this class (such as {@link60* #ROUND_HALF_UP}) to represent rounding mode is deprecated; the61* enumeration values of the {@code RoundingMode} {@code enum}, (such62* as {@link RoundingMode#HALF_UP}) should be used instead.63*64* <p>When a {@code MathContext} object is supplied with a precision65* setting of 0 (for example, {@link MathContext#UNLIMITED}),66* arithmetic operations are exact, as are the arithmetic methods67* which take no {@code MathContext} object. As a corollary of68* computing the exact result, the rounding mode setting of a {@code69* MathContext} object with a precision setting of 0 is not used and70* thus irrelevant. In the case of divide, the exact quotient could71* have an infinitely long decimal expansion; for example, 1 divided72* by 3. If the quotient has a nonterminating decimal expansion and73* the operation is specified to return an exact result, an {@code74* ArithmeticException} is thrown. Otherwise, the exact result of the75* division is returned, as done for other operations.76*77* <p>When the precision setting is not 0, the rules of {@code78* BigDecimal} arithmetic are broadly compatible with selected modes79* of operation of the arithmetic defined in ANSI X3.274-1996 and ANSI80* X3.274-1996/AM 1-2000 (section 7.4). Unlike those standards,81* {@code BigDecimal} includes many rounding modes. Any conflicts82* between these ANSI standards and the {@code BigDecimal}83* specification are resolved in favor of {@code BigDecimal}.84*85* <p>Since the same numerical value can have different86* representations (with different scales), the rules of arithmetic87* and rounding must specify both the numerical result and the scale88* used in the result's representation.89*90* The different representations of the same numerical value are91* called members of the same <i>cohort</i>. The {@linkplain92* compareTo(BigDecimal) natural order} of {@code BigDecimal}93* considers members of the same cohort to be equal to each other. In94* contrast, the {@link equals equals} method requires both the95* numerical value and representation to be the same for equality to96* hold. The results of methods like {@link scale} and {@link97* unscaledValue} will differ for numerically equal values with98* different representations.99*100* <p>In general the rounding modes and precision setting determine101* how operations return results with a limited number of digits when102* the exact result has more digits (perhaps infinitely many in the103* case of division and square root) than the number of digits returned.104*105* First, the total number of digits to return is specified by the106* {@code MathContext}'s {@code precision} setting; this determines107* the result's <i>precision</i>. The digit count starts from the108* leftmost nonzero digit of the exact result. The rounding mode109* determines how any discarded trailing digits affect the returned110* result.111*112* <p>For all arithmetic operators, the operation is carried out as113* though an exact intermediate result were first calculated and then114* rounded to the number of digits specified by the precision setting115* (if necessary), using the selected rounding mode. If the exact116* result is not returned, some digit positions of the exact result117* are discarded. When rounding increases the magnitude of the118* returned result, it is possible for a new digit position to be119* created by a carry propagating to a leading {@literal "9"} digit.120* For example, rounding the value 999.9 to three digits rounding up121* would be numerically equal to one thousand, represented as122* 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is123* the leading digit position of the returned result.124*125* <p>For methods and constructors with a {@code MathContext}126* parameter, if the result is inexact but the rounding mode is {@link127* RoundingMode#UNNECESSARY UNNECESSARY}, an {@code128* ArithmeticException} will be thrown.129*130* <p>Besides a logical exact result, each arithmetic operation has a131* preferred scale for representing a result. The preferred132* scale for each operation is listed in the table below.133*134* <table class="striped" style="text-align:left">135* <caption>Preferred Scales for Results of Arithmetic Operations136* </caption>137* <thead>138* <tr><th scope="col">Operation</th><th scope="col">Preferred Scale of Result</th></tr>139* </thead>140* <tbody>141* <tr><th scope="row">Add</th><td>max(addend.scale(), augend.scale())</td>142* <tr><th scope="row">Subtract</th><td>max(minuend.scale(), subtrahend.scale())</td>143* <tr><th scope="row">Multiply</th><td>multiplier.scale() + multiplicand.scale()</td>144* <tr><th scope="row">Divide</th><td>dividend.scale() - divisor.scale()</td>145* <tr><th scope="row">Square root</th><td>radicand.scale()/2</td>146* </tbody>147* </table>148*149* These scales are the ones used by the methods which return exact150* arithmetic results; except that an exact divide may have to use a151* larger scale since the exact result may have more digits. For152* example, {@code 1/32} is {@code 0.03125}.153*154* <p>Before rounding, the scale of the logical exact intermediate155* result is the preferred scale for that operation. If the exact156* numerical result cannot be represented in {@code precision}157* digits, rounding selects the set of digits to return and the scale158* of the result is reduced from the scale of the intermediate result159* to the least scale which can represent the {@code precision}160* digits actually returned. If the exact result can be represented161* with at most {@code precision} digits, the representation162* of the result with the scale closest to the preferred scale is163* returned. In particular, an exactly representable quotient may be164* represented in fewer than {@code precision} digits by removing165* trailing zeros and decreasing the scale. For example, rounding to166* three digits using the {@linkplain RoundingMode#FLOOR floor}167* rounding mode, <br>168*169* {@code 19/100 = 0.19 // integer=19, scale=2} <br>170*171* but<br>172*173* {@code 21/110 = 0.190 // integer=190, scale=3} <br>174*175* <p>Note that for add, subtract, and multiply, the reduction in176* scale will equal the number of digit positions of the exact result177* which are discarded. If the rounding causes a carry propagation to178* create a new high-order digit position, an additional digit of the179* result is discarded than when no new digit position is created.180*181* <p>Other methods may have slightly different rounding semantics.182* For example, the result of the {@code pow} method using the183* {@linkplain #pow(int, MathContext) specified algorithm} can184* occasionally differ from the rounded mathematical result by more185* than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.186*187* <p>Two types of operations are provided for manipulating the scale188* of a {@code BigDecimal}: scaling/rounding operations and decimal189* point motion operations. Scaling/rounding operations ({@link190* #setScale setScale} and {@link #round round}) return a191* {@code BigDecimal} whose value is approximately (or exactly) equal192* to that of the operand, but whose scale or precision is the193* specified value; that is, they increase or decrease the precision194* of the stored number with minimal effect on its value. Decimal195* point motion operations ({@link #movePointLeft movePointLeft} and196* {@link #movePointRight movePointRight}) return a197* {@code BigDecimal} created from the operand by moving the decimal198* point a specified distance in the specified direction.199*200* <p>As a 32-bit integer, the set of values for the scale is large,201* but bounded. If the scale of a result would exceed the range of a202* 32-bit integer, either by overflow or underflow, the operation may203* throw an {@code ArithmeticException}.204*205* <p>For the sake of brevity and clarity, pseudo-code is used206* throughout the descriptions of {@code BigDecimal} methods. The207* pseudo-code expression {@code (i + j)} is shorthand for "a208* {@code BigDecimal} whose value is that of the {@code BigDecimal}209* {@code i} added to that of the {@code BigDecimal}210* {@code j}." The pseudo-code expression {@code (i == j)} is211* shorthand for "{@code true} if and only if the212* {@code BigDecimal} {@code i} represents the same value as the213* {@code BigDecimal} {@code j}." Other pseudo-code expressions214* are interpreted similarly. Square brackets are used to represent215* the particular {@code BigInteger} and scale pair defining a216* {@code BigDecimal} value; for example [19, 2] is the217* {@code BigDecimal} numerically equal to 0.19 having a scale of 2.218*219* <p>All methods and constructors for this class throw220* {@code NullPointerException} when passed a {@code null} object221* reference for any input parameter.222*223* @apiNote Care should be exercised if {@code BigDecimal} objects are224* used as keys in a {@link java.util.SortedMap SortedMap} or elements225* in a {@link java.util.SortedSet SortedSet} since {@code226* BigDecimal}'s <i>{@linkplain compareTo(BigDecimal) natural227* ordering}</i> is <em>inconsistent with equals</em>. See {@link228* Comparable}, {@link java.util.SortedMap} or {@link229* java.util.SortedSet} for more information.230*231* <h2>Relation to IEEE 754 Decimal Arithmetic</h2>232*233* Starting with its 2008 revision, the <cite>IEEE 754 Standard for234* Floating-point Arithmetic</cite> has covered decimal formats and235* operations. While there are broad similarities in the decimal236* arithmetic defined by IEEE 754 and by this class, there are notable237* differences as well. The fundamental similarity shared by {@code238* BigDecimal} and IEEE 754 decimal arithmetic is the conceptual239* operation of computing the mathematical infinitely precise real240* number value of an operation and then mapping that real number to a241* representable decimal floating-point value under a <em>rounding242* policy</em>. The rounding policy is called a {@linkplain243* RoundingMode rounding mode} for {@code BigDecimal} and called a244* rounding-direction attribute in IEEE 754-2019. When the exact value245* is not representable, the rounding policy determines which of the246* two representable decimal values bracketing the exact value is247* selected as the computed result. The notion of a <em>preferred248* scale/preferred exponent</em> is also shared by both systems.249*250* <p>For differences, IEEE 754 includes several kinds of values not251* modeled by {@code BigDecimal} including negative zero, signed252* infinities, and NaN (not-a-number). IEEE 754 defines formats, which253* are parameterized by base (binary or decimal), number of digits of254* precision, and exponent range. A format determines the set of255* representable values. Most operations accept as input one or more256* values of a given format and produce a result in the same format.257* A {@code BigDecimal}'s {@linkplain scale() scale} is equivalent to258* negating an IEEE 754 value's exponent. {@code BigDecimal} values do259* not have a format in the same sense; all values have the same260* possible range of scale/exponent and the {@linkplain261* unscaledValue() unscaled value} has arbitrary precision. Instead,262* for the {@code BigDecimal} operations taking a {@code MathContext}263* parameter, if the {@code MathContext} has a nonzero precision, the264* set of possible representable values for the result is determined265* by the precision of the {@code MathContext} argument. For example266* in {@code BigDecimal}, if a nonzero three-digit number and a267* nonzero four-digit number are multiplied together in the context of268* a {@code MathContext} object having a precision of three, the269* result will have three digits (assuming no overflow or underflow,270* etc.).271*272* <p>The rounding policies implemented by {@code BigDecimal}273* operations indicated by {@linkplain RoundingMode rounding modes}274* are a proper superset of the IEEE 754 rounding-direction275* attributes.276277* <p>{@code BigDecimal} arithmetic will most resemble IEEE 754278* decimal arithmetic if a {@code MathContext} corresponding to an279* IEEE 754 decimal format, such as {@linkplain MathContext#DECIMAL64280* decimal64} or {@linkplain MathContext#DECIMAL128 decimal128} is281* used to round all starting values and intermediate operations. The282* numerical values computed can differ if the exponent range of the283* IEEE 754 format being approximated is exceeded since a {@code284* MathContext} does not constrain the scale of {@code BigDecimal}285* results. Operations that would generate a NaN or exact infinity,286* such as dividing by zero, throw an {@code ArithmeticException} in287* {@code BigDecimal} arithmetic.288*289* @see BigInteger290* @see MathContext291* @see RoundingMode292* @see java.util.SortedMap293* @see java.util.SortedSet294* @author Josh Bloch295* @author Mike Cowlishaw296* @author Joseph D. Darcy297* @author Sergey V. Kuksenko298* @since 1.1299*/300public class BigDecimal extends Number implements Comparable<BigDecimal> {301/**302* The unscaled value of this BigDecimal, as returned by {@link303* #unscaledValue}.304*305* @serial306* @see #unscaledValue307*/308private final BigInteger intVal;309310/**311* The scale of this BigDecimal, as returned by {@link #scale}.312*313* @serial314* @see #scale315*/316private final int scale; // Note: this may have any value, so317// calculations must be done in longs318319/**320* The number of decimal digits in this BigDecimal, or 0 if the321* number of digits are not known (lookaside information). If322* nonzero, the value is guaranteed correct. Use the precision()323* method to obtain and set the value if it might be 0. This324* field is mutable until set nonzero.325*326* @since 1.5327*/328private transient int precision;329330/**331* Used to store the canonical string representation, if computed.332*/333private transient String stringCache;334335/**336* Sentinel value for {@link #intCompact} indicating the337* significand information is only available from {@code intVal}.338*/339static final long INFLATED = Long.MIN_VALUE;340341private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED);342343/**344* If the absolute value of the significand of this BigDecimal is345* less than or equal to {@code Long.MAX_VALUE}, the value can be346* compactly stored in this field and used in computations.347*/348private final transient long intCompact;349350// All 18-digit base ten strings fit into a long; not all 19-digit351// strings will352private static final int MAX_COMPACT_DIGITS = 18;353354/* Appease the serialization gods */355@java.io.Serial356private static final long serialVersionUID = 6108874887143696463L;357358// Cache of common small BigDecimal values.359private static final BigDecimal ZERO_THROUGH_TEN[] = {360new BigDecimal(BigInteger.ZERO, 0, 0, 1),361new BigDecimal(BigInteger.ONE, 1, 0, 1),362new BigDecimal(BigInteger.TWO, 2, 0, 1),363new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),364new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),365new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),366new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),367new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),368new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),369new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),370new BigDecimal(BigInteger.TEN, 10, 0, 2),371};372373// Cache of zero scaled by 0 - 15374private static final BigDecimal[] ZERO_SCALED_BY = {375ZERO_THROUGH_TEN[0],376new BigDecimal(BigInteger.ZERO, 0, 1, 1),377new BigDecimal(BigInteger.ZERO, 0, 2, 1),378new BigDecimal(BigInteger.ZERO, 0, 3, 1),379new BigDecimal(BigInteger.ZERO, 0, 4, 1),380new BigDecimal(BigInteger.ZERO, 0, 5, 1),381new BigDecimal(BigInteger.ZERO, 0, 6, 1),382new BigDecimal(BigInteger.ZERO, 0, 7, 1),383new BigDecimal(BigInteger.ZERO, 0, 8, 1),384new BigDecimal(BigInteger.ZERO, 0, 9, 1),385new BigDecimal(BigInteger.ZERO, 0, 10, 1),386new BigDecimal(BigInteger.ZERO, 0, 11, 1),387new BigDecimal(BigInteger.ZERO, 0, 12, 1),388new BigDecimal(BigInteger.ZERO, 0, 13, 1),389new BigDecimal(BigInteger.ZERO, 0, 14, 1),390new BigDecimal(BigInteger.ZERO, 0, 15, 1),391};392393// Half of Long.MIN_VALUE & Long.MAX_VALUE.394private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;395private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;396397// Constants398/**399* The value 0, with a scale of 0.400*401* @since 1.5402*/403public static final BigDecimal ZERO =404ZERO_THROUGH_TEN[0];405406/**407* The value 1, with a scale of 0.408*409* @since 1.5410*/411public static final BigDecimal ONE =412ZERO_THROUGH_TEN[1];413414/**415* The value 10, with a scale of 0.416*417* @since 1.5418*/419public static final BigDecimal TEN =420ZERO_THROUGH_TEN[10];421422/**423* The value 0.1, with a scale of 1.424*/425private static final BigDecimal ONE_TENTH = valueOf(1L, 1);426427/**428* The value 0.5, with a scale of 1.429*/430private static final BigDecimal ONE_HALF = valueOf(5L, 1);431432// Constructors433434/**435* Trusted package private constructor.436* Trusted simply means if val is INFLATED, intVal could not be null and437* if intVal is null, val could not be INFLATED.438*/439BigDecimal(BigInteger intVal, long val, int scale, int prec) {440this.scale = scale;441this.precision = prec;442this.intCompact = val;443this.intVal = intVal;444}445446/**447* Translates a character array representation of a448* {@code BigDecimal} into a {@code BigDecimal}, accepting the449* same sequence of characters as the {@link #BigDecimal(String)}450* constructor, while allowing a sub-array to be specified.451*452* @implNote If the sequence of characters is already available453* within a character array, using this constructor is faster than454* converting the {@code char} array to string and using the455* {@code BigDecimal(String)} constructor.456*457* @param in {@code char} array that is the source of characters.458* @param offset first character in the array to inspect.459* @param len number of characters to consider.460* @throws NumberFormatException if {@code in} is not a valid461* representation of a {@code BigDecimal} or the defined subarray462* is not wholly within {@code in}.463* @since 1.5464*/465public BigDecimal(char[] in, int offset, int len) {466this(in,offset,len,MathContext.UNLIMITED);467}468469/**470* Translates a character array representation of a471* {@code BigDecimal} into a {@code BigDecimal}, accepting the472* same sequence of characters as the {@link #BigDecimal(String)}473* constructor, while allowing a sub-array to be specified and474* with rounding according to the context settings.475*476* @implNote If the sequence of characters is already available477* within a character array, using this constructor is faster than478* converting the {@code char} array to string and using the479* {@code BigDecimal(String)} constructor.480*481* @param in {@code char} array that is the source of characters.482* @param offset first character in the array to inspect.483* @param len number of characters to consider.484* @param mc the context to use.485* @throws NumberFormatException if {@code in} is not a valid486* representation of a {@code BigDecimal} or the defined subarray487* is not wholly within {@code in}.488* @since 1.5489*/490public BigDecimal(char[] in, int offset, int len, MathContext mc) {491// protect against huge length, negative values, and integer overflow492try {493Objects.checkFromIndexSize(offset, len, in.length);494} catch (IndexOutOfBoundsException e) {495throw new NumberFormatException496("Bad offset or len arguments for char[] input.");497}498499// This is the primary string to BigDecimal constructor; all500// incoming strings end up here; it uses explicit (inline)501// parsing for speed and generates at most one intermediate502// (temporary) object (a char[] array) for non-compact case.503504// Use locals for all fields values until completion505int prec = 0; // record precision value506int scl = 0; // record scale value507long rs = 0; // the compact value in long508BigInteger rb = null; // the inflated value in BigInteger509// use array bounds checking to handle too-long, len == 0,510// bad offset, etc.511try {512// handle the sign513boolean isneg = false; // assume positive514if (in[offset] == '-') {515isneg = true; // leading minus means negative516offset++;517len--;518} else if (in[offset] == '+') { // leading + allowed519offset++;520len--;521}522523// should now be at numeric part of the significand524boolean dot = false; // true when there is a '.'525long exp = 0; // exponent526char c; // current character527boolean isCompact = (len <= MAX_COMPACT_DIGITS);528// integer significand array & idx is the index to it. The array529// is ONLY used when we can't use a compact representation.530int idx = 0;531if (isCompact) {532// First compact case, we need not to preserve the character533// and we can just compute the value in place.534for (; len > 0; offset++, len--) {535c = in[offset];536if ((c == '0')) { // have zero537if (prec == 0)538prec = 1;539else if (rs != 0) {540rs *= 10;541++prec;542} // else digit is a redundant leading zero543if (dot)544++scl;545} else if ((c >= '1' && c <= '9')) { // have digit546int digit = c - '0';547if (prec != 1 || rs != 0)548++prec; // prec unchanged if preceded by 0s549rs = rs * 10 + digit;550if (dot)551++scl;552} else if (c == '.') { // have dot553// have dot554if (dot) // two dots555throw new NumberFormatException("Character array"556+ " contains more than one decimal point.");557dot = true;558} else if (Character.isDigit(c)) { // slow path559int digit = Character.digit(c, 10);560if (digit == 0) {561if (prec == 0)562prec = 1;563else if (rs != 0) {564rs *= 10;565++prec;566} // else digit is a redundant leading zero567} else {568if (prec != 1 || rs != 0)569++prec; // prec unchanged if preceded by 0s570rs = rs * 10 + digit;571}572if (dot)573++scl;574} else if ((c == 'e') || (c == 'E')) {575exp = parseExp(in, offset, len);576// Next test is required for backwards compatibility577if ((int) exp != exp) // overflow578throw new NumberFormatException("Exponent overflow.");579break; // [saves a test]580} else {581throw new NumberFormatException("Character " + c582+ " is neither a decimal digit number, decimal point, nor"583+ " \"e\" notation exponential mark.");584}585}586if (prec == 0) // no digits found587throw new NumberFormatException("No digits found.");588// Adjust scale if exp is not zero.589if (exp != 0) { // had significant exponent590scl = adjustScale(scl, exp);591}592rs = isneg ? -rs : rs;593int mcp = mc.precision;594int drop = prec - mcp; // prec has range [1, MAX_INT], mcp has range [0, MAX_INT];595// therefore, this subtract cannot overflow596if (mcp > 0 && drop > 0) { // do rounding597while (drop > 0) {598scl = checkScaleNonZero((long) scl - drop);599rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);600prec = longDigitLength(rs);601drop = prec - mcp;602}603}604} else {605char coeff[] = new char[len];606for (; len > 0; offset++, len--) {607c = in[offset];608// have digit609if ((c >= '0' && c <= '9') || Character.isDigit(c)) {610// First compact case, we need not to preserve the character611// and we can just compute the value in place.612if (c == '0' || Character.digit(c, 10) == 0) {613if (prec == 0) {614coeff[idx] = c;615prec = 1;616} else if (idx != 0) {617coeff[idx++] = c;618++prec;619} // else c must be a redundant leading zero620} else {621if (prec != 1 || idx != 0)622++prec; // prec unchanged if preceded by 0s623coeff[idx++] = c;624}625if (dot)626++scl;627continue;628}629// have dot630if (c == '.') {631// have dot632if (dot) // two dots633throw new NumberFormatException("Character array"634+ " contains more than one decimal point.");635dot = true;636continue;637}638// exponent expected639if ((c != 'e') && (c != 'E'))640throw new NumberFormatException("Character array"641+ " is missing \"e\" notation exponential mark.");642exp = parseExp(in, offset, len);643// Next test is required for backwards compatibility644if ((int) exp != exp) // overflow645throw new NumberFormatException("Exponent overflow.");646break; // [saves a test]647}648// here when no characters left649if (prec == 0) // no digits found650throw new NumberFormatException("No digits found.");651// Adjust scale if exp is not zero.652if (exp != 0) { // had significant exponent653scl = adjustScale(scl, exp);654}655// Remove leading zeros from precision (digits count)656rb = new BigInteger(coeff, isneg ? -1 : 1, prec);657rs = compactValFor(rb);658int mcp = mc.precision;659if (mcp > 0 && (prec > mcp)) {660if (rs == INFLATED) {661int drop = prec - mcp;662while (drop > 0) {663scl = checkScaleNonZero((long) scl - drop);664rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode);665rs = compactValFor(rb);666if (rs != INFLATED) {667prec = longDigitLength(rs);668break;669}670prec = bigDigitLength(rb);671drop = prec - mcp;672}673}674if (rs != INFLATED) {675int drop = prec - mcp;676while (drop > 0) {677scl = checkScaleNonZero((long) scl - drop);678rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);679prec = longDigitLength(rs);680drop = prec - mcp;681}682rb = null;683}684}685}686} catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {687NumberFormatException nfe = new NumberFormatException();688nfe.initCause(e);689throw nfe;690}691this.scale = scl;692this.precision = prec;693this.intCompact = rs;694this.intVal = rb;695}696697private int adjustScale(int scl, long exp) {698long adjustedScale = scl - exp;699if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE)700throw new NumberFormatException("Scale out of range.");701scl = (int) adjustedScale;702return scl;703}704705/*706* parse exponent707*/708private static long parseExp(char[] in, int offset, int len){709long exp = 0;710offset++;711char c = in[offset];712len--;713boolean negexp = (c == '-');714// optional sign715if (negexp || c == '+') {716offset++;717c = in[offset];718len--;719}720if (len <= 0) // no exponent digits721throw new NumberFormatException("No exponent digits.");722// skip leading zeros in the exponent723while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) {724offset++;725c = in[offset];726len--;727}728if (len > 10) // too many nonzero exponent digits729throw new NumberFormatException("Too many nonzero exponent digits.");730// c now holds first digit of exponent731for (;; len--) {732int v;733if (c >= '0' && c <= '9') {734v = c - '0';735} else {736v = Character.digit(c, 10);737if (v < 0) // not a digit738throw new NumberFormatException("Not a digit.");739}740exp = exp * 10 + v;741if (len == 1)742break; // that was final character743offset++;744c = in[offset];745}746if (negexp) // apply sign747exp = -exp;748return exp;749}750751/**752* Translates a character array representation of a753* {@code BigDecimal} into a {@code BigDecimal}, accepting the754* same sequence of characters as the {@link #BigDecimal(String)}755* constructor.756*757* @implNote If the sequence of characters is already available758* as a character array, using this constructor is faster than759* converting the {@code char} array to string and using the760* {@code BigDecimal(String)} constructor.761*762* @param in {@code char} array that is the source of characters.763* @throws NumberFormatException if {@code in} is not a valid764* representation of a {@code BigDecimal}.765* @since 1.5766*/767public BigDecimal(char[] in) {768this(in, 0, in.length);769}770771/**772* Translates a character array representation of a773* {@code BigDecimal} into a {@code BigDecimal}, accepting the774* same sequence of characters as the {@link #BigDecimal(String)}775* constructor and with rounding according to the context776* settings.777*778* @implNote If the sequence of characters is already available779* as a character array, using this constructor is faster than780* converting the {@code char} array to string and using the781* {@code BigDecimal(String)} constructor.782*783* @param in {@code char} array that is the source of characters.784* @param mc the context to use.785* @throws NumberFormatException if {@code in} is not a valid786* representation of a {@code BigDecimal}.787* @since 1.5788*/789public BigDecimal(char[] in, MathContext mc) {790this(in, 0, in.length, mc);791}792793/**794* Translates the string representation of a {@code BigDecimal}795* into a {@code BigDecimal}. The string representation consists796* of an optional sign, {@code '+'} (<code> '\u002B'</code>) or797* {@code '-'} (<code>'\u002D'</code>), followed by a sequence of798* zero or more decimal digits ("the integer"), optionally799* followed by a fraction, optionally followed by an exponent.800*801* <p>The fraction consists of a decimal point followed by zero802* or more decimal digits. The string must contain at least one803* digit in either the integer or the fraction. The number formed804* by the sign, the integer and the fraction is referred to as the805* <i>significand</i>.806*807* <p>The exponent consists of the character {@code 'e'}808* (<code>'\u0065'</code>) or {@code 'E'} (<code>'\u0045'</code>)809* followed by one or more decimal digits. The value of the810* exponent must lie between -{@link Integer#MAX_VALUE} ({@link811* Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.812*813* <p>More formally, the strings this constructor accepts are814* described by the following grammar:815* <blockquote>816* <dl>817* <dt><i>BigDecimalString:</i>818* <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>819* <dt><i>Sign:</i>820* <dd>{@code +}821* <dd>{@code -}822* <dt><i>Significand:</i>823* <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>824* <dd>{@code .} <i>FractionPart</i>825* <dd><i>IntegerPart</i>826* <dt><i>IntegerPart:</i>827* <dd><i>Digits</i>828* <dt><i>FractionPart:</i>829* <dd><i>Digits</i>830* <dt><i>Exponent:</i>831* <dd><i>ExponentIndicator SignedInteger</i>832* <dt><i>ExponentIndicator:</i>833* <dd>{@code e}834* <dd>{@code E}835* <dt><i>SignedInteger:</i>836* <dd><i>Sign<sub>opt</sub> Digits</i>837* <dt><i>Digits:</i>838* <dd><i>Digit</i>839* <dd><i>Digits Digit</i>840* <dt><i>Digit:</i>841* <dd>any character for which {@link Character#isDigit}842* returns {@code true}, including 0, 1, 2 ...843* </dl>844* </blockquote>845*846* <p>The scale of the returned {@code BigDecimal} will be the847* number of digits in the fraction, or zero if the string848* contains no decimal point, subject to adjustment for any849* exponent; if the string contains an exponent, the exponent is850* subtracted from the scale. The value of the resulting scale851* must lie between {@code Integer.MIN_VALUE} and852* {@code Integer.MAX_VALUE}, inclusive.853*854* <p>The character-to-digit mapping is provided by {@link855* java.lang.Character#digit} set to convert to radix 10. The856* String may not contain any extraneous characters (whitespace,857* for example).858*859* <p><b>Examples:</b><br>860* The value of the returned {@code BigDecimal} is equal to861* <i>significand</i> × 10<sup> <i>exponent</i></sup>.862* For each string on the left, the resulting representation863* [{@code BigInteger}, {@code scale}] is shown on the right.864* <pre>865* "0" [0,0]866* "0.00" [0,2]867* "123" [123,0]868* "-123" [-123,0]869* "1.23E3" [123,-1]870* "1.23E+3" [123,-1]871* "12.3E+7" [123,-6]872* "12.0" [120,1]873* "12.3" [123,1]874* "0.00123" [123,5]875* "-1.23E-12" [-123,14]876* "1234.5E-4" [12345,5]877* "0E+7" [0,-7]878* "-0" [0,0]879* </pre>880*881* @apiNote For values other than {@code float} and882* {@code double} NaN and ±Infinity, this constructor is883* compatible with the values returned by {@link Float#toString}884* and {@link Double#toString}. This is generally the preferred885* way to convert a {@code float} or {@code double} into a886* BigDecimal, as it doesn't suffer from the unpredictability of887* the {@link #BigDecimal(double)} constructor.888*889* @param val String representation of {@code BigDecimal}.890*891* @throws NumberFormatException if {@code val} is not a valid892* representation of a {@code BigDecimal}.893*/894public BigDecimal(String val) {895this(val.toCharArray(), 0, val.length());896}897898/**899* Translates the string representation of a {@code BigDecimal}900* into a {@code BigDecimal}, accepting the same strings as the901* {@link #BigDecimal(String)} constructor, with rounding902* according to the context settings.903*904* @param val string representation of a {@code BigDecimal}.905* @param mc the context to use.906* @throws NumberFormatException if {@code val} is not a valid907* representation of a BigDecimal.908* @since 1.5909*/910public BigDecimal(String val, MathContext mc) {911this(val.toCharArray(), 0, val.length(), mc);912}913914/**915* Translates a {@code double} into a {@code BigDecimal} which916* is the exact decimal representation of the {@code double}'s917* binary floating-point value. The scale of the returned918* {@code BigDecimal} is the smallest value such that919* <code>(10<sup>scale</sup> × val)</code> is an integer.920* <p>921* <b>Notes:</b>922* <ol>923* <li>924* The results of this constructor can be somewhat unpredictable.925* One might assume that writing {@code new BigDecimal(0.1)} in926* Java creates a {@code BigDecimal} which is exactly equal to927* 0.1 (an unscaled value of 1, with a scale of 1), but it is928* actually equal to929* 0.1000000000000000055511151231257827021181583404541015625.930* This is because 0.1 cannot be represented exactly as a931* {@code double} (or, for that matter, as a binary fraction of932* any finite length). Thus, the value that is being passed933* <em>in</em> to the constructor is not exactly equal to 0.1,934* appearances notwithstanding.935*936* <li>937* The {@code String} constructor, on the other hand, is938* perfectly predictable: writing {@code new BigDecimal("0.1")}939* creates a {@code BigDecimal} which is <em>exactly</em> equal to940* 0.1, as one would expect. Therefore, it is generally941* recommended that the {@linkplain #BigDecimal(String)942* String constructor} be used in preference to this one.943*944* <li>945* When a {@code double} must be used as a source for a946* {@code BigDecimal}, note that this constructor provides an947* exact conversion; it does not give the same result as948* converting the {@code double} to a {@code String} using the949* {@link Double#toString(double)} method and then using the950* {@link #BigDecimal(String)} constructor. To get that result,951* use the {@code static} {@link #valueOf(double)} method.952* </ol>953*954* @param val {@code double} value to be converted to955* {@code BigDecimal}.956* @throws NumberFormatException if {@code val} is infinite or NaN.957*/958public BigDecimal(double val) {959this(val,MathContext.UNLIMITED);960}961962/**963* Translates a {@code double} into a {@code BigDecimal}, with964* rounding according to the context settings. The scale of the965* {@code BigDecimal} is the smallest value such that966* <code>(10<sup>scale</sup> × val)</code> is an integer.967*968* <p>The results of this constructor can be somewhat unpredictable969* and its use is generally not recommended; see the notes under970* the {@link #BigDecimal(double)} constructor.971*972* @param val {@code double} value to be converted to973* {@code BigDecimal}.974* @param mc the context to use.975* @throws NumberFormatException if {@code val} is infinite or NaN.976* @since 1.5977*/978public BigDecimal(double val, MathContext mc) {979if (Double.isInfinite(val) || Double.isNaN(val))980throw new NumberFormatException("Infinite or NaN");981// Translate the double into sign, exponent and significand, according982// to the formulae in JLS, Section 20.10.22.983long valBits = Double.doubleToLongBits(val);984int sign = ((valBits >> 63) == 0 ? 1 : -1);985int exponent = (int) ((valBits >> 52) & 0x7ffL);986long significand = (exponent == 0987? (valBits & ((1L << 52) - 1)) << 1988: (valBits & ((1L << 52) - 1)) | (1L << 52));989exponent -= 1075;990// At this point, val == sign * significand * 2**exponent.991992/*993* Special case zero to suppress nonterminating normalization and bogus994* scale calculation.995*/996if (significand == 0) {997this.intVal = BigInteger.ZERO;998this.scale = 0;999this.intCompact = 0;1000this.precision = 1;1001return;1002}1003// Normalize1004while ((significand & 1) == 0) { // i.e., significand is even1005significand >>= 1;1006exponent++;1007}1008int scl = 0;1009// Calculate intVal and scale1010BigInteger rb;1011long compactVal = sign * significand;1012if (exponent == 0) {1013rb = (compactVal == INFLATED) ? INFLATED_BIGINT : null;1014} else {1015if (exponent < 0) {1016rb = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);1017scl = -exponent;1018} else { // (exponent > 0)1019rb = BigInteger.TWO.pow(exponent).multiply(compactVal);1020}1021compactVal = compactValFor(rb);1022}1023int prec = 0;1024int mcp = mc.precision;1025if (mcp > 0) { // do rounding1026int mode = mc.roundingMode.oldMode;1027int drop;1028if (compactVal == INFLATED) {1029prec = bigDigitLength(rb);1030drop = prec - mcp;1031while (drop > 0) {1032scl = checkScaleNonZero((long) scl - drop);1033rb = divideAndRoundByTenPow(rb, drop, mode);1034compactVal = compactValFor(rb);1035if (compactVal != INFLATED) {1036break;1037}1038prec = bigDigitLength(rb);1039drop = prec - mcp;1040}1041}1042if (compactVal != INFLATED) {1043prec = longDigitLength(compactVal);1044drop = prec - mcp;1045while (drop > 0) {1046scl = checkScaleNonZero((long) scl - drop);1047compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);1048prec = longDigitLength(compactVal);1049drop = prec - mcp;1050}1051rb = null;1052}1053}1054this.intVal = rb;1055this.intCompact = compactVal;1056this.scale = scl;1057this.precision = prec;1058}10591060/**1061* Translates a {@code BigInteger} into a {@code BigDecimal}.1062* The scale of the {@code BigDecimal} is zero.1063*1064* @param val {@code BigInteger} value to be converted to1065* {@code BigDecimal}.1066*/1067public BigDecimal(BigInteger val) {1068scale = 0;1069intVal = val;1070intCompact = compactValFor(val);1071}10721073/**1074* Translates a {@code BigInteger} into a {@code BigDecimal}1075* rounding according to the context settings. The scale of the1076* {@code BigDecimal} is zero.1077*1078* @param val {@code BigInteger} value to be converted to1079* {@code BigDecimal}.1080* @param mc the context to use.1081* @since 1.51082*/1083public BigDecimal(BigInteger val, MathContext mc) {1084this(val,0,mc);1085}10861087/**1088* Translates a {@code BigInteger} unscaled value and an1089* {@code int} scale into a {@code BigDecimal}. The value of1090* the {@code BigDecimal} is1091* <code>(unscaledVal × 10<sup>-scale</sup>)</code>.1092*1093* @param unscaledVal unscaled value of the {@code BigDecimal}.1094* @param scale scale of the {@code BigDecimal}.1095*/1096public BigDecimal(BigInteger unscaledVal, int scale) {1097// Negative scales are now allowed1098this.intVal = unscaledVal;1099this.intCompact = compactValFor(unscaledVal);1100this.scale = scale;1101}11021103/**1104* Translates a {@code BigInteger} unscaled value and an1105* {@code int} scale into a {@code BigDecimal}, with rounding1106* according to the context settings. The value of the1107* {@code BigDecimal} is <code>(unscaledVal ×1108* 10<sup>-scale</sup>)</code>, rounded according to the1109* {@code precision} and rounding mode settings.1110*1111* @param unscaledVal unscaled value of the {@code BigDecimal}.1112* @param scale scale of the {@code BigDecimal}.1113* @param mc the context to use.1114* @since 1.51115*/1116public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {1117long compactVal = compactValFor(unscaledVal);1118int mcp = mc.precision;1119int prec = 0;1120if (mcp > 0) { // do rounding1121int mode = mc.roundingMode.oldMode;1122if (compactVal == INFLATED) {1123prec = bigDigitLength(unscaledVal);1124int drop = prec - mcp;1125while (drop > 0) {1126scale = checkScaleNonZero((long) scale - drop);1127unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode);1128compactVal = compactValFor(unscaledVal);1129if (compactVal != INFLATED) {1130break;1131}1132prec = bigDigitLength(unscaledVal);1133drop = prec - mcp;1134}1135}1136if (compactVal != INFLATED) {1137prec = longDigitLength(compactVal);1138int drop = prec - mcp; // drop can't be more than 181139while (drop > 0) {1140scale = checkScaleNonZero((long) scale - drop);1141compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode);1142prec = longDigitLength(compactVal);1143drop = prec - mcp;1144}1145unscaledVal = null;1146}1147}1148this.intVal = unscaledVal;1149this.intCompact = compactVal;1150this.scale = scale;1151this.precision = prec;1152}11531154/**1155* Translates an {@code int} into a {@code BigDecimal}. The1156* scale of the {@code BigDecimal} is zero.1157*1158* @param val {@code int} value to be converted to1159* {@code BigDecimal}.1160* @since 1.51161*/1162public BigDecimal(int val) {1163this.intCompact = val;1164this.scale = 0;1165this.intVal = null;1166}11671168/**1169* Translates an {@code int} into a {@code BigDecimal}, with1170* rounding according to the context settings. The scale of the1171* {@code BigDecimal}, before any rounding, is zero.1172*1173* @param val {@code int} value to be converted to {@code BigDecimal}.1174* @param mc the context to use.1175* @since 1.51176*/1177public BigDecimal(int val, MathContext mc) {1178int mcp = mc.precision;1179long compactVal = val;1180int scl = 0;1181int prec = 0;1182if (mcp > 0) { // do rounding1183prec = longDigitLength(compactVal);1184int drop = prec - mcp; // drop can't be more than 181185while (drop > 0) {1186scl = checkScaleNonZero((long) scl - drop);1187compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);1188prec = longDigitLength(compactVal);1189drop = prec - mcp;1190}1191}1192this.intVal = null;1193this.intCompact = compactVal;1194this.scale = scl;1195this.precision = prec;1196}11971198/**1199* Translates a {@code long} into a {@code BigDecimal}. The1200* scale of the {@code BigDecimal} is zero.1201*1202* @param val {@code long} value to be converted to {@code BigDecimal}.1203* @since 1.51204*/1205public BigDecimal(long val) {1206this.intCompact = val;1207this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;1208this.scale = 0;1209}12101211/**1212* Translates a {@code long} into a {@code BigDecimal}, with1213* rounding according to the context settings. The scale of the1214* {@code BigDecimal}, before any rounding, is zero.1215*1216* @param val {@code long} value to be converted to {@code BigDecimal}.1217* @param mc the context to use.1218* @since 1.51219*/1220public BigDecimal(long val, MathContext mc) {1221int mcp = mc.precision;1222int mode = mc.roundingMode.oldMode;1223int prec = 0;1224int scl = 0;1225BigInteger rb = (val == INFLATED) ? INFLATED_BIGINT : null;1226if (mcp > 0) { // do rounding1227if (val == INFLATED) {1228prec = 19;1229int drop = prec - mcp;1230while (drop > 0) {1231scl = checkScaleNonZero((long) scl - drop);1232rb = divideAndRoundByTenPow(rb, drop, mode);1233val = compactValFor(rb);1234if (val != INFLATED) {1235break;1236}1237prec = bigDigitLength(rb);1238drop = prec - mcp;1239}1240}1241if (val != INFLATED) {1242prec = longDigitLength(val);1243int drop = prec - mcp;1244while (drop > 0) {1245scl = checkScaleNonZero((long) scl - drop);1246val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);1247prec = longDigitLength(val);1248drop = prec - mcp;1249}1250rb = null;1251}1252}1253this.intVal = rb;1254this.intCompact = val;1255this.scale = scl;1256this.precision = prec;1257}12581259// Static Factory Methods12601261/**1262* Translates a {@code long} unscaled value and an1263* {@code int} scale into a {@code BigDecimal}.1264*1265* @apiNote This static factory method is provided in preference1266* to a ({@code long}, {@code int}) constructor because it allows1267* for reuse of frequently used {@code BigDecimal} values.1268*1269* @param unscaledVal unscaled value of the {@code BigDecimal}.1270* @param scale scale of the {@code BigDecimal}.1271* @return a {@code BigDecimal} whose value is1272* <code>(unscaledVal × 10<sup>-scale</sup>)</code>.1273*/1274public static BigDecimal valueOf(long unscaledVal, int scale) {1275if (scale == 0)1276return valueOf(unscaledVal);1277else if (unscaledVal == 0) {1278return zeroValueOf(scale);1279}1280return new BigDecimal(unscaledVal == INFLATED ?1281INFLATED_BIGINT : null,1282unscaledVal, scale, 0);1283}12841285/**1286* Translates a {@code long} value into a {@code BigDecimal}1287* with a scale of zero.1288*1289* @apiNote This static factory method is provided in preference1290* to a ({@code long}) constructor because it allows for reuse of1291* frequently used {@code BigDecimal} values.1292*1293* @param val value of the {@code BigDecimal}.1294* @return a {@code BigDecimal} whose value is {@code val}.1295*/1296public static BigDecimal valueOf(long val) {1297if (val >= 0 && val < ZERO_THROUGH_TEN.length)1298return ZERO_THROUGH_TEN[(int)val];1299else if (val != INFLATED)1300return new BigDecimal(null, val, 0, 0);1301return new BigDecimal(INFLATED_BIGINT, val, 0, 0);1302}13031304static BigDecimal valueOf(long unscaledVal, int scale, int prec) {1305if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {1306return ZERO_THROUGH_TEN[(int) unscaledVal];1307} else if (unscaledVal == 0) {1308return zeroValueOf(scale);1309}1310return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,1311unscaledVal, scale, prec);1312}13131314static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {1315long val = compactValFor(intVal);1316if (val == 0) {1317return zeroValueOf(scale);1318} else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {1319return ZERO_THROUGH_TEN[(int) val];1320}1321return new BigDecimal(intVal, val, scale, prec);1322}13231324static BigDecimal zeroValueOf(int scale) {1325if (scale >= 0 && scale < ZERO_SCALED_BY.length)1326return ZERO_SCALED_BY[scale];1327else1328return new BigDecimal(BigInteger.ZERO, 0, scale, 1);1329}13301331/**1332* Translates a {@code double} into a {@code BigDecimal}, using1333* the {@code double}'s canonical string representation provided1334* by the {@link Double#toString(double)} method.1335*1336* @apiNote This is generally the preferred way to convert a1337* {@code double} (or {@code float}) into a {@code BigDecimal}, as1338* the value returned is equal to that resulting from constructing1339* a {@code BigDecimal} from the result of using {@link1340* Double#toString(double)}.1341*1342* @param val {@code double} to convert to a {@code BigDecimal}.1343* @return a {@code BigDecimal} whose value is equal to or approximately1344* equal to the value of {@code val}.1345* @throws NumberFormatException if {@code val} is infinite or NaN.1346* @since 1.51347*/1348public static BigDecimal valueOf(double val) {1349// Reminder: a zero double returns '0.0', so we cannot fastpath1350// to use the constant ZERO. This might be important enough to1351// justify a factory approach, a cache, or a few private1352// constants, later.1353return new BigDecimal(Double.toString(val));1354}13551356// Arithmetic Operations1357/**1358* Returns a {@code BigDecimal} whose value is {@code (this +1359* augend)}, and whose scale is {@code max(this.scale(),1360* augend.scale())}.1361*1362* @param augend value to be added to this {@code BigDecimal}.1363* @return {@code this + augend}1364*/1365public BigDecimal add(BigDecimal augend) {1366if (this.intCompact != INFLATED) {1367if ((augend.intCompact != INFLATED)) {1368return add(this.intCompact, this.scale, augend.intCompact, augend.scale);1369} else {1370return add(this.intCompact, this.scale, augend.intVal, augend.scale);1371}1372} else {1373if ((augend.intCompact != INFLATED)) {1374return add(augend.intCompact, augend.scale, this.intVal, this.scale);1375} else {1376return add(this.intVal, this.scale, augend.intVal, augend.scale);1377}1378}1379}13801381/**1382* Returns a {@code BigDecimal} whose value is {@code (this + augend)},1383* with rounding according to the context settings.1384*1385* If either number is zero and the precision setting is nonzero then1386* the other number, rounded if necessary, is used as the result.1387*1388* @param augend value to be added to this {@code BigDecimal}.1389* @param mc the context to use.1390* @return {@code this + augend}, rounded as necessary.1391* @since 1.51392*/1393public BigDecimal add(BigDecimal augend, MathContext mc) {1394if (mc.precision == 0)1395return add(augend);1396BigDecimal lhs = this;13971398// If either number is zero then the other number, rounded and1399// scaled if necessary, is used as the result.1400{1401boolean lhsIsZero = lhs.signum() == 0;1402boolean augendIsZero = augend.signum() == 0;14031404if (lhsIsZero || augendIsZero) {1405int preferredScale = Math.max(lhs.scale(), augend.scale());1406BigDecimal result;14071408if (lhsIsZero && augendIsZero)1409return zeroValueOf(preferredScale);1410result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);14111412if (result.scale() == preferredScale)1413return result;1414else if (result.scale() > preferredScale) {1415return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale);1416} else { // result.scale < preferredScale1417int precisionDiff = mc.precision - result.precision();1418int scaleDiff = preferredScale - result.scale();14191420if (precisionDiff >= scaleDiff)1421return result.setScale(preferredScale); // can achieve target scale1422else1423return result.setScale(result.scale() + precisionDiff);1424}1425}1426}14271428long padding = (long) lhs.scale - augend.scale;1429if (padding != 0) { // scales differ; alignment needed1430BigDecimal arg[] = preAlign(lhs, augend, padding, mc);1431matchScale(arg);1432lhs = arg[0];1433augend = arg[1];1434}1435return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc);1436}14371438/**1439* Returns an array of length two, the sum of whose entries is1440* equal to the rounded sum of the {@code BigDecimal} arguments.1441*1442* <p>If the digit positions of the arguments have a sufficient1443* gap between them, the value smaller in magnitude can be1444* condensed into a {@literal "sticky bit"} and the end result will1445* round the same way <em>if</em> the precision of the final1446* result does not include the high order digit of the small1447* magnitude operand.1448*1449* <p>Note that while strictly speaking this is an optimization,1450* it makes a much wider range of additions practical.1451*1452* <p>This corresponds to a pre-shift operation in a fixed1453* precision floating-point adder; this method is complicated by1454* variable precision of the result as determined by the1455* MathContext. A more nuanced operation could implement a1456* {@literal "right shift"} on the smaller magnitude operand so1457* that the number of digits of the smaller operand could be1458* reduced even though the significands partially overlapped.1459*/1460private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) {1461assert padding != 0;1462BigDecimal big;1463BigDecimal small;14641465if (padding < 0) { // lhs is big; augend is small1466big = lhs;1467small = augend;1468} else { // lhs is small; augend is big1469big = augend;1470small = lhs;1471}14721473/*1474* This is the estimated scale of an ulp of the result; it assumes that1475* the result doesn't have a carry-out on a true add (e.g. 999 + 1 =>1476* 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 =>1477* 98.8)1478*/1479long estResultUlpScale = (long) big.scale - big.precision() + mc.precision;14801481/*1482* The low-order digit position of big is big.scale(). This1483* is true regardless of whether big has a positive or1484* negative scale. The high-order digit position of small is1485* small.scale - (small.precision() - 1). To do the full1486* condensation, the digit positions of big and small must be1487* disjoint *and* the digit positions of small should not be1488* directly visible in the result.1489*/1490long smallHighDigitPos = (long) small.scale - small.precision() + 1;1491if (smallHighDigitPos > big.scale + 2 && // big and small disjoint1492smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible1493small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));1494}14951496// Since addition is symmetric, preserving input order in1497// returned operands doesn't matter1498BigDecimal[] result = {big, small};1499return result;1500}15011502/**1503* Returns a {@code BigDecimal} whose value is {@code (this -1504* subtrahend)}, and whose scale is {@code max(this.scale(),1505* subtrahend.scale())}.1506*1507* @param subtrahend value to be subtracted from this {@code BigDecimal}.1508* @return {@code this - subtrahend}1509*/1510public BigDecimal subtract(BigDecimal subtrahend) {1511if (this.intCompact != INFLATED) {1512if ((subtrahend.intCompact != INFLATED)) {1513return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale);1514} else {1515return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale);1516}1517} else {1518if ((subtrahend.intCompact != INFLATED)) {1519// Pair of subtrahend values given before pair of1520// values from this BigDecimal to avoid need for1521// method overloading on the specialized add method1522return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale);1523} else {1524return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale);1525}1526}1527}15281529/**1530* Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},1531* with rounding according to the context settings.1532*1533* If {@code subtrahend} is zero then this, rounded if necessary, is used as the1534* result. If this is zero then the result is {@code subtrahend.negate(mc)}.1535*1536* @param subtrahend value to be subtracted from this {@code BigDecimal}.1537* @param mc the context to use.1538* @return {@code this - subtrahend}, rounded as necessary.1539* @since 1.51540*/1541public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {1542if (mc.precision == 0)1543return subtract(subtrahend);1544// share the special rounding code in add()1545return add(subtrahend.negate(), mc);1546}15471548/**1549* Returns a {@code BigDecimal} whose value is <code>(this ×1550* multiplicand)</code>, and whose scale is {@code (this.scale() +1551* multiplicand.scale())}.1552*1553* @param multiplicand value to be multiplied by this {@code BigDecimal}.1554* @return {@code this * multiplicand}1555*/1556public BigDecimal multiply(BigDecimal multiplicand) {1557int productScale = checkScale((long) scale + multiplicand.scale);1558if (this.intCompact != INFLATED) {1559if ((multiplicand.intCompact != INFLATED)) {1560return multiply(this.intCompact, multiplicand.intCompact, productScale);1561} else {1562return multiply(this.intCompact, multiplicand.intVal, productScale);1563}1564} else {1565if ((multiplicand.intCompact != INFLATED)) {1566return multiply(multiplicand.intCompact, this.intVal, productScale);1567} else {1568return multiply(this.intVal, multiplicand.intVal, productScale);1569}1570}1571}15721573/**1574* Returns a {@code BigDecimal} whose value is <code>(this ×1575* multiplicand)</code>, with rounding according to the context settings.1576*1577* @param multiplicand value to be multiplied by this {@code BigDecimal}.1578* @param mc the context to use.1579* @return {@code this * multiplicand}, rounded as necessary.1580* @since 1.51581*/1582public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {1583if (mc.precision == 0)1584return multiply(multiplicand);1585int productScale = checkScale((long) scale + multiplicand.scale);1586if (this.intCompact != INFLATED) {1587if ((multiplicand.intCompact != INFLATED)) {1588return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc);1589} else {1590return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc);1591}1592} else {1593if ((multiplicand.intCompact != INFLATED)) {1594return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc);1595} else {1596return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc);1597}1598}1599}16001601/**1602* Returns a {@code BigDecimal} whose value is {@code (this /1603* divisor)}, and whose scale is as specified. If rounding must1604* be performed to generate a result with the specified scale, the1605* specified rounding mode is applied.1606*1607* @deprecated The method {@link #divide(BigDecimal, int, RoundingMode)}1608* should be used in preference to this legacy method.1609*1610* @param divisor value by which this {@code BigDecimal} is to be divided.1611* @param scale scale of the {@code BigDecimal} quotient to be returned.1612* @param roundingMode rounding mode to apply.1613* @return {@code this / divisor}1614* @throws ArithmeticException if {@code divisor} is zero,1615* {@code roundingMode==ROUND_UNNECESSARY} and1616* the specified scale is insufficient to represent the result1617* of the division exactly.1618* @throws IllegalArgumentException if {@code roundingMode} does not1619* represent a valid rounding mode.1620* @see #ROUND_UP1621* @see #ROUND_DOWN1622* @see #ROUND_CEILING1623* @see #ROUND_FLOOR1624* @see #ROUND_HALF_UP1625* @see #ROUND_HALF_DOWN1626* @see #ROUND_HALF_EVEN1627* @see #ROUND_UNNECESSARY1628*/1629@Deprecated(since="9")1630public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {1631if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)1632throw new IllegalArgumentException("Invalid rounding mode");1633if (this.intCompact != INFLATED) {1634if ((divisor.intCompact != INFLATED)) {1635return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);1636} else {1637return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);1638}1639} else {1640if ((divisor.intCompact != INFLATED)) {1641return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode);1642} else {1643return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode);1644}1645}1646}16471648/**1649* Returns a {@code BigDecimal} whose value is {@code (this /1650* divisor)}, and whose scale is as specified. If rounding must1651* be performed to generate a result with the specified scale, the1652* specified rounding mode is applied.1653*1654* @param divisor value by which this {@code BigDecimal} is to be divided.1655* @param scale scale of the {@code BigDecimal} quotient to be returned.1656* @param roundingMode rounding mode to apply.1657* @return {@code this / divisor}1658* @throws ArithmeticException if {@code divisor} is zero,1659* {@code roundingMode==RoundingMode.UNNECESSARY} and1660* the specified scale is insufficient to represent the result1661* of the division exactly.1662* @since 1.51663*/1664public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {1665return divide(divisor, scale, roundingMode.oldMode);1666}16671668/**1669* Returns a {@code BigDecimal} whose value is {@code (this /1670* divisor)}, and whose scale is {@code this.scale()}. If1671* rounding must be performed to generate a result with the given1672* scale, the specified rounding mode is applied.1673*1674* @deprecated The method {@link #divide(BigDecimal, RoundingMode)}1675* should be used in preference to this legacy method.1676*1677* @param divisor value by which this {@code BigDecimal} is to be divided.1678* @param roundingMode rounding mode to apply.1679* @return {@code this / divisor}1680* @throws ArithmeticException if {@code divisor==0}, or1681* {@code roundingMode==ROUND_UNNECESSARY} and1682* {@code this.scale()} is insufficient to represent the result1683* of the division exactly.1684* @throws IllegalArgumentException if {@code roundingMode} does not1685* represent a valid rounding mode.1686* @see #ROUND_UP1687* @see #ROUND_DOWN1688* @see #ROUND_CEILING1689* @see #ROUND_FLOOR1690* @see #ROUND_HALF_UP1691* @see #ROUND_HALF_DOWN1692* @see #ROUND_HALF_EVEN1693* @see #ROUND_UNNECESSARY1694*/1695@Deprecated(since="9")1696public BigDecimal divide(BigDecimal divisor, int roundingMode) {1697return this.divide(divisor, scale, roundingMode);1698}16991700/**1701* Returns a {@code BigDecimal} whose value is {@code (this /1702* divisor)}, and whose scale is {@code this.scale()}. If1703* rounding must be performed to generate a result with the given1704* scale, the specified rounding mode is applied.1705*1706* @param divisor value by which this {@code BigDecimal} is to be divided.1707* @param roundingMode rounding mode to apply.1708* @return {@code this / divisor}1709* @throws ArithmeticException if {@code divisor==0}, or1710* {@code roundingMode==RoundingMode.UNNECESSARY} and1711* {@code this.scale()} is insufficient to represent the result1712* of the division exactly.1713* @since 1.51714*/1715public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {1716return this.divide(divisor, scale, roundingMode.oldMode);1717}17181719/**1720* Returns a {@code BigDecimal} whose value is {@code (this /1721* divisor)}, and whose preferred scale is {@code (this.scale() -1722* divisor.scale())}; if the exact quotient cannot be1723* represented (because it has a non-terminating decimal1724* expansion) an {@code ArithmeticException} is thrown.1725*1726* @param divisor value by which this {@code BigDecimal} is to be divided.1727* @throws ArithmeticException if the exact quotient does not have a1728* terminating decimal expansion, including dividing by zero1729* @return {@code this / divisor}1730* @since 1.51731* @author Joseph D. Darcy1732*/1733public BigDecimal divide(BigDecimal divisor) {1734/*1735* Handle zero cases first.1736*/1737if (divisor.signum() == 0) { // x/01738if (this.signum() == 0) // 0/01739throw new ArithmeticException("Division undefined"); // NaN1740throw new ArithmeticException("Division by zero");1741}17421743// Calculate preferred scale1744int preferredScale = saturateLong((long) this.scale - divisor.scale);17451746if (this.signum() == 0) // 0/y1747return zeroValueOf(preferredScale);1748else {1749/*1750* If the quotient this/divisor has a terminating decimal1751* expansion, the expansion can have no more than1752* (a.precision() + ceil(10*b.precision)/3) digits.1753* Therefore, create a MathContext object with this1754* precision and do a divide with the UNNECESSARY rounding1755* mode.1756*/1757MathContext mc = new MathContext( (int)Math.min(this.precision() +1758(long)Math.ceil(10.0*divisor.precision()/3.0),1759Integer.MAX_VALUE),1760RoundingMode.UNNECESSARY);1761BigDecimal quotient;1762try {1763quotient = this.divide(divisor, mc);1764} catch (ArithmeticException e) {1765throw new ArithmeticException("Non-terminating decimal expansion; " +1766"no exact representable decimal result.");1767}17681769int quotientScale = quotient.scale();17701771// divide(BigDecimal, mc) tries to adjust the quotient to1772// the desired one by removing trailing zeros; since the1773// exact divide method does not have an explicit digit1774// limit, we can add zeros too.1775if (preferredScale > quotientScale)1776return quotient.setScale(preferredScale, ROUND_UNNECESSARY);17771778return quotient;1779}1780}17811782/**1783* Returns a {@code BigDecimal} whose value is {@code (this /1784* divisor)}, with rounding according to the context settings.1785*1786* @param divisor value by which this {@code BigDecimal} is to be divided.1787* @param mc the context to use.1788* @return {@code this / divisor}, rounded as necessary.1789* @throws ArithmeticException if the result is inexact but the1790* rounding mode is {@code UNNECESSARY} or1791* {@code mc.precision == 0} and the quotient has a1792* non-terminating decimal expansion,including dividing by zero1793* @since 1.51794*/1795public BigDecimal divide(BigDecimal divisor, MathContext mc) {1796int mcp = mc.precision;1797if (mcp == 0)1798return divide(divisor);17991800BigDecimal dividend = this;1801long preferredScale = (long)dividend.scale - divisor.scale;1802// Now calculate the answer. We use the existing1803// divide-and-round method, but as this rounds to scale we have1804// to normalize the values here to achieve the desired result.1805// For x/y we first handle y=0 and x=0, and then normalize x and1806// y to give x' and y' with the following constraints:1807// (a) 0.1 <= x' < 11808// (b) x' <= y' < 10*x'1809// Dividing x'/y' with the required scale set to mc.precision then1810// will give a result in the range 0.1 to 1 rounded to exactly1811// the right number of digits (except in the case of a result of1812// 1.000... which can arise when x=y, or when rounding overflows1813// The 1.000... case will reduce properly to 1.1814if (divisor.signum() == 0) { // x/01815if (dividend.signum() == 0) // 0/01816throw new ArithmeticException("Division undefined"); // NaN1817throw new ArithmeticException("Division by zero");1818}1819if (dividend.signum() == 0) // 0/y1820return zeroValueOf(saturateLong(preferredScale));1821int xscale = dividend.precision();1822int yscale = divisor.precision();1823if(dividend.intCompact!=INFLATED) {1824if(divisor.intCompact!=INFLATED) {1825return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc);1826} else {1827return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc);1828}1829} else {1830if(divisor.intCompact!=INFLATED) {1831return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc);1832} else {1833return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc);1834}1835}1836}18371838/**1839* Returns a {@code BigDecimal} whose value is the integer part1840* of the quotient {@code (this / divisor)} rounded down. The1841* preferred scale of the result is {@code (this.scale() -1842* divisor.scale())}.1843*1844* @param divisor value by which this {@code BigDecimal} is to be divided.1845* @return The integer part of {@code this / divisor}.1846* @throws ArithmeticException if {@code divisor==0}1847* @since 1.51848*/1849public BigDecimal divideToIntegralValue(BigDecimal divisor) {1850// Calculate preferred scale1851int preferredScale = saturateLong((long) this.scale - divisor.scale);1852if (this.compareMagnitude(divisor) < 0) {1853// much faster when this << divisor1854return zeroValueOf(preferredScale);1855}18561857if (this.signum() == 0 && divisor.signum() != 0)1858return this.setScale(preferredScale, ROUND_UNNECESSARY);18591860// Perform a divide with enough digits to round to a correct1861// integer value; then remove any fractional digits18621863int maxDigits = (int)Math.min(this.precision() +1864(long)Math.ceil(10.0*divisor.precision()/3.0) +1865Math.abs((long)this.scale() - divisor.scale()) + 2,1866Integer.MAX_VALUE);1867BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,1868RoundingMode.DOWN));1869if (quotient.scale > 0) {1870quotient = quotient.setScale(0, RoundingMode.DOWN);1871quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale);1872}18731874if (quotient.scale < preferredScale) {1875// pad with zeros if necessary1876quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);1877}18781879return quotient;1880}18811882/**1883* Returns a {@code BigDecimal} whose value is the integer part1884* of {@code (this / divisor)}. Since the integer part of the1885* exact quotient does not depend on the rounding mode, the1886* rounding mode does not affect the values returned by this1887* method. The preferred scale of the result is1888* {@code (this.scale() - divisor.scale())}. An1889* {@code ArithmeticException} is thrown if the integer part of1890* the exact quotient needs more than {@code mc.precision}1891* digits.1892*1893* @param divisor value by which this {@code BigDecimal} is to be divided.1894* @param mc the context to use.1895* @return The integer part of {@code this / divisor}.1896* @throws ArithmeticException if {@code divisor==0}1897* @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result1898* requires a precision of more than {@code mc.precision} digits.1899* @since 1.51900* @author Joseph D. Darcy1901*/1902public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {1903if (mc.precision == 0 || // exact result1904(this.compareMagnitude(divisor) < 0)) // zero result1905return divideToIntegralValue(divisor);19061907// Calculate preferred scale1908int preferredScale = saturateLong((long)this.scale - divisor.scale);19091910/*1911* Perform a normal divide to mc.precision digits. If the1912* remainder has absolute value less than the divisor, the1913* integer portion of the quotient fits into mc.precision1914* digits. Next, remove any fractional digits from the1915* quotient and adjust the scale to the preferred value.1916*/1917BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));19181919if (result.scale() < 0) {1920/*1921* Result is an integer. See if quotient represents the1922* full integer portion of the exact quotient; if it does,1923* the computed remainder will be less than the divisor.1924*/1925BigDecimal product = result.multiply(divisor);1926// If the quotient is the full integer value,1927// |dividend-product| < |divisor|.1928if (this.subtract(product).compareMagnitude(divisor) >= 0) {1929throw new ArithmeticException("Division impossible");1930}1931} else if (result.scale() > 0) {1932/*1933* Integer portion of quotient will fit into precision1934* digits; recompute quotient to scale 0 to avoid double1935* rounding and then try to adjust, if necessary.1936*/1937result = result.setScale(0, RoundingMode.DOWN);1938}1939// else result.scale() == 0;19401941int precisionDiff;1942if ((preferredScale > result.scale()) &&1943(precisionDiff = mc.precision - result.precision()) > 0) {1944return result.setScale(result.scale() +1945Math.min(precisionDiff, preferredScale - result.scale) );1946} else {1947return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);1948}1949}19501951/**1952* Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.1953*1954* <p>The remainder is given by1955* {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.1956* Note that this is <em>not</em> the modulo operation (the result can be1957* negative).1958*1959* @param divisor value by which this {@code BigDecimal} is to be divided.1960* @return {@code this % divisor}.1961* @throws ArithmeticException if {@code divisor==0}1962* @since 1.51963*/1964public BigDecimal remainder(BigDecimal divisor) {1965BigDecimal divrem[] = this.divideAndRemainder(divisor);1966return divrem[1];1967}196819691970/**1971* Returns a {@code BigDecimal} whose value is {@code (this %1972* divisor)}, with rounding according to the context settings.1973* The {@code MathContext} settings affect the implicit divide1974* used to compute the remainder. The remainder computation1975* itself is by definition exact. Therefore, the remainder may1976* contain more than {@code mc.getPrecision()} digits.1977*1978* <p>The remainder is given by1979* {@code this.subtract(this.divideToIntegralValue(divisor,1980* mc).multiply(divisor))}. Note that this is not the modulo1981* operation (the result can be negative).1982*1983* @param divisor value by which this {@code BigDecimal} is to be divided.1984* @param mc the context to use.1985* @return {@code this % divisor}, rounded as necessary.1986* @throws ArithmeticException if {@code divisor==0}1987* @throws ArithmeticException if the result is inexact but the1988* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}1989* {@literal >} 0 and the result of {@code this.divideToIntegralValue(divisor)} would1990* require a precision of more than {@code mc.precision} digits.1991* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)1992* @since 1.51993*/1994public BigDecimal remainder(BigDecimal divisor, MathContext mc) {1995BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);1996return divrem[1];1997}19981999/**2000* Returns a two-element {@code BigDecimal} array containing the2001* result of {@code divideToIntegralValue} followed by the result of2002* {@code remainder} on the two operands.2003*2004* <p>Note that if both the integer quotient and remainder are2005* needed, this method is faster than using the2006* {@code divideToIntegralValue} and {@code remainder} methods2007* separately because the division need only be carried out once.2008*2009* @param divisor value by which this {@code BigDecimal} is to be divided,2010* and the remainder computed.2011* @return a two element {@code BigDecimal} array: the quotient2012* (the result of {@code divideToIntegralValue}) is the initial element2013* and the remainder is the final element.2014* @throws ArithmeticException if {@code divisor==0}2015* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)2016* @see #remainder(java.math.BigDecimal, java.math.MathContext)2017* @since 1.52018*/2019public BigDecimal[] divideAndRemainder(BigDecimal divisor) {2020// we use the identity x = i * y + r to determine r2021BigDecimal[] result = new BigDecimal[2];20222023result[0] = this.divideToIntegralValue(divisor);2024result[1] = this.subtract(result[0].multiply(divisor));2025return result;2026}20272028/**2029* Returns a two-element {@code BigDecimal} array containing the2030* result of {@code divideToIntegralValue} followed by the result of2031* {@code remainder} on the two operands calculated with rounding2032* according to the context settings.2033*2034* <p>Note that if both the integer quotient and remainder are2035* needed, this method is faster than using the2036* {@code divideToIntegralValue} and {@code remainder} methods2037* separately because the division need only be carried out once.2038*2039* @param divisor value by which this {@code BigDecimal} is to be divided,2040* and the remainder computed.2041* @param mc the context to use.2042* @return a two element {@code BigDecimal} array: the quotient2043* (the result of {@code divideToIntegralValue}) is the2044* initial element and the remainder is the final element.2045* @throws ArithmeticException if {@code divisor==0}2046* @throws ArithmeticException if the result is inexact but the2047* rounding mode is {@code UNNECESSARY}, or {@code mc.precision}2048* {@literal >} 0 and the result of {@code this.divideToIntegralValue(divisor)} would2049* require a precision of more than {@code mc.precision} digits.2050* @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)2051* @see #remainder(java.math.BigDecimal, java.math.MathContext)2052* @since 1.52053*/2054public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {2055if (mc.precision == 0)2056return divideAndRemainder(divisor);20572058BigDecimal[] result = new BigDecimal[2];2059BigDecimal lhs = this;20602061result[0] = lhs.divideToIntegralValue(divisor, mc);2062result[1] = lhs.subtract(result[0].multiply(divisor));2063return result;2064}20652066/**2067* Returns an approximation to the square root of {@code this}2068* with rounding according to the context settings.2069*2070* <p>The preferred scale of the returned result is equal to2071* {@code this.scale()/2}. The value of the returned result is2072* always within one ulp of the exact decimal value for the2073* precision in question. If the rounding mode is {@link2074* RoundingMode#HALF_UP HALF_UP}, {@link RoundingMode#HALF_DOWN2075* HALF_DOWN}, or {@link RoundingMode#HALF_EVEN HALF_EVEN}, the2076* result is within one half an ulp of the exact decimal value.2077*2078* <p>Special case:2079* <ul>2080* <li> The square root of a number numerically equal to {@code2081* ZERO} is numerically equal to {@code ZERO} with a preferred2082* scale according to the general rule above. In particular, for2083* {@code ZERO}, {@code ZERO.sqrt(mc).equals(ZERO)} is true with2084* any {@code MathContext} as an argument.2085* </ul>2086*2087* @param mc the context to use.2088* @return the square root of {@code this}.2089* @throws ArithmeticException if {@code this} is less than zero.2090* @throws ArithmeticException if an exact result is requested2091* ({@code mc.getPrecision()==0}) and there is no finite decimal2092* expansion of the exact result2093* @throws ArithmeticException if2094* {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and2095* the exact result cannot fit in {@code mc.getPrecision()}2096* digits.2097* @see BigInteger#sqrt()2098* @since 92099*/2100public BigDecimal sqrt(MathContext mc) {2101int signum = signum();2102if (signum == 1) {2103/*2104* The following code draws on the algorithm presented in2105* "Properly Rounded Variable Precision Square Root," Hull and2106* Abrham, ACM Transactions on Mathematical Software, Vol 11,2107* No. 3, September 1985, Pages 229-237.2108*2109* The BigDecimal computational model differs from the one2110* presented in the paper in several ways: first BigDecimal2111* numbers aren't necessarily normalized, second many more2112* rounding modes are supported, including UNNECESSARY, and2113* exact results can be requested.2114*2115* The main steps of the algorithm below are as follows,2116* first argument reduce the value to the numerical range2117* [1, 10) using the following relations:2118*2119* x = y * 10 ^ exp2120* sqrt(x) = sqrt(y) * 10^(exp / 2) if exp is even2121* sqrt(x) = sqrt(y/10) * 10 ^((exp+1)/2) is exp is odd2122*2123* Then use Newton's iteration on the reduced value to compute2124* the numerical digits of the desired result.2125*2126* Finally, scale back to the desired exponent range and2127* perform any adjustment to get the preferred scale in the2128* representation.2129*/21302131// The code below favors relative simplicity over checking2132// for special cases that could run faster.21332134int preferredScale = this.scale()/2;2135BigDecimal zeroWithFinalPreferredScale = valueOf(0L, preferredScale);21362137// First phase of numerical normalization, strip trailing2138// zeros and check for even powers of 10.2139BigDecimal stripped = this.stripTrailingZeros();2140int strippedScale = stripped.scale();21412142// Numerically sqrt(10^2N) = 10^N2143if (stripped.isPowerOfTen() &&2144strippedScale % 2 == 0) {2145BigDecimal result = valueOf(1L, strippedScale/2);2146if (result.scale() != preferredScale) {2147// Adjust to requested precision and preferred2148// scale as appropriate.2149result = result.add(zeroWithFinalPreferredScale, mc);2150}2151return result;2152}21532154// After stripTrailingZeros, the representation is normalized as2155//2156// unscaledValue * 10^(-scale)2157//2158// where unscaledValue is an integer with the mimimum2159// precision for the cohort of the numerical value. To2160// allow binary floating-point hardware to be used to get2161// approximately a 15 digit approximation to the square2162// root, it is helpful to instead normalize this so that2163// the significand portion is to right of the decimal2164// point by roughly (scale() - precision() + 1).21652166// Now the precision / scale adjustment2167int scaleAdjust = 0;2168int scale = stripped.scale() - stripped.precision() + 1;2169if (scale % 2 == 0) {2170scaleAdjust = scale;2171} else {2172scaleAdjust = scale - 1;2173}21742175BigDecimal working = stripped.scaleByPowerOfTen(scaleAdjust);21762177assert // Verify 0.1 <= working < 102178ONE_TENTH.compareTo(working) <= 0 && working.compareTo(TEN) < 0;21792180// Use good ole' Math.sqrt to get the initial guess for2181// the Newton iteration, good to at least 15 decimal2182// digits. This approach does incur the cost of a2183//2184// BigDecimal -> double -> BigDecimal2185//2186// conversion cycle, but it avoids the need for several2187// Newton iterations in BigDecimal arithmetic to get the2188// working answer to 15 digits of precision. If many fewer2189// than 15 digits were needed, it might be faster to do2190// the loop entirely in BigDecimal arithmetic.2191//2192// (A double value might have as many as 17 decimal2193// digits of precision; it depends on the relative density2194// of binary and decimal numbers at different regions of2195// the number line.)2196//2197// (It would be possible to check for certain special2198// cases to avoid doing any Newton iterations. For2199// example, if the BigDecimal -> double conversion was2200// known to be exact and the rounding mode had a2201// low-enough precision, the post-Newton rounding logic2202// could be applied directly.)22032204BigDecimal guess = new BigDecimal(Math.sqrt(working.doubleValue()));2205int guessPrecision = 15;2206int originalPrecision = mc.getPrecision();2207int targetPrecision;22082209// If an exact value is requested, it must only need about2210// half of the input digits to represent since multiplying2211// an N digit number by itself yield a 2N-1 digit or 2N2212// digit result.2213if (originalPrecision == 0) {2214targetPrecision = stripped.precision()/2 + 1;2215} else {2216/*2217* To avoid the need for post-Newton fix-up logic, in2218* the case of half-way rounding modes, double the2219* target precision so that the "2p + 2" property can2220* be relied on to accomplish the final rounding.2221*/2222switch (mc.getRoundingMode()) {2223case HALF_UP:2224case HALF_DOWN:2225case HALF_EVEN:2226targetPrecision = 2 * originalPrecision;2227if (targetPrecision < 0) // Overflow2228targetPrecision = Integer.MAX_VALUE - 2;2229break;22302231default:2232targetPrecision = originalPrecision;2233break;2234}2235}22362237// When setting the precision to use inside the Newton2238// iteration loop, take care to avoid the case where the2239// precision of the input exceeds the requested precision2240// and rounding the input value too soon.2241BigDecimal approx = guess;2242int workingPrecision = working.precision();2243do {2244int tmpPrecision = Math.max(Math.max(guessPrecision, targetPrecision + 2),2245workingPrecision);2246MathContext mcTmp = new MathContext(tmpPrecision, RoundingMode.HALF_EVEN);2247// approx = 0.5 * (approx + fraction / approx)2248approx = ONE_HALF.multiply(approx.add(working.divide(approx, mcTmp), mcTmp));2249guessPrecision *= 2;2250} while (guessPrecision < targetPrecision + 2);22512252BigDecimal result;2253RoundingMode targetRm = mc.getRoundingMode();2254if (targetRm == RoundingMode.UNNECESSARY || originalPrecision == 0) {2255RoundingMode tmpRm =2256(targetRm == RoundingMode.UNNECESSARY) ? RoundingMode.DOWN : targetRm;2257MathContext mcTmp = new MathContext(targetPrecision, tmpRm);2258result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mcTmp);22592260// If result*result != this numerically, the square2261// root isn't exact2262if (this.subtract(result.square()).compareTo(ZERO) != 0) {2263throw new ArithmeticException("Computed square root not exact.");2264}2265} else {2266result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mc);22672268switch (targetRm) {2269case DOWN:2270case FLOOR:2271// Check if too big2272if (result.square().compareTo(this) > 0) {2273BigDecimal ulp = result.ulp();2274// Adjust increment down in case of 1.0 = 10^02275// since the next smaller number is only 1/102276// as far way as the next larger at exponent2277// boundaries. Test approx and *not* result to2278// avoid having to detect an arbitrary power2279// of ten.2280if (approx.compareTo(ONE) == 0) {2281ulp = ulp.multiply(ONE_TENTH);2282}2283result = result.subtract(ulp);2284}2285break;22862287case UP:2288case CEILING:2289// Check if too small2290if (result.square().compareTo(this) < 0) {2291result = result.add(result.ulp());2292}2293break;22942295default:2296// No additional work, rely on "2p + 2" property2297// for correct rounding. Alternatively, could2298// instead run the Newton iteration to around p2299// digits and then do tests and fix-ups on the2300// rounded value. One possible set of tests and2301// fix-ups is given in the Hull and Abrham paper;2302// however, additional half-way cases can occur2303// for BigDecimal given the more varied2304// combinations of input and output precisions2305// supported.2306break;2307}23082309}23102311// Test numerical properties at full precision before any2312// scale adjustments.2313assert squareRootResultAssertions(result, mc);2314if (result.scale() != preferredScale) {2315// The preferred scale of an add is2316// max(addend.scale(), augend.scale()). Therefore, if2317// the scale of the result is first minimized using2318// stripTrailingZeros(), adding a zero of the2319// preferred scale rounding to the correct precision2320// will perform the proper scale vs precision2321// tradeoffs.2322result = result.stripTrailingZeros().2323add(zeroWithFinalPreferredScale,2324new MathContext(originalPrecision, RoundingMode.UNNECESSARY));2325}2326return result;2327} else {2328BigDecimal result = null;2329switch (signum) {2330case -1:2331throw new ArithmeticException("Attempted square root " +2332"of negative BigDecimal");2333case 0:2334result = valueOf(0L, scale()/2);2335assert squareRootResultAssertions(result, mc);2336return result;23372338default:2339throw new AssertionError("Bad value from signum");2340}2341}2342}23432344private BigDecimal square() {2345return this.multiply(this);2346}23472348private boolean isPowerOfTen() {2349return BigInteger.ONE.equals(this.unscaledValue());2350}23512352/**2353* For nonzero values, check numerical correctness properties of2354* the computed result for the chosen rounding mode.2355*2356* For the directed rounding modes:2357*2358* <ul>2359*2360* <li> For DOWN and FLOOR, result^2 must be {@code <=} the input2361* and (result+ulp)^2 must be {@code >} the input.2362*2363* <li>Conversely, for UP and CEIL, result^2 must be {@code >=}2364* the input and (result-ulp)^2 must be {@code <} the input.2365* </ul>2366*/2367private boolean squareRootResultAssertions(BigDecimal result, MathContext mc) {2368if (result.signum() == 0) {2369return squareRootZeroResultAssertions(result, mc);2370} else {2371RoundingMode rm = mc.getRoundingMode();2372BigDecimal ulp = result.ulp();2373BigDecimal neighborUp = result.add(ulp);2374// Make neighbor down accurate even for powers of ten2375if (result.isPowerOfTen()) {2376ulp = ulp.divide(TEN);2377}2378BigDecimal neighborDown = result.subtract(ulp);23792380// Both the starting value and result should be nonzero and positive.2381assert (result.signum() == 1 &&2382this.signum() == 1) :2383"Bad signum of this and/or its sqrt.";23842385switch (rm) {2386case DOWN:2387case FLOOR:2388assert2389result.square().compareTo(this) <= 0 &&2390neighborUp.square().compareTo(this) > 0:2391"Square of result out for bounds rounding " + rm;2392return true;23932394case UP:2395case CEILING:2396assert2397result.square().compareTo(this) >= 0 &&2398neighborDown.square().compareTo(this) < 0:2399"Square of result out for bounds rounding " + rm;2400return true;240124022403case HALF_DOWN:2404case HALF_EVEN:2405case HALF_UP:2406BigDecimal err = result.square().subtract(this).abs();2407BigDecimal errUp = neighborUp.square().subtract(this);2408BigDecimal errDown = this.subtract(neighborDown.square());2409// All error values should be positive so don't need to2410// compare absolute values.24112412int err_comp_errUp = err.compareTo(errUp);2413int err_comp_errDown = err.compareTo(errDown);24142415assert2416errUp.signum() == 1 &&2417errDown.signum() == 1 :2418"Errors of neighbors squared don't have correct signs";24192420// For breaking a half-way tie, the return value may2421// have a larger error than one of the neighbors. For2422// example, the square root of 2.25 to a precision of2423// 1 digit is either 1 or 2 depending on how the exact2424// value of 1.5 is rounded. If 2 is returned, it will2425// have a larger rounding error than its neighbor 1.2426assert2427err_comp_errUp <= 0 ||2428err_comp_errDown <= 0 :2429"Computed square root has larger error than neighbors for " + rm;24302431assert2432((err_comp_errUp == 0 ) ? err_comp_errDown < 0 : true) &&2433((err_comp_errDown == 0 ) ? err_comp_errUp < 0 : true) :2434"Incorrect error relationships";2435// && could check for digit conditions for ties too2436return true;24372438default: // Definition of UNNECESSARY already verified.2439return true;2440}2441}2442}24432444private boolean squareRootZeroResultAssertions(BigDecimal result, MathContext mc) {2445return this.compareTo(ZERO) == 0;2446}24472448/**2449* Returns a {@code BigDecimal} whose value is2450* <code>(this<sup>n</sup>)</code>, The power is computed exactly, to2451* unlimited precision.2452*2453* <p>The parameter {@code n} must be in the range 0 through2454* 999999999, inclusive. {@code ZERO.pow(0)} returns {@link2455* #ONE}.2456*2457* Note that future releases may expand the allowable exponent2458* range of this method.2459*2460* @param n power to raise this {@code BigDecimal} to.2461* @return <code>this<sup>n</sup></code>2462* @throws ArithmeticException if {@code n} is out of range.2463* @since 1.52464*/2465public BigDecimal pow(int n) {2466if (n < 0 || n > 999999999)2467throw new ArithmeticException("Invalid operation");2468// No need to calculate pow(n) if result will over/underflow.2469// Don't attempt to support "supernormal" numbers.2470int newScale = checkScale((long)scale * n);2471return new BigDecimal(this.inflated().pow(n), newScale);2472}247324742475/**2476* Returns a {@code BigDecimal} whose value is2477* <code>(this<sup>n</sup>)</code>. The current implementation uses2478* the core algorithm defined in ANSI standard X3.274-1996 with2479* rounding according to the context settings. In general, the2480* returned numerical value is within two ulps of the exact2481* numerical value for the chosen precision. Note that future2482* releases may use a different algorithm with a decreased2483* allowable error bound and increased allowable exponent range.2484*2485* <p>The X3.274-1996 algorithm is:2486*2487* <ul>2488* <li> An {@code ArithmeticException} exception is thrown if2489* <ul>2490* <li>{@code abs(n) > 999999999}2491* <li>{@code mc.precision == 0} and {@code n < 0}2492* <li>{@code mc.precision > 0} and {@code n} has more than2493* {@code mc.precision} decimal digits2494* </ul>2495*2496* <li> if {@code n} is zero, {@link #ONE} is returned even if2497* {@code this} is zero, otherwise2498* <ul>2499* <li> if {@code n} is positive, the result is calculated via2500* the repeated squaring technique into a single accumulator.2501* The individual multiplications with the accumulator use the2502* same math context settings as in {@code mc} except for a2503* precision increased to {@code mc.precision + elength + 1}2504* where {@code elength} is the number of decimal digits in2505* {@code n}.2506*2507* <li> if {@code n} is negative, the result is calculated as if2508* {@code n} were positive; this value is then divided into one2509* using the working precision specified above.2510*2511* <li> The final value from either the positive or negative case2512* is then rounded to the destination precision.2513* </ul>2514* </ul>2515*2516* @param n power to raise this {@code BigDecimal} to.2517* @param mc the context to use.2518* @return <code>this<sup>n</sup></code> using the ANSI standard X3.274-19962519* algorithm2520* @throws ArithmeticException if the result is inexact but the2521* rounding mode is {@code UNNECESSARY}, or {@code n} is out2522* of range.2523* @since 1.52524*/2525public BigDecimal pow(int n, MathContext mc) {2526if (mc.precision == 0)2527return pow(n);2528if (n < -999999999 || n > 999999999)2529throw new ArithmeticException("Invalid operation");2530if (n == 0)2531return ONE; // x**0 == 1 in X3.2742532BigDecimal lhs = this;2533MathContext workmc = mc; // working settings2534int mag = Math.abs(n); // magnitude of n2535if (mc.precision > 0) {2536int elength = longDigitLength(mag); // length of n in digits2537if (elength > mc.precision) // X3.274 rule2538throw new ArithmeticException("Invalid operation");2539workmc = new MathContext(mc.precision + elength + 1,2540mc.roundingMode);2541}2542// ready to carry out power calculation...2543BigDecimal acc = ONE; // accumulator2544boolean seenbit = false; // set once we've seen a 1-bit2545for (int i=1;;i++) { // for each bit [top bit ignored]2546mag += mag; // shift left 1 bit2547if (mag < 0) { // top bit is set2548seenbit = true; // OK, we're off2549acc = acc.multiply(lhs, workmc); // acc=acc*x2550}2551if (i == 31)2552break; // that was the last bit2553if (seenbit)2554acc=acc.multiply(acc, workmc); // acc=acc*acc [square]2555// else (!seenbit) no point in squaring ONE2556}2557// if negative n, calculate the reciprocal using working precision2558if (n < 0) // [hence mc.precision>0]2559acc=ONE.divide(acc, workmc);2560// round to final precision and strip zeros2561return doRound(acc, mc);2562}25632564/**2565* Returns a {@code BigDecimal} whose value is the absolute value2566* of this {@code BigDecimal}, and whose scale is2567* {@code this.scale()}.2568*2569* @return {@code abs(this)}2570*/2571public BigDecimal abs() {2572return (signum() < 0 ? negate() : this);2573}25742575/**2576* Returns a {@code BigDecimal} whose value is the absolute value2577* of this {@code BigDecimal}, with rounding according to the2578* context settings.2579*2580* @param mc the context to use.2581* @return {@code abs(this)}, rounded as necessary.2582* @since 1.52583*/2584public BigDecimal abs(MathContext mc) {2585return (signum() < 0 ? negate(mc) : plus(mc));2586}25872588/**2589* Returns a {@code BigDecimal} whose value is {@code (-this)},2590* and whose scale is {@code this.scale()}.2591*2592* @return {@code -this}.2593*/2594public BigDecimal negate() {2595if (intCompact == INFLATED) {2596return new BigDecimal(intVal.negate(), INFLATED, scale, precision);2597} else {2598return valueOf(-intCompact, scale, precision);2599}2600}26012602/**2603* Returns a {@code BigDecimal} whose value is {@code (-this)},2604* with rounding according to the context settings.2605*2606* @param mc the context to use.2607* @return {@code -this}, rounded as necessary.2608* @since 1.52609*/2610public BigDecimal negate(MathContext mc) {2611return negate().plus(mc);2612}26132614/**2615* Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose2616* scale is {@code this.scale()}.2617*2618* <p>This method, which simply returns this {@code BigDecimal}2619* is included for symmetry with the unary minus method {@link2620* #negate()}.2621*2622* @return {@code this}.2623* @see #negate()2624* @since 1.52625*/2626public BigDecimal plus() {2627return this;2628}26292630/**2631* Returns a {@code BigDecimal} whose value is {@code (+this)},2632* with rounding according to the context settings.2633*2634* <p>The effect of this method is identical to that of the {@link2635* #round(MathContext)} method.2636*2637* @param mc the context to use.2638* @return {@code this}, rounded as necessary. A zero result will2639* have a scale of 0.2640* @see #round(MathContext)2641* @since 1.52642*/2643public BigDecimal plus(MathContext mc) {2644if (mc.precision == 0) // no rounding please2645return this;2646return doRound(this, mc);2647}26482649/**2650* Returns the signum function of this {@code BigDecimal}.2651*2652* @return -1, 0, or 1 as the value of this {@code BigDecimal}2653* is negative, zero, or positive.2654*/2655public int signum() {2656return (intCompact != INFLATED)?2657Long.signum(intCompact):2658intVal.signum();2659}26602661/**2662* Returns the <i>scale</i> of this {@code BigDecimal}. If zero2663* or positive, the scale is the number of digits to the right of2664* the decimal point. If negative, the unscaled value of the2665* number is multiplied by ten to the power of the negation of the2666* scale. For example, a scale of {@code -3} means the unscaled2667* value is multiplied by 1000.2668*2669* @return the scale of this {@code BigDecimal}.2670*/2671public int scale() {2672return scale;2673}26742675/**2676* Returns the <i>precision</i> of this {@code BigDecimal}. (The2677* precision is the number of digits in the unscaled value.)2678*2679* <p>The precision of a zero value is 1.2680*2681* @return the precision of this {@code BigDecimal}.2682* @since 1.52683*/2684public int precision() {2685int result = precision;2686if (result == 0) {2687long s = intCompact;2688if (s != INFLATED)2689result = longDigitLength(s);2690else2691result = bigDigitLength(intVal);2692precision = result;2693}2694return result;2695}269626972698/**2699* Returns a {@code BigInteger} whose value is the <i>unscaled2700* value</i> of this {@code BigDecimal}. (Computes <code>(this *2701* 10<sup>this.scale()</sup>)</code>.)2702*2703* @return the unscaled value of this {@code BigDecimal}.2704* @since 1.22705*/2706public BigInteger unscaledValue() {2707return this.inflated();2708}27092710// Rounding Modes27112712/**2713* Rounding mode to round away from zero. Always increments the2714* digit prior to a nonzero discarded fraction. Note that this rounding2715* mode never decreases the magnitude of the calculated value.2716*2717* @deprecated Use {@link RoundingMode#UP} instead.2718*/2719@Deprecated(since="9")2720public static final int ROUND_UP = 0;27212722/**2723* Rounding mode to round towards zero. Never increments the digit2724* prior to a discarded fraction (i.e., truncates). Note that this2725* rounding mode never increases the magnitude of the calculated value.2726*2727* @deprecated Use {@link RoundingMode#DOWN} instead.2728*/2729@Deprecated(since="9")2730public static final int ROUND_DOWN = 1;27312732/**2733* Rounding mode to round towards positive infinity. If the2734* {@code BigDecimal} is positive, behaves as for2735* {@code ROUND_UP}; if negative, behaves as for2736* {@code ROUND_DOWN}. Note that this rounding mode never2737* decreases the calculated value.2738*2739* @deprecated Use {@link RoundingMode#CEILING} instead.2740*/2741@Deprecated(since="9")2742public static final int ROUND_CEILING = 2;27432744/**2745* Rounding mode to round towards negative infinity. If the2746* {@code BigDecimal} is positive, behave as for2747* {@code ROUND_DOWN}; if negative, behave as for2748* {@code ROUND_UP}. Note that this rounding mode never2749* increases the calculated value.2750*2751* @deprecated Use {@link RoundingMode#FLOOR} instead.2752*/2753@Deprecated(since="9")2754public static final int ROUND_FLOOR = 3;27552756/**2757* Rounding mode to round towards {@literal "nearest neighbor"}2758* unless both neighbors are equidistant, in which case round up.2759* Behaves as for {@code ROUND_UP} if the discarded fraction is2760* ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note2761* that this is the rounding mode that most of us were taught in2762* grade school.2763*2764* @deprecated Use {@link RoundingMode#HALF_UP} instead.2765*/2766@Deprecated(since="9")2767public static final int ROUND_HALF_UP = 4;27682769/**2770* Rounding mode to round towards {@literal "nearest neighbor"}2771* unless both neighbors are equidistant, in which case round2772* down. Behaves as for {@code ROUND_UP} if the discarded2773* fraction is {@literal >} 0.5; otherwise, behaves as for2774* {@code ROUND_DOWN}.2775*2776* @deprecated Use {@link RoundingMode#HALF_DOWN} instead.2777*/2778@Deprecated(since="9")2779public static final int ROUND_HALF_DOWN = 5;27802781/**2782* Rounding mode to round towards the {@literal "nearest neighbor"}2783* unless both neighbors are equidistant, in which case, round2784* towards the even neighbor. Behaves as for2785* {@code ROUND_HALF_UP} if the digit to the left of the2786* discarded fraction is odd; behaves as for2787* {@code ROUND_HALF_DOWN} if it's even. Note that this is the2788* rounding mode that minimizes cumulative error when applied2789* repeatedly over a sequence of calculations.2790*2791* @deprecated Use {@link RoundingMode#HALF_EVEN} instead.2792*/2793@Deprecated(since="9")2794public static final int ROUND_HALF_EVEN = 6;27952796/**2797* Rounding mode to assert that the requested operation has an exact2798* result, hence no rounding is necessary. If this rounding mode is2799* specified on an operation that yields an inexact result, an2800* {@code ArithmeticException} is thrown.2801*2802* @deprecated Use {@link RoundingMode#UNNECESSARY} instead.2803*/2804@Deprecated(since="9")2805public static final int ROUND_UNNECESSARY = 7;280628072808// Scaling/Rounding Operations28092810/**2811* Returns a {@code BigDecimal} rounded according to the2812* {@code MathContext} settings. If the precision setting is 0 then2813* no rounding takes place.2814*2815* <p>The effect of this method is identical to that of the2816* {@link #plus(MathContext)} method.2817*2818* @param mc the context to use.2819* @return a {@code BigDecimal} rounded according to the2820* {@code MathContext} settings.2821* @see #plus(MathContext)2822* @since 1.52823*/2824public BigDecimal round(MathContext mc) {2825return plus(mc);2826}28272828/**2829* Returns a {@code BigDecimal} whose scale is the specified2830* value, and whose unscaled value is determined by multiplying or2831* dividing this {@code BigDecimal}'s unscaled value by the2832* appropriate power of ten to maintain its overall value. If the2833* scale is reduced by the operation, the unscaled value must be2834* divided (rather than multiplied), and the value may be changed;2835* in this case, the specified rounding mode is applied to the2836* division.2837*2838* @apiNote Since BigDecimal objects are immutable, calls of2839* this method do <em>not</em> result in the original object being2840* modified, contrary to the usual convention of having methods2841* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.2842* Instead, {@code setScale} returns an object with the proper2843* scale; the returned object may or may not be newly allocated.2844*2845* @param newScale scale of the {@code BigDecimal} value to be returned.2846* @param roundingMode The rounding mode to apply.2847* @return a {@code BigDecimal} whose scale is the specified value,2848* and whose unscaled value is determined by multiplying or2849* dividing this {@code BigDecimal}'s unscaled value by the2850* appropriate power of ten to maintain its overall value.2851* @throws ArithmeticException if {@code roundingMode==UNNECESSARY}2852* and the specified scaling operation would require2853* rounding.2854* @see RoundingMode2855* @since 1.52856*/2857public BigDecimal setScale(int newScale, RoundingMode roundingMode) {2858return setScale(newScale, roundingMode.oldMode);2859}28602861/**2862* Returns a {@code BigDecimal} whose scale is the specified2863* value, and whose unscaled value is determined by multiplying or2864* dividing this {@code BigDecimal}'s unscaled value by the2865* appropriate power of ten to maintain its overall value. If the2866* scale is reduced by the operation, the unscaled value must be2867* divided (rather than multiplied), and the value may be changed;2868* in this case, the specified rounding mode is applied to the2869* division.2870*2871* @apiNote Since BigDecimal objects are immutable, calls of2872* this method do <em>not</em> result in the original object being2873* modified, contrary to the usual convention of having methods2874* named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.2875* Instead, {@code setScale} returns an object with the proper2876* scale; the returned object may or may not be newly allocated.2877*2878* @deprecated The method {@link #setScale(int, RoundingMode)} should2879* be used in preference to this legacy method.2880*2881* @param newScale scale of the {@code BigDecimal} value to be returned.2882* @param roundingMode The rounding mode to apply.2883* @return a {@code BigDecimal} whose scale is the specified value,2884* and whose unscaled value is determined by multiplying or2885* dividing this {@code BigDecimal}'s unscaled value by the2886* appropriate power of ten to maintain its overall value.2887* @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}2888* and the specified scaling operation would require2889* rounding.2890* @throws IllegalArgumentException if {@code roundingMode} does not2891* represent a valid rounding mode.2892* @see #ROUND_UP2893* @see #ROUND_DOWN2894* @see #ROUND_CEILING2895* @see #ROUND_FLOOR2896* @see #ROUND_HALF_UP2897* @see #ROUND_HALF_DOWN2898* @see #ROUND_HALF_EVEN2899* @see #ROUND_UNNECESSARY2900*/2901@Deprecated(since="9")2902public BigDecimal setScale(int newScale, int roundingMode) {2903if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)2904throw new IllegalArgumentException("Invalid rounding mode");29052906int oldScale = this.scale;2907if (newScale == oldScale) // easy case2908return this;2909if (this.signum() == 0) // zero can have any scale2910return zeroValueOf(newScale);2911if(this.intCompact!=INFLATED) {2912long rs = this.intCompact;2913if (newScale > oldScale) {2914int raise = checkScale((long) newScale - oldScale);2915if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) {2916return valueOf(rs,newScale);2917}2918BigInteger rb = bigMultiplyPowerTen(raise);2919return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);2920} else {2921// newScale < oldScale -- drop some digits2922// Can't predict the precision due to the effect of rounding.2923int drop = checkScale((long) oldScale - newScale);2924if (drop < LONG_TEN_POWERS_TABLE.length) {2925return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale);2926} else {2927return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale);2928}2929}2930} else {2931if (newScale > oldScale) {2932int raise = checkScale((long) newScale - oldScale);2933BigInteger rb = bigMultiplyPowerTen(this.intVal,raise);2934return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0);2935} else {2936// newScale < oldScale -- drop some digits2937// Can't predict the precision due to the effect of rounding.2938int drop = checkScale((long) oldScale - newScale);2939if (drop < LONG_TEN_POWERS_TABLE.length)2940return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode,2941newScale);2942else2943return divideAndRound(this.intVal, bigTenToThe(drop), newScale, roundingMode, newScale);2944}2945}2946}29472948/**2949* Returns a {@code BigDecimal} whose scale is the specified2950* value, and whose value is numerically equal to this2951* {@code BigDecimal}'s. Throws an {@code ArithmeticException}2952* if this is not possible.2953*2954* <p>This call is typically used to increase the scale, in which2955* case it is guaranteed that there exists a {@code BigDecimal}2956* of the specified scale and the correct value. The call can2957* also be used to reduce the scale if the caller knows that the2958* {@code BigDecimal} has sufficiently many zeros at the end of2959* its fractional part (i.e., factors of ten in its integer value)2960* to allow for the rescaling without changing its value.2961*2962* <p>This method returns the same result as the two-argument2963* versions of {@code setScale}, but saves the caller the trouble2964* of specifying a rounding mode in cases where it is irrelevant.2965*2966* @apiNote Since {@code BigDecimal} objects are immutable,2967* calls of this method do <em>not</em> result in the original2968* object being modified, contrary to the usual convention of2969* having methods named <code>set<i>X</i></code> mutate field2970* <i>{@code X}</i>. Instead, {@code setScale} returns an2971* object with the proper scale; the returned object may or may2972* not be newly allocated.2973*2974* @param newScale scale of the {@code BigDecimal} value to be returned.2975* @return a {@code BigDecimal} whose scale is the specified value, and2976* whose unscaled value is determined by multiplying or dividing2977* this {@code BigDecimal}'s unscaled value by the appropriate2978* power of ten to maintain its overall value.2979* @throws ArithmeticException if the specified scaling operation would2980* require rounding.2981* @see #setScale(int, int)2982* @see #setScale(int, RoundingMode)2983*/2984public BigDecimal setScale(int newScale) {2985return setScale(newScale, ROUND_UNNECESSARY);2986}29872988// Decimal Point Motion Operations29892990/**2991* Returns a {@code BigDecimal} which is equivalent to this one2992* with the decimal point moved {@code n} places to the left. If2993* {@code n} is non-negative, the call merely adds {@code n} to2994* the scale. If {@code n} is negative, the call is equivalent2995* to {@code movePointRight(-n)}. The {@code BigDecimal}2996* returned by this call has value <code>(this ×2997* 10<sup>-n</sup>)</code> and scale {@code max(this.scale()+n,2998* 0)}.2999*3000* @param n number of places to move the decimal point to the left.3001* @return a {@code BigDecimal} which is equivalent to this one with the3002* decimal point moved {@code n} places to the left.3003* @throws ArithmeticException if scale overflows.3004*/3005public BigDecimal movePointLeft(int n) {3006if (n == 0) return this;30073008// Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE3009int newScale = checkScale((long)scale + n);3010BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);3011return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;3012}30133014/**3015* Returns a {@code BigDecimal} which is equivalent to this one3016* with the decimal point moved {@code n} places to the right.3017* If {@code n} is non-negative, the call merely subtracts3018* {@code n} from the scale. If {@code n} is negative, the call3019* is equivalent to {@code movePointLeft(-n)}. The3020* {@code BigDecimal} returned by this call has value <code>(this3021* × 10<sup>n</sup>)</code> and scale {@code max(this.scale()-n,3022* 0)}.3023*3024* @param n number of places to move the decimal point to the right.3025* @return a {@code BigDecimal} which is equivalent to this one3026* with the decimal point moved {@code n} places to the right.3027* @throws ArithmeticException if scale overflows.3028*/3029public BigDecimal movePointRight(int n) {3030if (n == 0) return this;30313032// Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE3033int newScale = checkScale((long)scale - n);3034BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);3035return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;3036}30373038/**3039* Returns a BigDecimal whose numerical value is equal to3040* ({@code this} * 10<sup>n</sup>). The scale of3041* the result is {@code (this.scale() - n)}.3042*3043* @param n the exponent power of ten to scale by3044* @return a BigDecimal whose numerical value is equal to3045* ({@code this} * 10<sup>n</sup>)3046* @throws ArithmeticException if the scale would be3047* outside the range of a 32-bit integer.3048*3049* @since 1.53050*/3051public BigDecimal scaleByPowerOfTen(int n) {3052return new BigDecimal(intVal, intCompact,3053checkScale((long)scale - n), precision);3054}30553056/**3057* Returns a {@code BigDecimal} which is numerically equal to3058* this one but with any trailing zeros removed from the3059* representation. For example, stripping the trailing zeros from3060* the {@code BigDecimal} value {@code 600.0}, which has3061* [{@code BigInteger}, {@code scale}] components equal to3062* [6000, 1], yields {@code 6E2} with [{@code BigInteger},3063* {@code scale}] components equal to [6, -2]. If3064* this BigDecimal is numerically equal to zero, then3065* {@code BigDecimal.ZERO} is returned.3066*3067* @return a numerically equal {@code BigDecimal} with any3068* trailing zeros removed.3069* @throws ArithmeticException if scale overflows.3070* @since 1.53071*/3072public BigDecimal stripTrailingZeros() {3073if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) {3074return BigDecimal.ZERO;3075} else if (intCompact != INFLATED) {3076return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE);3077} else {3078return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE);3079}3080}30813082// Comparison Operations30833084/**3085* Compares this {@code BigDecimal} numerically with the specified3086* {@code BigDecimal}. Two {@code BigDecimal} objects that are3087* equal in value but have a different scale (like 2.0 and 2.00)3088* are considered equal by this method. Such values are in the3089* same <i>cohort</i>.3090*3091* This method is provided in preference to individual methods for3092* each of the six boolean comparison operators ({@literal <}, ==,3093* {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested3094* idiom for performing these comparisons is: {@code3095* (x.compareTo(y)} <<i>op</i>> {@code 0)}, where3096* <<i>op</i>> is one of the six comparison operators.30973098* @apiNote3099* Note: this class has a natural ordering that is inconsistent with equals.3100*3101* @param val {@code BigDecimal} to which this {@code BigDecimal} is3102* to be compared.3103* @return -1, 0, or 1 as this {@code BigDecimal} is numerically3104* less than, equal to, or greater than {@code val}.3105*/3106@Override3107public int compareTo(BigDecimal val) {3108// Quick path for equal scale and non-inflated case.3109if (scale == val.scale) {3110long xs = intCompact;3111long ys = val.intCompact;3112if (xs != INFLATED && ys != INFLATED)3113return xs != ys ? ((xs > ys) ? 1 : -1) : 0;3114}3115int xsign = this.signum();3116int ysign = val.signum();3117if (xsign != ysign)3118return (xsign > ysign) ? 1 : -1;3119if (xsign == 0)3120return 0;3121int cmp = compareMagnitude(val);3122return (xsign > 0) ? cmp : -cmp;3123}31243125/**3126* Version of compareTo that ignores sign.3127*/3128private int compareMagnitude(BigDecimal val) {3129// Match scales, avoid unnecessary inflation3130long ys = val.intCompact;3131long xs = this.intCompact;3132if (xs == 0)3133return (ys == 0) ? 0 : -1;3134if (ys == 0)3135return 1;31363137long sdiff = (long)this.scale - val.scale;3138if (sdiff != 0) {3139// Avoid matching scales if the (adjusted) exponents differ3140long xae = (long)this.precision() - this.scale; // [-1]3141long yae = (long)val.precision() - val.scale; // [-1]3142if (xae < yae)3143return -1;3144if (xae > yae)3145return 1;3146if (sdiff < 0) {3147// The cases sdiff <= Integer.MIN_VALUE intentionally fall through.3148if ( sdiff > Integer.MIN_VALUE &&3149(xs == INFLATED ||3150(xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&3151ys == INFLATED) {3152BigInteger rb = bigMultiplyPowerTen((int)-sdiff);3153return rb.compareMagnitude(val.intVal);3154}3155} else { // sdiff > 03156// The cases sdiff > Integer.MAX_VALUE intentionally fall through.3157if ( sdiff <= Integer.MAX_VALUE &&3158(ys == INFLATED ||3159(ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&3160xs == INFLATED) {3161BigInteger rb = val.bigMultiplyPowerTen((int)sdiff);3162return this.intVal.compareMagnitude(rb);3163}3164}3165}3166if (xs != INFLATED)3167return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;3168else if (ys != INFLATED)3169return 1;3170else3171return this.intVal.compareMagnitude(val.intVal);3172}31733174/**3175* Compares this {@code BigDecimal} with the specified {@code3176* Object} for equality. Unlike {@link #compareTo(BigDecimal)3177* compareTo}, this method considers two {@code BigDecimal}3178* objects equal only if they are equal in value and3179* scale. Therefore 2.0 is not equal to 2.00 when compared by this3180* method since the former has [{@code BigInteger}, {@code scale}]3181* components equal to [20, 1] while the latter has components3182* equal to [200, 2].3183*3184* @apiNote3185* One example that shows how 2.0 and 2.00 are <em>not</em>3186* substitutable for each other under some arithmetic operations3187* are the two expressions:<br>3188* {@code new BigDecimal("2.0" ).divide(BigDecimal.valueOf(3),3189* HALF_UP)} which evaluates to 0.7 and <br>3190* {@code new BigDecimal("2.00").divide(BigDecimal.valueOf(3),3191* HALF_UP)} which evaluates to 0.67.3192*3193* @param x {@code Object} to which this {@code BigDecimal} is3194* to be compared.3195* @return {@code true} if and only if the specified {@code Object} is a3196* {@code BigDecimal} whose value and scale are equal to this3197* {@code BigDecimal}'s.3198* @see #compareTo(java.math.BigDecimal)3199* @see #hashCode3200*/3201@Override3202public boolean equals(Object x) {3203if (!(x instanceof BigDecimal xDec))3204return false;3205if (x == this)3206return true;3207if (scale != xDec.scale)3208return false;3209long s = this.intCompact;3210long xs = xDec.intCompact;3211if (s != INFLATED) {3212if (xs == INFLATED)3213xs = compactValFor(xDec.intVal);3214return xs == s;3215} else if (xs != INFLATED)3216return xs == compactValFor(this.intVal);32173218return this.inflated().equals(xDec.inflated());3219}32203221/**3222* Returns the minimum of this {@code BigDecimal} and3223* {@code val}.3224*3225* @param val value with which the minimum is to be computed.3226* @return the {@code BigDecimal} whose value is the lesser of this3227* {@code BigDecimal} and {@code val}. If they are equal,3228* as defined by the {@link #compareTo(BigDecimal) compareTo}3229* method, {@code this} is returned.3230* @see #compareTo(java.math.BigDecimal)3231*/3232public BigDecimal min(BigDecimal val) {3233return (compareTo(val) <= 0 ? this : val);3234}32353236/**3237* Returns the maximum of this {@code BigDecimal} and {@code val}.3238*3239* @param val value with which the maximum is to be computed.3240* @return the {@code BigDecimal} whose value is the greater of this3241* {@code BigDecimal} and {@code val}. If they are equal,3242* as defined by the {@link #compareTo(BigDecimal) compareTo}3243* method, {@code this} is returned.3244* @see #compareTo(java.math.BigDecimal)3245*/3246public BigDecimal max(BigDecimal val) {3247return (compareTo(val) >= 0 ? this : val);3248}32493250// Hash Function32513252/**3253* Returns the hash code for this {@code BigDecimal}.3254* The hash code is computed as a function of the {@linkplain3255* unscaledValue() unscaled value} and the {@linkplain scale()3256* scale} of this {@code BigDecimal}.3257*3258* @apiNote3259* Two {@code BigDecimal} objects that are numerically equal but3260* differ in scale (like 2.0 and 2.00) will generally <em>not</em>3261* have the same hash code.3262*3263* @return hash code for this {@code BigDecimal}.3264* @see #equals(Object)3265*/3266@Override3267public int hashCode() {3268if (intCompact != INFLATED) {3269long val2 = (intCompact < 0)? -intCompact : intCompact;3270int temp = (int)( ((int)(val2 >>> 32)) * 31 +3271(val2 & LONG_MASK));3272return 31*((intCompact < 0) ?-temp:temp) + scale;3273} else3274return 31*intVal.hashCode() + scale;3275}32763277// Format Converters32783279/**3280* Returns the string representation of this {@code BigDecimal},3281* using scientific notation if an exponent is needed.3282*3283* <p>A standard canonical string form of the {@code BigDecimal}3284* is created as though by the following steps: first, the3285* absolute value of the unscaled value of the {@code BigDecimal}3286* is converted to a string in base ten using the characters3287* {@code '0'} through {@code '9'} with no leading zeros (except3288* if its value is zero, in which case a single {@code '0'}3289* character is used).3290*3291* <p>Next, an <i>adjusted exponent</i> is calculated; this is the3292* negated scale, plus the number of characters in the converted3293* unscaled value, less one. That is,3294* {@code -scale+(ulength-1)}, where {@code ulength} is the3295* length of the absolute value of the unscaled value in decimal3296* digits (its <i>precision</i>).3297*3298* <p>If the scale is greater than or equal to zero and the3299* adjusted exponent is greater than or equal to {@code -6}, the3300* number will be converted to a character form without using3301* exponential notation. In this case, if the scale is zero then3302* no decimal point is added and if the scale is positive a3303* decimal point will be inserted with the scale specifying the3304* number of characters to the right of the decimal point.3305* {@code '0'} characters are added to the left of the converted3306* unscaled value as necessary. If no character precedes the3307* decimal point after this insertion then a conventional3308* {@code '0'} character is prefixed.3309*3310* <p>Otherwise (that is, if the scale is negative, or the3311* adjusted exponent is less than {@code -6}), the number will be3312* converted to a character form using exponential notation. In3313* this case, if the converted {@code BigInteger} has more than3314* one digit a decimal point is inserted after the first digit.3315* An exponent in character form is then suffixed to the converted3316* unscaled value (perhaps with inserted decimal point); this3317* comprises the letter {@code 'E'} followed immediately by the3318* adjusted exponent converted to a character form. The latter is3319* in base ten, using the characters {@code '0'} through3320* {@code '9'} with no leading zeros, and is always prefixed by a3321* sign character {@code '-'} (<code>'\u002D'</code>) if the3322* adjusted exponent is negative, {@code '+'}3323* (<code>'\u002B'</code>) otherwise).3324*3325* <p>Finally, the entire string is prefixed by a minus sign3326* character {@code '-'} (<code>'\u002D'</code>) if the unscaled3327* value is less than zero. No sign character is prefixed if the3328* unscaled value is zero or positive.3329*3330* <p><b>Examples:</b>3331* <p>For each representation [<i>unscaled value</i>, <i>scale</i>]3332* on the left, the resulting string is shown on the right.3333* <pre>3334* [123,0] "123"3335* [-123,0] "-123"3336* [123,-1] "1.23E+3"3337* [123,-3] "1.23E+5"3338* [123,1] "12.3"3339* [123,5] "0.00123"3340* [123,10] "1.23E-8"3341* [-123,12] "-1.23E-10"3342* </pre>3343*3344* <b>Notes:</b>3345* <ol>3346*3347* <li>There is a one-to-one mapping between the distinguishable3348* {@code BigDecimal} values and the result of this conversion.3349* That is, every distinguishable {@code BigDecimal} value3350* (unscaled value and scale) has a unique string representation3351* as a result of using {@code toString}. If that string3352* representation is converted back to a {@code BigDecimal} using3353* the {@link #BigDecimal(String)} constructor, then the original3354* value will be recovered.3355*3356* <li>The string produced for a given number is always the same;3357* it is not affected by locale. This means that it can be used3358* as a canonical string representation for exchanging decimal3359* data, or as a key for a Hashtable, etc. Locale-sensitive3360* number formatting and parsing is handled by the {@link3361* java.text.NumberFormat} class and its subclasses.3362*3363* <li>The {@link #toEngineeringString} method may be used for3364* presenting numbers with exponents in engineering notation, and the3365* {@link #setScale(int,RoundingMode) setScale} method may be used for3366* rounding a {@code BigDecimal} so it has a known number of digits after3367* the decimal point.3368*3369* <li>The digit-to-character mapping provided by3370* {@code Character.forDigit} is used.3371*3372* </ol>3373*3374* @return string representation of this {@code BigDecimal}.3375* @see Character#forDigit3376* @see #BigDecimal(java.lang.String)3377*/3378@Override3379public String toString() {3380String sc = stringCache;3381if (sc == null) {3382stringCache = sc = layoutChars(true);3383}3384return sc;3385}33863387/**3388* Returns a string representation of this {@code BigDecimal},3389* using engineering notation if an exponent is needed.3390*3391* <p>Returns a string that represents the {@code BigDecimal} as3392* described in the {@link #toString()} method, except that if3393* exponential notation is used, the power of ten is adjusted to3394* be a multiple of three (engineering notation) such that the3395* integer part of nonzero values will be in the range 1 through3396* 999. If exponential notation is used for zero values, a3397* decimal point and one or two fractional zero digits are used so3398* that the scale of the zero value is preserved. Note that3399* unlike the output of {@link #toString()}, the output of this3400* method is <em>not</em> guaranteed to recover the same [integer,3401* scale] pair of this {@code BigDecimal} if the output string is3402* converting back to a {@code BigDecimal} using the {@linkplain3403* #BigDecimal(String) string constructor}. The result of this method meets3404* the weaker constraint of always producing a numerically equal3405* result from applying the string constructor to the method's output.3406*3407* @return string representation of this {@code BigDecimal}, using3408* engineering notation if an exponent is needed.3409* @since 1.53410*/3411public String toEngineeringString() {3412return layoutChars(false);3413}34143415/**3416* Returns a string representation of this {@code BigDecimal}3417* without an exponent field. For values with a positive scale,3418* the number of digits to the right of the decimal point is used3419* to indicate scale. For values with a zero or negative scale,3420* the resulting string is generated as if the value were3421* converted to a numerically equal value with zero scale and as3422* if all the trailing zeros of the zero scale value were present3423* in the result.3424*3425* The entire string is prefixed by a minus sign character '-'3426* (<code>'\u002D'</code>) if the unscaled value is less than3427* zero. No sign character is prefixed if the unscaled value is3428* zero or positive.3429*3430* Note that if the result of this method is passed to the3431* {@linkplain #BigDecimal(String) string constructor}, only the3432* numerical value of this {@code BigDecimal} will necessarily be3433* recovered; the representation of the new {@code BigDecimal}3434* may have a different scale. In particular, if this3435* {@code BigDecimal} has a negative scale, the string resulting3436* from this method will have a scale of zero when processed by3437* the string constructor.3438*3439* (This method behaves analogously to the {@code toString}3440* method in 1.4 and earlier releases.)3441*3442* @return a string representation of this {@code BigDecimal}3443* without an exponent field.3444* @since 1.53445* @see #toString()3446* @see #toEngineeringString()3447*/3448public String toPlainString() {3449if(scale==0) {3450if(intCompact!=INFLATED) {3451return Long.toString(intCompact);3452} else {3453return intVal.toString();3454}3455}3456if(this.scale<0) { // No decimal point3457if(signum()==0) {3458return "0";3459}3460int trailingZeros = checkScaleNonZero((-(long)scale));3461StringBuilder buf;3462if(intCompact!=INFLATED) {3463buf = new StringBuilder(20+trailingZeros);3464buf.append(intCompact);3465} else {3466String str = intVal.toString();3467buf = new StringBuilder(str.length()+trailingZeros);3468buf.append(str);3469}3470for (int i = 0; i < trailingZeros; i++) {3471buf.append('0');3472}3473return buf.toString();3474}3475String str ;3476if(intCompact!=INFLATED) {3477str = Long.toString(Math.abs(intCompact));3478} else {3479str = intVal.abs().toString();3480}3481return getValueString(signum(), str, scale);3482}34833484/* Returns a digit.digit string */3485private String getValueString(int signum, String intString, int scale) {3486/* Insert decimal point */3487StringBuilder buf;3488int insertionPoint = intString.length() - scale;3489if (insertionPoint == 0) { /* Point goes right before intVal */3490return (signum<0 ? "-0." : "0.") + intString;3491} else if (insertionPoint > 0) { /* Point goes inside intVal */3492buf = new StringBuilder(intString);3493buf.insert(insertionPoint, '.');3494if (signum < 0)3495buf.insert(0, '-');3496} else { /* We must insert zeros between point and intVal */3497buf = new StringBuilder(3-insertionPoint + intString.length());3498buf.append(signum<0 ? "-0." : "0.");3499for (int i=0; i<-insertionPoint; i++) {3500buf.append('0');3501}3502buf.append(intString);3503}3504return buf.toString();3505}35063507/**3508* Converts this {@code BigDecimal} to a {@code BigInteger}.3509* This conversion is analogous to the3510* <i>narrowing primitive conversion</i> from {@code double} to3511* {@code long} as defined in3512* <cite>The Java Language Specification</cite>:3513* any fractional part of this3514* {@code BigDecimal} will be discarded. Note that this3515* conversion can lose information about the precision of the3516* {@code BigDecimal} value.3517* <p>3518* To have an exception thrown if the conversion is inexact (in3519* other words if a nonzero fractional part is discarded), use the3520* {@link #toBigIntegerExact()} method.3521*3522* @return this {@code BigDecimal} converted to a {@code BigInteger}.3523* @jls 5.1.3 Narrowing Primitive Conversion3524*/3525public BigInteger toBigInteger() {3526// force to an integer, quietly3527return this.setScale(0, ROUND_DOWN).inflated();3528}35293530/**3531* Converts this {@code BigDecimal} to a {@code BigInteger},3532* checking for lost information. An exception is thrown if this3533* {@code BigDecimal} has a nonzero fractional part.3534*3535* @return this {@code BigDecimal} converted to a {@code BigInteger}.3536* @throws ArithmeticException if {@code this} has a nonzero3537* fractional part.3538* @since 1.53539*/3540public BigInteger toBigIntegerExact() {3541// round to an integer, with Exception if decimal part non-03542return this.setScale(0, ROUND_UNNECESSARY).inflated();3543}35443545/**3546* Converts this {@code BigDecimal} to a {@code long}.3547* This conversion is analogous to the3548* <i>narrowing primitive conversion</i> from {@code double} to3549* {@code short} as defined in3550* <cite>The Java Language Specification</cite>:3551* any fractional part of this3552* {@code BigDecimal} will be discarded, and if the resulting3553* "{@code BigInteger}" is too big to fit in a3554* {@code long}, only the low-order 64 bits are returned.3555* Note that this conversion can lose information about the3556* overall magnitude and precision of this {@code BigDecimal} value as well3557* as return a result with the opposite sign.3558*3559* @return this {@code BigDecimal} converted to a {@code long}.3560* @jls 5.1.3 Narrowing Primitive Conversion3561*/3562@Override3563public long longValue(){3564if (intCompact != INFLATED && scale == 0) {3565return intCompact;3566} else {3567// Fastpath zero and small values3568if (this.signum() == 0 || fractionOnly() ||3569// Fastpath very large-scale values that will result3570// in a truncated value of zero. If the scale is -643571// or less, there are at least 64 powers of 10 in the3572// value of the numerical result. Since 10 = 2*5, in3573// that case there would also be 64 powers of 2 in the3574// result, meaning all 64 bits of a long will be zero.3575scale <= -64) {3576return 0;3577} else {3578return toBigInteger().longValue();3579}3580}3581}35823583/**3584* Return true if a nonzero BigDecimal has an absolute value less3585* than one; i.e. only has fraction digits.3586*/3587private boolean fractionOnly() {3588assert this.signum() != 0;3589return (this.precision() - this.scale) <= 0;3590}35913592/**3593* Converts this {@code BigDecimal} to a {@code long}, checking3594* for lost information. If this {@code BigDecimal} has a3595* nonzero fractional part or is out of the possible range for a3596* {@code long} result then an {@code ArithmeticException} is3597* thrown.3598*3599* @return this {@code BigDecimal} converted to a {@code long}.3600* @throws ArithmeticException if {@code this} has a nonzero3601* fractional part, or will not fit in a {@code long}.3602* @since 1.53603*/3604public long longValueExact() {3605if (intCompact != INFLATED && scale == 0)3606return intCompact;36073608// Fastpath zero3609if (this.signum() == 0)3610return 0;36113612// Fastpath numbers less than 1.0 (the latter can be very slow3613// to round if very small)3614if (fractionOnly())3615throw new ArithmeticException("Rounding necessary");36163617// If more than 19 digits in integer part it cannot possibly fit3618if ((precision() - scale) > 19) // [OK for negative scale too]3619throw new java.lang.ArithmeticException("Overflow");36203621// round to an integer, with Exception if decimal part non-03622BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);3623if (num.precision() >= 19) // need to check carefully3624LongOverflow.check(num);3625return num.inflated().longValue();3626}36273628private static class LongOverflow {3629/** BigInteger equal to Long.MIN_VALUE. */3630private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);36313632/** BigInteger equal to Long.MAX_VALUE. */3633private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);36343635public static void check(BigDecimal num) {3636BigInteger intVal = num.inflated();3637if (intVal.compareTo(LONGMIN) < 0 ||3638intVal.compareTo(LONGMAX) > 0)3639throw new java.lang.ArithmeticException("Overflow");3640}3641}36423643/**3644* Converts this {@code BigDecimal} to an {@code int}.3645* This conversion is analogous to the3646* <i>narrowing primitive conversion</i> from {@code double} to3647* {@code short} as defined in3648* <cite>The Java Language Specification</cite>:3649* any fractional part of this3650* {@code BigDecimal} will be discarded, and if the resulting3651* "{@code BigInteger}" is too big to fit in an3652* {@code int}, only the low-order 32 bits are returned.3653* Note that this conversion can lose information about the3654* overall magnitude and precision of this {@code BigDecimal}3655* value as well as return a result with the opposite sign.3656*3657* @return this {@code BigDecimal} converted to an {@code int}.3658* @jls 5.1.3 Narrowing Primitive Conversion3659*/3660@Override3661public int intValue() {3662return (intCompact != INFLATED && scale == 0) ?3663(int)intCompact :3664(int)longValue();3665}36663667/**3668* Converts this {@code BigDecimal} to an {@code int}, checking3669* for lost information. If this {@code BigDecimal} has a3670* nonzero fractional part or is out of the possible range for an3671* {@code int} result then an {@code ArithmeticException} is3672* thrown.3673*3674* @return this {@code BigDecimal} converted to an {@code int}.3675* @throws ArithmeticException if {@code this} has a nonzero3676* fractional part, or will not fit in an {@code int}.3677* @since 1.53678*/3679public int intValueExact() {3680long num;3681num = this.longValueExact(); // will check decimal part3682if ((int)num != num)3683throw new java.lang.ArithmeticException("Overflow");3684return (int)num;3685}36863687/**3688* Converts this {@code BigDecimal} to a {@code short}, checking3689* for lost information. If this {@code BigDecimal} has a3690* nonzero fractional part or is out of the possible range for a3691* {@code short} result then an {@code ArithmeticException} is3692* thrown.3693*3694* @return this {@code BigDecimal} converted to a {@code short}.3695* @throws ArithmeticException if {@code this} has a nonzero3696* fractional part, or will not fit in a {@code short}.3697* @since 1.53698*/3699public short shortValueExact() {3700long num;3701num = this.longValueExact(); // will check decimal part3702if ((short)num != num)3703throw new java.lang.ArithmeticException("Overflow");3704return (short)num;3705}37063707/**3708* Converts this {@code BigDecimal} to a {@code byte}, checking3709* for lost information. If this {@code BigDecimal} has a3710* nonzero fractional part or is out of the possible range for a3711* {@code byte} result then an {@code ArithmeticException} is3712* thrown.3713*3714* @return this {@code BigDecimal} converted to a {@code byte}.3715* @throws ArithmeticException if {@code this} has a nonzero3716* fractional part, or will not fit in a {@code byte}.3717* @since 1.53718*/3719public byte byteValueExact() {3720long num;3721num = this.longValueExact(); // will check decimal part3722if ((byte)num != num)3723throw new java.lang.ArithmeticException("Overflow");3724return (byte)num;3725}37263727/**3728* Converts this {@code BigDecimal} to a {@code float}.3729* This conversion is similar to the3730* <i>narrowing primitive conversion</i> from {@code double} to3731* {@code float} as defined in3732* <cite>The Java Language Specification</cite>:3733* if this {@code BigDecimal} has too great a3734* magnitude to represent as a {@code float}, it will be3735* converted to {@link Float#NEGATIVE_INFINITY} or {@link3736* Float#POSITIVE_INFINITY} as appropriate. Note that even when3737* the return value is finite, this conversion can lose3738* information about the precision of the {@code BigDecimal}3739* value.3740*3741* @return this {@code BigDecimal} converted to a {@code float}.3742* @jls 5.1.3 Narrowing Primitive Conversion3743*/3744@Override3745public float floatValue(){3746if(intCompact != INFLATED) {3747if (scale == 0) {3748return (float)intCompact;3749} else {3750/*3751* If both intCompact and the scale can be exactly3752* represented as float values, perform a single float3753* multiply or divide to compute the (properly3754* rounded) result.3755*/3756if (Math.abs(intCompact) < 1L<<22 ) {3757// Don't have too guard against3758// Math.abs(MIN_VALUE) because of outer check3759// against INFLATED.3760if (scale > 0 && scale < FLOAT_10_POW.length) {3761return (float)intCompact / FLOAT_10_POW[scale];3762} else if (scale < 0 && scale > -FLOAT_10_POW.length) {3763return (float)intCompact * FLOAT_10_POW[-scale];3764}3765}3766}3767}3768// Somewhat inefficient, but guaranteed to work.3769return Float.parseFloat(this.toString());3770}37713772/**3773* Converts this {@code BigDecimal} to a {@code double}.3774* This conversion is similar to the3775* <i>narrowing primitive conversion</i> from {@code double} to3776* {@code float} as defined in3777* <cite>The Java Language Specification</cite>:3778* if this {@code BigDecimal} has too great a3779* magnitude represent as a {@code double}, it will be3780* converted to {@link Double#NEGATIVE_INFINITY} or {@link3781* Double#POSITIVE_INFINITY} as appropriate. Note that even when3782* the return value is finite, this conversion can lose3783* information about the precision of the {@code BigDecimal}3784* value.3785*3786* @return this {@code BigDecimal} converted to a {@code double}.3787* @jls 5.1.3 Narrowing Primitive Conversion3788*/3789@Override3790public double doubleValue(){3791if(intCompact != INFLATED) {3792if (scale == 0) {3793return (double)intCompact;3794} else {3795/*3796* If both intCompact and the scale can be exactly3797* represented as double values, perform a single3798* double multiply or divide to compute the (properly3799* rounded) result.3800*/3801if (Math.abs(intCompact) < 1L<<52 ) {3802// Don't have too guard against3803// Math.abs(MIN_VALUE) because of outer check3804// against INFLATED.3805if (scale > 0 && scale < DOUBLE_10_POW.length) {3806return (double)intCompact / DOUBLE_10_POW[scale];3807} else if (scale < 0 && scale > -DOUBLE_10_POW.length) {3808return (double)intCompact * DOUBLE_10_POW[-scale];3809}3810}3811}3812}3813// Somewhat inefficient, but guaranteed to work.3814return Double.parseDouble(this.toString());3815}38163817/**3818* Powers of 10 which can be represented exactly in {@code3819* double}.3820*/3821private static final double DOUBLE_10_POW[] = {38221.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,38231.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11,38241.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,38251.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e223826};38273828/**3829* Powers of 10 which can be represented exactly in {@code3830* float}.3831*/3832private static final float FLOAT_10_POW[] = {38331.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,38341.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f3835};38363837/**3838* Returns the size of an ulp, a unit in the last place, of this3839* {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}3840* value is the positive distance between this value and the3841* {@code BigDecimal} value next larger in magnitude with the3842* same number of digits. An ulp of a zero value is numerically3843* equal to 1 with the scale of {@code this}. The result is3844* stored with the same scale as {@code this} so the result3845* for zero and nonzero values is equal to {@code [1,3846* this.scale()]}.3847*3848* @return the size of an ulp of {@code this}3849* @since 1.53850*/3851public BigDecimal ulp() {3852return BigDecimal.valueOf(1, this.scale(), 1);3853}38543855// Private class to build a string representation for BigDecimal object. The3856// StringBuilder field acts as a buffer to hold the temporary representation3857// of BigDecimal. The cmpCharArray holds all the characters for the compact3858// representation of BigDecimal (except for '-' sign' if it is negative) if3859// its intCompact field is not INFLATED.3860static class StringBuilderHelper {3861final StringBuilder sb; // Placeholder for BigDecimal string3862final char[] cmpCharArray; // character array to place the intCompact38633864StringBuilderHelper() {3865sb = new StringBuilder(32);3866// All non negative longs can be made to fit into 19 character array.3867cmpCharArray = new char[19];3868}38693870// Accessors.3871StringBuilder getStringBuilder() {3872sb.setLength(0);3873return sb;3874}38753876char[] getCompactCharArray() {3877return cmpCharArray;3878}38793880/**3881* Places characters representing the intCompact in {@code long} into3882* cmpCharArray and returns the offset to the array where the3883* representation starts.3884*3885* @param intCompact the number to put into the cmpCharArray.3886* @return offset to the array where the representation starts.3887* Note: intCompact must be greater or equal to zero.3888*/3889int putIntCompact(long intCompact) {3890assert intCompact >= 0;38913892long q;3893int r;3894// since we start from the least significant digit, charPos points to3895// the last character in cmpCharArray.3896int charPos = cmpCharArray.length;38973898// Get 2 digits/iteration using longs until quotient fits into an int3899while (intCompact > Integer.MAX_VALUE) {3900q = intCompact / 100;3901r = (int)(intCompact - q * 100);3902intCompact = q;3903cmpCharArray[--charPos] = DIGIT_ONES[r];3904cmpCharArray[--charPos] = DIGIT_TENS[r];3905}39063907// Get 2 digits/iteration using ints when i2 >= 1003908int q2;3909int i2 = (int)intCompact;3910while (i2 >= 100) {3911q2 = i2 / 100;3912r = i2 - q2 * 100;3913i2 = q2;3914cmpCharArray[--charPos] = DIGIT_ONES[r];3915cmpCharArray[--charPos] = DIGIT_TENS[r];3916}39173918cmpCharArray[--charPos] = DIGIT_ONES[i2];3919if (i2 >= 10)3920cmpCharArray[--charPos] = DIGIT_TENS[i2];39213922return charPos;3923}39243925static final char[] DIGIT_TENS = {3926'0', '0', '0', '0', '0', '0', '0', '0', '0', '0',3927'1', '1', '1', '1', '1', '1', '1', '1', '1', '1',3928'2', '2', '2', '2', '2', '2', '2', '2', '2', '2',3929'3', '3', '3', '3', '3', '3', '3', '3', '3', '3',3930'4', '4', '4', '4', '4', '4', '4', '4', '4', '4',3931'5', '5', '5', '5', '5', '5', '5', '5', '5', '5',3932'6', '6', '6', '6', '6', '6', '6', '6', '6', '6',3933'7', '7', '7', '7', '7', '7', '7', '7', '7', '7',3934'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',3935'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',3936};39373938static final char[] DIGIT_ONES = {3939'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3940'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3941'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3942'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3943'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3944'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3945'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3946'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3947'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3948'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',3949};3950}39513952/**3953* Lay out this {@code BigDecimal} into a {@code char[]} array.3954* The Java 1.2 equivalent to this was called {@code getValueString}.3955*3956* @param sci {@code true} for Scientific exponential notation;3957* {@code false} for Engineering3958* @return string with canonical string representation of this3959* {@code BigDecimal}3960*/3961private String layoutChars(boolean sci) {3962if (scale == 0) // zero scale is trivial3963return (intCompact != INFLATED) ?3964Long.toString(intCompact):3965intVal.toString();3966if (scale == 2 &&3967intCompact >= 0 && intCompact < Integer.MAX_VALUE) {3968// currency fast path3969int lowInt = (int)intCompact % 100;3970int highInt = (int)intCompact / 100;3971return (Integer.toString(highInt) + '.' +3972StringBuilderHelper.DIGIT_TENS[lowInt] +3973StringBuilderHelper.DIGIT_ONES[lowInt]) ;3974}39753976StringBuilderHelper sbHelper = new StringBuilderHelper();3977char[] coeff;3978int offset; // offset is the starting index for coeff array3979// Get the significand as an absolute value3980if (intCompact != INFLATED) {3981offset = sbHelper.putIntCompact(Math.abs(intCompact));3982coeff = sbHelper.getCompactCharArray();3983} else {3984offset = 0;3985coeff = intVal.abs().toString().toCharArray();3986}39873988// Construct a buffer, with sufficient capacity for all cases.3989// If E-notation is needed, length will be: +1 if negative, +13990// if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.3991// Otherwise it could have +1 if negative, plus leading "0.00000"3992StringBuilder buf = sbHelper.getStringBuilder();3993if (signum() < 0) // prefix '-' if negative3994buf.append('-');3995int coeffLen = coeff.length - offset;3996long adjusted = -(long)scale + (coeffLen -1);3997if ((scale >= 0) && (adjusted >= -6)) { // plain number3998int pad = scale - coeffLen; // count of padding zeros3999if (pad >= 0) { // 0.xxx form4000buf.append('0');4001buf.append('.');4002for (; pad>0; pad--) {4003buf.append('0');4004}4005buf.append(coeff, offset, coeffLen);4006} else { // xx.xx form4007buf.append(coeff, offset, -pad);4008buf.append('.');4009buf.append(coeff, -pad + offset, scale);4010}4011} else { // E-notation is needed4012if (sci) { // Scientific notation4013buf.append(coeff[offset]); // first character4014if (coeffLen > 1) { // more to come4015buf.append('.');4016buf.append(coeff, offset + 1, coeffLen - 1);4017}4018} else { // Engineering notation4019int sig = (int)(adjusted % 3);4020if (sig < 0)4021sig += 3; // [adjusted was negative]4022adjusted -= sig; // now a multiple of 34023sig++;4024if (signum() == 0) {4025switch (sig) {4026case 1:4027buf.append('0'); // exponent is a multiple of three4028break;4029case 2:4030buf.append("0.00");4031adjusted += 3;4032break;4033case 3:4034buf.append("0.0");4035adjusted += 3;4036break;4037default:4038throw new AssertionError("Unexpected sig value " + sig);4039}4040} else if (sig >= coeffLen) { // significand all in integer4041buf.append(coeff, offset, coeffLen);4042// may need some zeros, too4043for (int i = sig - coeffLen; i > 0; i--) {4044buf.append('0');4045}4046} else { // xx.xxE form4047buf.append(coeff, offset, sig);4048buf.append('.');4049buf.append(coeff, offset + sig, coeffLen - sig);4050}4051}4052if (adjusted != 0) { // [!sci could have made 0]4053buf.append('E');4054if (adjusted > 0) // force sign for positive4055buf.append('+');4056buf.append(adjusted);4057}4058}4059return buf.toString();4060}40614062/**4063* Return 10 to the power n, as a {@code BigInteger}.4064*4065* @param n the power of ten to be returned (>=0)4066* @return a {@code BigInteger} with the value (10<sup>n</sup>)4067*/4068private static BigInteger bigTenToThe(int n) {4069if (n < 0)4070return BigInteger.ZERO;40714072if (n < BIG_TEN_POWERS_TABLE_MAX) {4073BigInteger[] pows = BIG_TEN_POWERS_TABLE;4074if (n < pows.length)4075return pows[n];4076else4077return expandBigIntegerTenPowers(n);4078}40794080return BigInteger.TEN.pow(n);4081}40824083/**4084* Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.4085*4086* @param n the power of ten to be returned (>=0)4087* @return a {@code BigDecimal} with the value (10<sup>n</sup>) and4088* in the meantime, the BIG_TEN_POWERS_TABLE array gets4089* expanded to the size greater than n.4090*/4091private static BigInteger expandBigIntegerTenPowers(int n) {4092synchronized(BigDecimal.class) {4093BigInteger[] pows = BIG_TEN_POWERS_TABLE;4094int curLen = pows.length;4095// The following comparison and the above synchronized statement is4096// to prevent multiple threads from expanding the same array.4097if (curLen <= n) {4098int newLen = curLen << 1;4099while (newLen <= n) {4100newLen <<= 1;4101}4102pows = Arrays.copyOf(pows, newLen);4103for (int i = curLen; i < newLen; i++) {4104pows[i] = pows[i - 1].multiply(BigInteger.TEN);4105}4106// Based on the following facts:4107// 1. pows is a private local variable;4108// 2. the following store is a volatile store.4109// the newly created array elements can be safely published.4110BIG_TEN_POWERS_TABLE = pows;4111}4112return pows[n];4113}4114}41154116private static final long[] LONG_TEN_POWERS_TABLE = {41171, // 0 / 10^0411810, // 1 / 10^14119100, // 2 / 10^241201000, // 3 / 10^3412110000, // 4 / 10^44122100000, // 5 / 10^541231000000, // 6 / 10^6412410000000, // 7 / 10^74125100000000, // 8 / 10^841261000000000, // 9 / 10^9412710000000000L, // 10 / 10^104128100000000000L, // 11 / 10^1141291000000000000L, // 12 / 10^12413010000000000000L, // 13 / 10^134131100000000000000L, // 14 / 10^1441321000000000000000L, // 15 / 10^15413310000000000000000L, // 16 / 10^164134100000000000000000L, // 17 / 10^1741351000000000000000000L // 18 / 10^184136};41374138private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {4139BigInteger.ONE,4140BigInteger.valueOf(10),4141BigInteger.valueOf(100),4142BigInteger.valueOf(1000),4143BigInteger.valueOf(10000),4144BigInteger.valueOf(100000),4145BigInteger.valueOf(1000000),4146BigInteger.valueOf(10000000),4147BigInteger.valueOf(100000000),4148BigInteger.valueOf(1000000000),4149BigInteger.valueOf(10000000000L),4150BigInteger.valueOf(100000000000L),4151BigInteger.valueOf(1000000000000L),4152BigInteger.valueOf(10000000000000L),4153BigInteger.valueOf(100000000000000L),4154BigInteger.valueOf(1000000000000000L),4155BigInteger.valueOf(10000000000000000L),4156BigInteger.valueOf(100000000000000000L),4157BigInteger.valueOf(1000000000000000000L)4158};41594160private static final int BIG_TEN_POWERS_TABLE_INITLEN =4161BIG_TEN_POWERS_TABLE.length;4162private static final int BIG_TEN_POWERS_TABLE_MAX =416316 * BIG_TEN_POWERS_TABLE_INITLEN;41644165private static final long THRESHOLDS_TABLE[] = {4166Long.MAX_VALUE, // 04167Long.MAX_VALUE/10L, // 14168Long.MAX_VALUE/100L, // 24169Long.MAX_VALUE/1000L, // 34170Long.MAX_VALUE/10000L, // 44171Long.MAX_VALUE/100000L, // 54172Long.MAX_VALUE/1000000L, // 64173Long.MAX_VALUE/10000000L, // 74174Long.MAX_VALUE/100000000L, // 84175Long.MAX_VALUE/1000000000L, // 94176Long.MAX_VALUE/10000000000L, // 104177Long.MAX_VALUE/100000000000L, // 114178Long.MAX_VALUE/1000000000000L, // 124179Long.MAX_VALUE/10000000000000L, // 134180Long.MAX_VALUE/100000000000000L, // 144181Long.MAX_VALUE/1000000000000000L, // 154182Long.MAX_VALUE/10000000000000000L, // 164183Long.MAX_VALUE/100000000000000000L, // 174184Long.MAX_VALUE/1000000000000000000L // 184185};41864187/**4188* Compute val * 10 ^ n; return this product if it is4189* representable as a long, INFLATED otherwise.4190*/4191private static long longMultiplyPowerTen(long val, int n) {4192if (val == 0 || n <= 0)4193return val;4194long[] tab = LONG_TEN_POWERS_TABLE;4195long[] bounds = THRESHOLDS_TABLE;4196if (n < tab.length && n < bounds.length) {4197long tenpower = tab[n];4198if (val == 1)4199return tenpower;4200if (Math.abs(val) <= bounds[n])4201return val * tenpower;4202}4203return INFLATED;4204}42054206/**4207* Compute this * 10 ^ n.4208* Needed mainly to allow special casing to trap zero value4209*/4210private BigInteger bigMultiplyPowerTen(int n) {4211if (n <= 0)4212return this.inflated();42134214if (intCompact != INFLATED)4215return bigTenToThe(n).multiply(intCompact);4216else4217return intVal.multiply(bigTenToThe(n));4218}42194220/**4221* Returns appropriate BigInteger from intVal field if intVal is4222* null, i.e. the compact representation is in use.4223*/4224private BigInteger inflated() {4225if (intVal == null) {4226return BigInteger.valueOf(intCompact);4227}4228return intVal;4229}42304231/**4232* Match the scales of two {@code BigDecimal}s to align their4233* least significant digits.4234*4235* <p>If the scales of val[0] and val[1] differ, rescale4236* (non-destructively) the lower-scaled {@code BigDecimal} so4237* they match. That is, the lower-scaled reference will be4238* replaced by a reference to a new object with the same scale as4239* the other {@code BigDecimal}.4240*4241* @param val array of two elements referring to the two4242* {@code BigDecimal}s to be aligned.4243*/4244private static void matchScale(BigDecimal[] val) {4245if (val[0].scale < val[1].scale) {4246val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);4247} else if (val[1].scale < val[0].scale) {4248val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);4249}4250}42514252private static class UnsafeHolder {4253private static final jdk.internal.misc.Unsafe unsafe4254= jdk.internal.misc.Unsafe.getUnsafe();4255private static final long intCompactOffset4256= unsafe.objectFieldOffset(BigDecimal.class, "intCompact");4257private static final long intValOffset4258= unsafe.objectFieldOffset(BigDecimal.class, "intVal");42594260static void setIntCompact(BigDecimal bd, long val) {4261unsafe.putLong(bd, intCompactOffset, val);4262}42634264static void setIntValVolatile(BigDecimal bd, BigInteger val) {4265unsafe.putReferenceVolatile(bd, intValOffset, val);4266}4267}42684269/**4270* Reconstitute the {@code BigDecimal} instance from a stream (that is,4271* deserialize it).4272*4273* @param s the stream being read.4274* @throws IOException if an I/O error occurs4275* @throws ClassNotFoundException if a serialized class cannot be loaded4276*/4277@java.io.Serial4278private void readObject(java.io.ObjectInputStream s)4279throws IOException, ClassNotFoundException {4280// Read in all fields4281s.defaultReadObject();4282// validate possibly bad fields4283if (intVal == null) {4284String message = "BigDecimal: null intVal in stream";4285throw new java.io.StreamCorruptedException(message);4286// [all values of scale are now allowed]4287}4288UnsafeHolder.setIntCompact(this, compactValFor(intVal));4289}42904291/**4292* Serialize this {@code BigDecimal} to the stream in question4293*4294* @param s the stream to serialize to.4295* @throws IOException if an I/O error occurs4296*/4297@java.io.Serial4298private void writeObject(java.io.ObjectOutputStream s)4299throws IOException {4300// Must inflate to maintain compatible serial form.4301if (this.intVal == null)4302UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact));4303// Could reset intVal back to null if it has to be set.4304s.defaultWriteObject();4305}43064307/**4308* Returns the length of the absolute value of a {@code long}, in decimal4309* digits.4310*4311* @param x the {@code long}4312* @return the length of the unscaled value, in deciaml digits.4313*/4314static int longDigitLength(long x) {4315/*4316* As described in "Bit Twiddling Hacks" by Sean Anderson,4317* (http://graphics.stanford.edu/~seander/bithacks.html)4318* integer log 10 of x is within 1 of (1233/4096)* (1 +4319* integer log 2 of x). The fraction 1233/4096 approximates4320* log10(2). So we first do a version of log2 (a variant of4321* Long class with pre-checks and opposite directionality) and4322* then scale and check against powers table. This is a little4323* simpler in present context than the version in Hacker's4324* Delight sec 11-4. Adding one to bit length allows comparing4325* downward from the LONG_TEN_POWERS_TABLE that we need4326* anyway.4327*/4328assert x != BigDecimal.INFLATED;4329if (x < 0)4330x = -x;4331if (x < 10) // must screen for 0, might as well 104332return 1;4333int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12;4334long[] tab = LONG_TEN_POWERS_TABLE;4335// if r >= length, must have max possible digits for long4336return (r >= tab.length || x < tab[r]) ? r : r + 1;4337}43384339/**4340* Returns the length of the absolute value of a BigInteger, in4341* decimal digits.4342*4343* @param b the BigInteger4344* @return the length of the unscaled value, in decimal digits4345*/4346private static int bigDigitLength(BigInteger b) {4347/*4348* Same idea as the long version, but we need a better4349* approximation of log10(2). Using 646456993/2^314350* is accurate up to max possible reported bitLength.4351*/4352if (b.signum == 0)4353return 1;4354int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);4355return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;4356}43574358/**4359* Check a scale for Underflow or Overflow. If this BigDecimal is4360* nonzero, throw an exception if the scale is outof range. If this4361* is zero, saturate the scale to the extreme value of the right4362* sign if the scale is out of range.4363*4364* @param val The new scale.4365* @throws ArithmeticException (overflow or underflow) if the new4366* scale is out of range.4367* @return validated scale as an int.4368*/4369private int checkScale(long val) {4370int asInt = (int)val;4371if (asInt != val) {4372asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;4373BigInteger b;4374if (intCompact != 0 &&4375((b = intVal) == null || b.signum() != 0))4376throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");4377}4378return asInt;4379}43804381/**4382* Returns the compact value for given {@code BigInteger}, or4383* INFLATED if too big. Relies on internal representation of4384* {@code BigInteger}.4385*/4386private static long compactValFor(BigInteger b) {4387int[] m = b.mag;4388int len = m.length;4389if (len == 0)4390return 0;4391int d = m[0];4392if (len > 2 || (len == 2 && d < 0))4393return INFLATED;43944395long u = (len == 2)?4396(((long) m[1] & LONG_MASK) + (((long)d) << 32)) :4397(((long)d) & LONG_MASK);4398return (b.signum < 0)? -u : u;4399}44004401private static int longCompareMagnitude(long x, long y) {4402if (x < 0)4403x = -x;4404if (y < 0)4405y = -y;4406return (x < y) ? -1 : ((x == y) ? 0 : 1);4407}44084409private static int saturateLong(long s) {4410int i = (int)s;4411return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);4412}44134414/*4415* Internal printing routine4416*/4417private static void print(String name, BigDecimal bd) {4418System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",4419name,4420bd.intCompact,4421bd.intVal,4422bd.scale,4423bd.precision);4424}44254426/**4427* Check internal invariants of this BigDecimal. These invariants4428* include:4429*4430* <ul>4431*4432* <li>The object must be initialized; either intCompact must not be4433* INFLATED or intVal is non-null. Both of these conditions may4434* be true.4435*4436* <li>If both intCompact and intVal and set, their values must be4437* consistent.4438*4439* <li>If precision is nonzero, it must have the right value.4440* </ul>4441*4442* Note: Since this is an audit method, we are not supposed to change the4443* state of this BigDecimal object.4444*/4445private BigDecimal audit() {4446if (intCompact == INFLATED) {4447if (intVal == null) {4448print("audit", this);4449throw new AssertionError("null intVal");4450}4451// Check precision4452if (precision > 0 && precision != bigDigitLength(intVal)) {4453print("audit", this);4454throw new AssertionError("precision mismatch");4455}4456} else {4457if (intVal != null) {4458long val = intVal.longValue();4459if (val != intCompact) {4460print("audit", this);4461throw new AssertionError("Inconsistent state, intCompact=" +4462intCompact + "\t intVal=" + val);4463}4464}4465// Check precision4466if (precision > 0 && precision != longDigitLength(intCompact)) {4467print("audit", this);4468throw new AssertionError("precision mismatch");4469}4470}4471return this;4472}44734474/* the same as checkScale where value!=0 */4475private static int checkScaleNonZero(long val) {4476int asInt = (int)val;4477if (asInt != val) {4478throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");4479}4480return asInt;4481}44824483private static int checkScale(long intCompact, long val) {4484int asInt = (int)val;4485if (asInt != val) {4486asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;4487if (intCompact != 0)4488throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");4489}4490return asInt;4491}44924493private static int checkScale(BigInteger intVal, long val) {4494int asInt = (int)val;4495if (asInt != val) {4496asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;4497if (intVal.signum() != 0)4498throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");4499}4500return asInt;4501}45024503/**4504* Returns a {@code BigDecimal} rounded according to the MathContext4505* settings;4506* If rounding is needed a new {@code BigDecimal} is created and returned.4507*4508* @param val the value to be rounded4509* @param mc the context to use.4510* @return a {@code BigDecimal} rounded according to the MathContext4511* settings. May return {@code value}, if no rounding needed.4512* @throws ArithmeticException if the rounding mode is4513* {@code RoundingMode.UNNECESSARY} and the4514* result is inexact.4515*/4516private static BigDecimal doRound(BigDecimal val, MathContext mc) {4517int mcp = mc.precision;4518boolean wasDivided = false;4519if (mcp > 0) {4520BigInteger intVal = val.intVal;4521long compactVal = val.intCompact;4522int scale = val.scale;4523int prec = val.precision();4524int mode = mc.roundingMode.oldMode;4525int drop;4526if (compactVal == INFLATED) {4527drop = prec - mcp;4528while (drop > 0) {4529scale = checkScaleNonZero((long) scale - drop);4530intVal = divideAndRoundByTenPow(intVal, drop, mode);4531wasDivided = true;4532compactVal = compactValFor(intVal);4533if (compactVal != INFLATED) {4534prec = longDigitLength(compactVal);4535break;4536}4537prec = bigDigitLength(intVal);4538drop = prec - mcp;4539}4540}4541if (compactVal != INFLATED) {4542drop = prec - mcp; // drop can't be more than 184543while (drop > 0) {4544scale = checkScaleNonZero((long) scale - drop);4545compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4546wasDivided = true;4547prec = longDigitLength(compactVal);4548drop = prec - mcp;4549intVal = null;4550}4551}4552return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val;4553}4554return val;4555}45564557/*4558* Returns a {@code BigDecimal} created from {@code long} value with4559* given scale rounded according to the MathContext settings4560*/4561private static BigDecimal doRound(long compactVal, int scale, MathContext mc) {4562int mcp = mc.precision;4563if (mcp > 0 && mcp < 19) {4564int prec = longDigitLength(compactVal);4565int drop = prec - mcp; // drop can't be more than 184566while (drop > 0) {4567scale = checkScaleNonZero((long) scale - drop);4568compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4569prec = longDigitLength(compactVal);4570drop = prec - mcp;4571}4572return valueOf(compactVal, scale, prec);4573}4574return valueOf(compactVal, scale);4575}45764577/*4578* Returns a {@code BigDecimal} created from {@code BigInteger} value with4579* given scale rounded according to the MathContext settings4580*/4581private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) {4582int mcp = mc.precision;4583int prec = 0;4584if (mcp > 0) {4585long compactVal = compactValFor(intVal);4586int mode = mc.roundingMode.oldMode;4587int drop;4588if (compactVal == INFLATED) {4589prec = bigDigitLength(intVal);4590drop = prec - mcp;4591while (drop > 0) {4592scale = checkScaleNonZero((long) scale - drop);4593intVal = divideAndRoundByTenPow(intVal, drop, mode);4594compactVal = compactValFor(intVal);4595if (compactVal != INFLATED) {4596break;4597}4598prec = bigDigitLength(intVal);4599drop = prec - mcp;4600}4601}4602if (compactVal != INFLATED) {4603prec = longDigitLength(compactVal);4604drop = prec - mcp; // drop can't be more than 184605while (drop > 0) {4606scale = checkScaleNonZero((long) scale - drop);4607compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);4608prec = longDigitLength(compactVal);4609drop = prec - mcp;4610}4611return valueOf(compactVal,scale,prec);4612}4613}4614return new BigDecimal(intVal,INFLATED,scale,prec);4615}46164617/*4618* Divides {@code BigInteger} value by ten power.4619*/4620private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) {4621if (tenPow < LONG_TEN_POWERS_TABLE.length)4622intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode);4623else4624intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode);4625return intVal;4626}46274628/**4629* Internally used for division operation for division {@code long} by4630* {@code long}.4631* The returned {@code BigDecimal} object is the quotient whose scale is set4632* to the passed in scale. If the remainder is not zero, it will be rounded4633* based on the passed in roundingMode. Also, if the remainder is zero and4634* the last parameter, i.e. preferredScale is NOT equal to scale, the4635* trailing zeros of the result is stripped to match the preferredScale.4636*/4637private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode,4638int preferredScale) {46394640int qsign; // quotient sign4641long q = ldividend / ldivisor; // store quotient in long4642if (roundingMode == ROUND_DOWN && scale == preferredScale)4643return valueOf(q, scale);4644long r = ldividend % ldivisor; // store remainder in long4645qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;4646if (r != 0) {4647boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);4648return valueOf((increment ? q + qsign : q), scale);4649} else {4650if (preferredScale != scale)4651return createAndStripZerosToMatchScale(q, scale, preferredScale);4652else4653return valueOf(q, scale);4654}4655}46564657/**4658* Divides {@code long} by {@code long} and do rounding based on the4659* passed in roundingMode.4660*/4661private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) {4662int qsign; // quotient sign4663long q = ldividend / ldivisor; // store quotient in long4664if (roundingMode == ROUND_DOWN)4665return q;4666long r = ldividend % ldivisor; // store remainder in long4667qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;4668if (r != 0) {4669boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r);4670return increment ? q + qsign : q;4671} else {4672return q;4673}4674}46754676/**4677* Shared logic of need increment computation.4678*/4679private static boolean commonNeedIncrement(int roundingMode, int qsign,4680int cmpFracHalf, boolean oddQuot) {4681switch(roundingMode) {4682case ROUND_UNNECESSARY:4683throw new ArithmeticException("Rounding necessary");46844685case ROUND_UP: // Away from zero4686return true;46874688case ROUND_DOWN: // Towards zero4689return false;46904691case ROUND_CEILING: // Towards +infinity4692return qsign > 0;46934694case ROUND_FLOOR: // Towards -infinity4695return qsign < 0;46964697default: // Some kind of half-way rounding4698assert roundingMode >= ROUND_HALF_UP &&4699roundingMode <= ROUND_HALF_EVEN: "Unexpected rounding mode" + RoundingMode.valueOf(roundingMode);47004701if (cmpFracHalf < 0 ) // We're closer to higher digit4702return false;4703else if (cmpFracHalf > 0 ) // We're closer to lower digit4704return true;4705else { // half-way4706assert cmpFracHalf == 0;47074708return switch (roundingMode) {4709case ROUND_HALF_DOWN -> false;4710case ROUND_HALF_UP -> true;4711case ROUND_HALF_EVEN -> oddQuot;47124713default -> throw new AssertionError("Unexpected rounding mode" + roundingMode);4714};4715}4716}4717}47184719/**4720* Tests if quotient has to be incremented according the roundingMode4721*/4722private static boolean needIncrement(long ldivisor, int roundingMode,4723int qsign, long q, long r) {4724assert r != 0L;47254726int cmpFracHalf;4727if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {4728cmpFracHalf = 1; // 2 * r can't fit into long4729} else {4730cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);4731}47324733return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);4734}47354736/**4737* Divides {@code BigInteger} value by {@code long} value and4738* do rounding based on the passed in roundingMode.4739*/4740private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {4741// Descend into mutables for faster remainder checks4742MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4743// store quotient4744MutableBigInteger mq = new MutableBigInteger();4745// store quotient & remainder in long4746long r = mdividend.divide(ldivisor, mq);4747// record remainder is zero or not4748boolean isRemainderZero = (r == 0);4749// quotient sign4750int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;4751if (!isRemainderZero) {4752if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {4753mq.add(MutableBigInteger.ONE);4754}4755}4756return mq.toBigInteger(qsign);4757}47584759/**4760* Internally used for division operation for division {@code BigInteger}4761* by {@code long}.4762* The returned {@code BigDecimal} object is the quotient whose scale is set4763* to the passed in scale. If the remainder is not zero, it will be rounded4764* based on the passed in roundingMode. Also, if the remainder is zero and4765* the last parameter, i.e. preferredScale is NOT equal to scale, the4766* trailing zeros of the result is stripped to match the preferredScale.4767*/4768private static BigDecimal divideAndRound(BigInteger bdividend,4769long ldivisor, int scale, int roundingMode, int preferredScale) {4770// Descend into mutables for faster remainder checks4771MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4772// store quotient4773MutableBigInteger mq = new MutableBigInteger();4774// store quotient & remainder in long4775long r = mdividend.divide(ldivisor, mq);4776// record remainder is zero or not4777boolean isRemainderZero = (r == 0);4778// quotient sign4779int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;4780if (!isRemainderZero) {4781if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {4782mq.add(MutableBigInteger.ONE);4783}4784return mq.toBigDecimal(qsign, scale);4785} else {4786if (preferredScale != scale) {4787long compactVal = mq.toCompactValue(qsign);4788if(compactVal!=INFLATED) {4789return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);4790}4791BigInteger intVal = mq.toBigInteger(qsign);4792return createAndStripZerosToMatchScale(intVal,scale, preferredScale);4793} else {4794return mq.toBigDecimal(qsign, scale);4795}4796}4797}47984799/**4800* Tests if quotient has to be incremented according the roundingMode4801*/4802private static boolean needIncrement(long ldivisor, int roundingMode,4803int qsign, MutableBigInteger mq, long r) {4804assert r != 0L;48054806int cmpFracHalf;4807if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {4808cmpFracHalf = 1; // 2 * r can't fit into long4809} else {4810cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);4811}48124813return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());4814}48154816/**4817* Divides {@code BigInteger} value by {@code BigInteger} value and4818* do rounding based on the passed in roundingMode.4819*/4820private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) {4821boolean isRemainderZero; // record remainder is zero or not4822int qsign; // quotient sign4823// Descend into mutables for faster remainder checks4824MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4825MutableBigInteger mq = new MutableBigInteger();4826MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);4827MutableBigInteger mr = mdividend.divide(mdivisor, mq);4828isRemainderZero = mr.isZero();4829qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;4830if (!isRemainderZero) {4831if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {4832mq.add(MutableBigInteger.ONE);4833}4834}4835return mq.toBigInteger(qsign);4836}48374838/**4839* Internally used for division operation for division {@code BigInteger}4840* by {@code BigInteger}.4841* The returned {@code BigDecimal} object is the quotient whose scale is set4842* to the passed in scale. If the remainder is not zero, it will be rounded4843* based on the passed in roundingMode. Also, if the remainder is zero and4844* the last parameter, i.e. preferredScale is NOT equal to scale, the4845* trailing zeros of the result is stripped to match the preferredScale.4846*/4847private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode,4848int preferredScale) {4849boolean isRemainderZero; // record remainder is zero or not4850int qsign; // quotient sign4851// Descend into mutables for faster remainder checks4852MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);4853MutableBigInteger mq = new MutableBigInteger();4854MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag);4855MutableBigInteger mr = mdividend.divide(mdivisor, mq);4856isRemainderZero = mr.isZero();4857qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;4858if (!isRemainderZero) {4859if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) {4860mq.add(MutableBigInteger.ONE);4861}4862return mq.toBigDecimal(qsign, scale);4863} else {4864if (preferredScale != scale) {4865long compactVal = mq.toCompactValue(qsign);4866if (compactVal != INFLATED) {4867return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);4868}4869BigInteger intVal = mq.toBigInteger(qsign);4870return createAndStripZerosToMatchScale(intVal, scale, preferredScale);4871} else {4872return mq.toBigDecimal(qsign, scale);4873}4874}4875}48764877/**4878* Tests if quotient has to be incremented according the roundingMode4879*/4880private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode,4881int qsign, MutableBigInteger mq, MutableBigInteger mr) {4882assert !mr.isZero();4883int cmpFracHalf = mr.compareHalf(mdivisor);4884return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd());4885}48864887/**4888* Remove insignificant trailing zeros from this4889* {@code BigInteger} value until the preferred scale is reached or no4890* more zeros can be removed. If the preferred scale is less than4891* Integer.MIN_VALUE, all the trailing zeros will be removed.4892*4893* @return new {@code BigDecimal} with a scale possibly reduced4894* to be closed to the preferred scale.4895* @throws ArithmeticException if scale overflows.4896*/4897private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) {4898BigInteger qr[]; // quotient-remainder pair4899while (intVal.compareMagnitude(BigInteger.TEN) >= 04900&& scale > preferredScale) {4901if (intVal.testBit(0))4902break; // odd number cannot end in 04903qr = intVal.divideAndRemainder(BigInteger.TEN);4904if (qr[1].signum() != 0)4905break; // non-0 remainder4906intVal = qr[0];4907scale = checkScale(intVal,(long) scale - 1); // could Overflow4908}4909return valueOf(intVal, scale, 0);4910}49114912/**4913* Remove insignificant trailing zeros from this4914* {@code long} value until the preferred scale is reached or no4915* more zeros can be removed. If the preferred scale is less than4916* Integer.MIN_VALUE, all the trailing zeros will be removed.4917*4918* @return new {@code BigDecimal} with a scale possibly reduced4919* to be closed to the preferred scale.4920* @throws ArithmeticException if scale overflows.4921*/4922private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) {4923while (Math.abs(compactVal) >= 10L && scale > preferredScale) {4924if ((compactVal & 1L) != 0L)4925break; // odd number cannot end in 04926long r = compactVal % 10L;4927if (r != 0L)4928break; // non-0 remainder4929compactVal /= 10;4930scale = checkScale(compactVal, (long) scale - 1); // could Overflow4931}4932return valueOf(compactVal, scale);4933}49344935private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) {4936if(intCompact!=INFLATED) {4937return createAndStripZerosToMatchScale(intCompact, scale, preferredScale);4938} else {4939return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal,4940scale, preferredScale);4941}4942}49434944/*4945* returns INFLATED if oveflow4946*/4947private static long add(long xs, long ys){4948long sum = xs + ys;4949// See "Hacker's Delight" section 2-12 for explanation of4950// the overflow test.4951if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed4952return sum;4953}4954return INFLATED;4955}49564957private static BigDecimal add(long xs, long ys, int scale){4958long sum = add(xs, ys);4959if (sum!=INFLATED)4960return BigDecimal.valueOf(sum, scale);4961return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale);4962}49634964private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) {4965long sdiff = (long) scale1 - scale2;4966if (sdiff == 0) {4967return add(xs, ys, scale1);4968} else if (sdiff < 0) {4969int raise = checkScale(xs,-sdiff);4970long scaledX = longMultiplyPowerTen(xs, raise);4971if (scaledX != INFLATED) {4972return add(scaledX, ys, scale2);4973} else {4974BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys);4975return ((xs^ys)>=0) ? // same sign test4976new BigDecimal(bigsum, INFLATED, scale2, 0)4977: valueOf(bigsum, scale2, 0);4978}4979} else {4980int raise = checkScale(ys,sdiff);4981long scaledY = longMultiplyPowerTen(ys, raise);4982if (scaledY != INFLATED) {4983return add(xs, scaledY, scale1);4984} else {4985BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs);4986return ((xs^ys)>=0) ?4987new BigDecimal(bigsum, INFLATED, scale1, 0)4988: valueOf(bigsum, scale1, 0);4989}4990}4991}49924993private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) {4994int rscale = scale1;4995long sdiff = (long)rscale - scale2;4996boolean sameSigns = (Long.signum(xs) == snd.signum);4997BigInteger sum;4998if (sdiff < 0) {4999int raise = checkScale(xs,-sdiff);5000rscale = scale2;5001long scaledX = longMultiplyPowerTen(xs, raise);5002if (scaledX == INFLATED) {5003sum = snd.add(bigMultiplyPowerTen(xs,raise));5004} else {5005sum = snd.add(scaledX);5006}5007} else { //if (sdiff > 0) {5008int raise = checkScale(snd,sdiff);5009snd = bigMultiplyPowerTen(snd,raise);5010sum = snd.add(xs);5011}5012return (sameSigns) ?5013new BigDecimal(sum, INFLATED, rscale, 0) :5014valueOf(sum, rscale, 0);5015}50165017private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) {5018int rscale = scale1;5019long sdiff = (long)rscale - scale2;5020if (sdiff != 0) {5021if (sdiff < 0) {5022int raise = checkScale(fst,-sdiff);5023rscale = scale2;5024fst = bigMultiplyPowerTen(fst,raise);5025} else {5026int raise = checkScale(snd,sdiff);5027snd = bigMultiplyPowerTen(snd,raise);5028}5029}5030BigInteger sum = fst.add(snd);5031return (fst.signum == snd.signum) ?5032new BigDecimal(sum, INFLATED, rscale, 0) :5033valueOf(sum, rscale, 0);5034}50355036private static BigInteger bigMultiplyPowerTen(long value, int n) {5037if (n <= 0)5038return BigInteger.valueOf(value);5039return bigTenToThe(n).multiply(value);5040}50415042private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) {5043if (n <= 0)5044return value;5045if(n<LONG_TEN_POWERS_TABLE.length) {5046return value.multiply(LONG_TEN_POWERS_TABLE[n]);5047}5048return value.multiply(bigTenToThe(n));5049}50505051/**5052* Returns a {@code BigDecimal} whose value is {@code (xs /5053* ys)}, with rounding according to the context settings.5054*5055* Fast path - used only when (xscale <= yscale && yscale < 185056* && mc.presision<18) {5057*/5058private static BigDecimal divideSmallFastPath(final long xs, int xscale,5059final long ys, int yscale,5060long preferredScale, MathContext mc) {5061int mcp = mc.precision;5062int roundingMode = mc.roundingMode.oldMode;50635064assert (xscale <= yscale) && (yscale < 18) && (mcp < 18);5065int xraise = yscale - xscale; // xraise >=05066long scaledX = (xraise==0) ? xs :5067longMultiplyPowerTen(xs, xraise); // can't overflow here!5068BigDecimal quotient;50695070int cmp = longCompareMagnitude(scaledX, ys);5071if(cmp > 0) { // satisfy constraint (b)5072yscale -= 1; // [that is, divisor *= 10]5073int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5074if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {5075// assert newScale >= xscale5076int raise = checkScaleNonZero((long) mcp + yscale - xscale);5077long scaledXs;5078if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {5079quotient = null;5080if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) {5081quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5082}5083if(quotient==null) {5084BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1);5085quotient = divideAndRound(rb, ys,5086scl, roundingMode, checkScaleNonZero(preferredScale));5087}5088} else {5089quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5090}5091} else {5092int newScale = checkScaleNonZero((long) xscale - mcp);5093// assert newScale >= yscale5094if (newScale == yscale) { // easy case5095quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));5096} else {5097int raise = checkScaleNonZero((long) newScale - yscale);5098long scaledYs;5099if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {5100BigInteger rb = bigMultiplyPowerTen(ys,raise);5101quotient = divideAndRound(BigInteger.valueOf(xs),5102rb, scl, roundingMode,checkScaleNonZero(preferredScale));5103} else {5104quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));5105}5106}5107}5108} else {5109// abs(scaledX) <= abs(ys)5110// result is "scaledX * 10^msp / ys"5111int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5112if(cmp==0) {5113// abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign5114quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale));5115} else {5116// abs(scaledX) < abs(ys)5117long scaledXs;5118if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) {5119quotient = null;5120if(mcp<LONG_TEN_POWERS_TABLE.length) {5121quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5122}5123if(quotient==null) {5124BigInteger rb = bigMultiplyPowerTen(scaledX,mcp);5125quotient = divideAndRound(rb, ys,5126scl, roundingMode, checkScaleNonZero(preferredScale));5127}5128} else {5129quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5130}5131}5132}5133// doRound, here, only affects 1000000000 case.5134return doRound(quotient,mc);5135}51365137/**5138* Returns a {@code BigDecimal} whose value is {@code (xs /5139* ys)}, with rounding according to the context settings.5140*/5141private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) {5142int mcp = mc.precision;5143if(xscale <= yscale && yscale < 18 && mcp<18) {5144return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc);5145}5146if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)5147yscale -= 1; // [that is, divisor *= 10]5148}5149int roundingMode = mc.roundingMode.oldMode;5150// In order to find out whether the divide generates the exact result,5151// we avoid calling the above divide method. 'quotient' holds the5152// return BigDecimal object whose scale will be set to 'scl'.5153int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5154BigDecimal quotient;5155if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {5156int raise = checkScaleNonZero((long) mcp + yscale - xscale);5157long scaledXs;5158if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) {5159BigInteger rb = bigMultiplyPowerTen(xs,raise);5160quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5161} else {5162quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5163}5164} else {5165int newScale = checkScaleNonZero((long) xscale - mcp);5166// assert newScale >= yscale5167if (newScale == yscale) { // easy case5168quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));5169} else {5170int raise = checkScaleNonZero((long) newScale - yscale);5171long scaledYs;5172if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {5173BigInteger rb = bigMultiplyPowerTen(ys,raise);5174quotient = divideAndRound(BigInteger.valueOf(xs),5175rb, scl, roundingMode,checkScaleNonZero(preferredScale));5176} else {5177quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));5178}5179}5180}5181// doRound, here, only affects 1000000000 case.5182return doRound(quotient,mc);5183}51845185/**5186* Returns a {@code BigDecimal} whose value is {@code (xs /5187* ys)}, with rounding according to the context settings.5188*/5189private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) {5190// Normalize dividend & divisor so that both fall into [0.1, 0.999...]5191if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b)5192yscale -= 1; // [that is, divisor *= 10]5193}5194int mcp = mc.precision;5195int roundingMode = mc.roundingMode.oldMode;51965197// In order to find out whether the divide generates the exact result,5198// we avoid calling the above divide method. 'quotient' holds the5199// return BigDecimal object whose scale will be set to 'scl'.5200BigDecimal quotient;5201int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5202if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {5203int raise = checkScaleNonZero((long) mcp + yscale - xscale);5204BigInteger rb = bigMultiplyPowerTen(xs,raise);5205quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5206} else {5207int newScale = checkScaleNonZero((long) xscale - mcp);5208// assert newScale >= yscale5209if (newScale == yscale) { // easy case5210quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale));5211} else {5212int raise = checkScaleNonZero((long) newScale - yscale);5213long scaledYs;5214if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) {5215BigInteger rb = bigMultiplyPowerTen(ys,raise);5216quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));5217} else {5218quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale));5219}5220}5221}5222// doRound, here, only affects 1000000000 case.5223return doRound(quotient, mc);5224}52255226/**5227* Returns a {@code BigDecimal} whose value is {@code (xs /5228* ys)}, with rounding according to the context settings.5229*/5230private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {5231// Normalize dividend & divisor so that both fall into [0.1, 0.999...]5232if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)5233yscale -= 1; // [that is, divisor *= 10]5234}5235int mcp = mc.precision;5236int roundingMode = mc.roundingMode.oldMode;52375238// In order to find out whether the divide generates the exact result,5239// we avoid calling the above divide method. 'quotient' holds the5240// return BigDecimal object whose scale will be set to 'scl'.5241BigDecimal quotient;5242int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5243if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {5244int raise = checkScaleNonZero((long) mcp + yscale - xscale);5245BigInteger rb = bigMultiplyPowerTen(xs,raise);5246quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5247} else {5248int newScale = checkScaleNonZero((long) xscale - mcp);5249int raise = checkScaleNonZero((long) newScale - yscale);5250BigInteger rb = bigMultiplyPowerTen(ys,raise);5251quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale));5252}5253// doRound, here, only affects 1000000000 case.5254return doRound(quotient, mc);5255}52565257/**5258* Returns a {@code BigDecimal} whose value is {@code (xs /5259* ys)}, with rounding according to the context settings.5260*/5261private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) {5262// Normalize dividend & divisor so that both fall into [0.1, 0.999...]5263if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b)5264yscale -= 1; // [that is, divisor *= 10]5265}5266int mcp = mc.precision;5267int roundingMode = mc.roundingMode.oldMode;52685269// In order to find out whether the divide generates the exact result,5270// we avoid calling the above divide method. 'quotient' holds the5271// return BigDecimal object whose scale will be set to 'scl'.5272BigDecimal quotient;5273int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp);5274if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) {5275int raise = checkScaleNonZero((long) mcp + yscale - xscale);5276BigInteger rb = bigMultiplyPowerTen(xs,raise);5277quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale));5278} else {5279int newScale = checkScaleNonZero((long) xscale - mcp);5280int raise = checkScaleNonZero((long) newScale - yscale);5281BigInteger rb = bigMultiplyPowerTen(ys,raise);5282quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale));5283}5284// doRound, here, only affects 1000000000 case.5285return doRound(quotient, mc);5286}52875288/*5289* performs divideAndRound for (dividend0*dividend1, divisor)5290* returns null if quotient can't fit into long value;5291*/5292private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode,5293int preferredScale) {5294int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor);5295dividend0 = Math.abs(dividend0);5296dividend1 = Math.abs(dividend1);5297divisor = Math.abs(divisor);5298// multiply dividend0 * dividend15299long d0_hi = dividend0 >>> 32;5300long d0_lo = dividend0 & LONG_MASK;5301long d1_hi = dividend1 >>> 32;5302long d1_lo = dividend1 & LONG_MASK;5303long product = d0_lo * d1_lo;5304long d0 = product & LONG_MASK;5305long d1 = product >>> 32;5306product = d0_hi * d1_lo + d1;5307d1 = product & LONG_MASK;5308long d2 = product >>> 32;5309product = d0_lo * d1_hi + d1;5310d1 = product & LONG_MASK;5311d2 += product >>> 32;5312long d3 = d2>>>32;5313d2 &= LONG_MASK;5314product = d0_hi*d1_hi + d2;5315d2 = product & LONG_MASK;5316d3 = ((product>>>32) + d3) & LONG_MASK;5317final long dividendHi = make64(d3,d2);5318final long dividendLo = make64(d1,d0);5319// divide5320return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale);5321}53225323private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits).53245325/*5326* divideAndRound 128-bit value by long divisor.5327* returns null if quotient can't fit into long value;5328* Specialized version of Knuth's division5329*/5330private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign,5331int scale, int roundingMode, int preferredScale) {5332if (dividendHi >= divisor) {5333return null;5334}53355336final int shift = Long.numberOfLeadingZeros(divisor);5337divisor <<= shift;53385339final long v1 = divisor >>> 32;5340final long v0 = divisor & LONG_MASK;53415342long tmp = dividendLo << shift;5343long u1 = tmp >>> 32;5344long u0 = tmp & LONG_MASK;53455346tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift);5347long u2 = tmp & LONG_MASK;5348long q1, r_tmp;5349if (v1 == 1) {5350q1 = tmp;5351r_tmp = 0;5352} else if (tmp >= 0) {5353q1 = tmp / v1;5354r_tmp = tmp - q1 * v1;5355} else {5356long[] rq = divRemNegativeLong(tmp, v1);5357q1 = rq[1];5358r_tmp = rq[0];5359}53605361while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) {5362q1--;5363r_tmp += v1;5364if (r_tmp >= DIV_NUM_BASE)5365break;5366}53675368tmp = mulsub(u2,u1,v1,v0,q1);5369u1 = tmp & LONG_MASK;5370long q0;5371if (v1 == 1) {5372q0 = tmp;5373r_tmp = 0;5374} else if (tmp >= 0) {5375q0 = tmp / v1;5376r_tmp = tmp - q0 * v1;5377} else {5378long[] rq = divRemNegativeLong(tmp, v1);5379q0 = rq[1];5380r_tmp = rq[0];5381}53825383while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) {5384q0--;5385r_tmp += v1;5386if (r_tmp >= DIV_NUM_BASE)5387break;5388}53895390if((int)q1 < 0) {5391// result (which is positive and unsigned here)5392// can't fit into long due to sign bit is used for value5393MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0});5394if (roundingMode == ROUND_DOWN && scale == preferredScale) {5395return mq.toBigDecimal(sign, scale);5396}5397long r = mulsub(u1, u0, v1, v0, q0) >>> shift;5398if (r != 0) {5399if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){5400mq.add(MutableBigInteger.ONE);5401}5402return mq.toBigDecimal(sign, scale);5403} else {5404if (preferredScale != scale) {5405BigInteger intVal = mq.toBigInteger(sign);5406return createAndStripZerosToMatchScale(intVal,scale, preferredScale);5407} else {5408return mq.toBigDecimal(sign, scale);5409}5410}5411}54125413long q = make64(q1,q0);5414q*=sign;54155416if (roundingMode == ROUND_DOWN && scale == preferredScale)5417return valueOf(q, scale);54185419long r = mulsub(u1, u0, v1, v0, q0) >>> shift;5420if (r != 0) {5421boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r);5422return valueOf((increment ? q + sign : q), scale);5423} else {5424if (preferredScale != scale) {5425return createAndStripZerosToMatchScale(q, scale, preferredScale);5426} else {5427return valueOf(q, scale);5428}5429}5430}54315432/*5433* calculate divideAndRound for ldividend*10^raise / divisor5434* when abs(dividend)==abs(divisor);5435*/5436private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) {5437if (scale > preferredScale) {5438int diff = scale - preferredScale;5439if(diff < raise) {5440return scaledTenPow(raise - diff, qsign, preferredScale);5441} else {5442return valueOf(qsign,scale-raise);5443}5444} else {5445return scaledTenPow(raise, qsign, scale);5446}5447}54485449static BigDecimal scaledTenPow(int n, int sign, int scale) {5450if (n < LONG_TEN_POWERS_TABLE.length)5451return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale);5452else {5453BigInteger unscaledVal = bigTenToThe(n);5454if(sign==-1) {5455unscaledVal = unscaledVal.negate();5456}5457return new BigDecimal(unscaledVal, INFLATED, scale, n+1);5458}5459}54605461/**5462* Calculate the quotient and remainder of dividing a negative long by5463* another long.5464*5465* @param n the numerator; must be negative5466* @param d the denominator; must not be unity5467* @return a two-element {@code long} array with the remainder and quotient in5468* the initial and final elements, respectively5469*/5470private static long[] divRemNegativeLong(long n, long d) {5471assert n < 0 : "Non-negative numerator " + n;5472assert d != 1 : "Unity denominator";54735474// Approximate the quotient and remainder5475long q = (n >>> 1) / (d >>> 1);5476long r = n - q * d;54775478// Correct the approximation5479while (r < 0) {5480r += d;5481q--;5482}5483while (r >= d) {5484r -= d;5485q++;5486}54875488// n - q*d == r && 0 <= r < d, hence we're done.5489return new long[] {r, q};5490}54915492private static long make64(long hi, long lo) {5493return hi<<32 | lo;5494}54955496private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) {5497long tmp = u0 - q0*v0;5498return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK);5499}55005501private static boolean unsignedLongCompare(long one, long two) {5502return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);5503}55045505private static boolean unsignedLongCompareEq(long one, long two) {5506return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE);5507}550855095510// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5511private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) {5512// assert xs!=0 && ys!=05513int sdiff = xscale - yscale;5514if (sdiff != 0) {5515if (sdiff < 0) {5516xs = longMultiplyPowerTen(xs, -sdiff);5517} else { // sdiff > 05518ys = longMultiplyPowerTen(ys, sdiff);5519}5520}5521if (xs != INFLATED)5522return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;5523else5524return 1;5525}55265527// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5528private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) {5529// assert "ys can't be represented as long"5530if (xs == 0)5531return -1;5532int sdiff = xscale - yscale;5533if (sdiff < 0) {5534if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) {5535return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);5536}5537}5538return -1;5539}55405541// Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...]5542private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) {5543int sdiff = xscale - yscale;5544if (sdiff < 0) {5545return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys);5546} else { // sdiff >= 05547return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff));5548}5549}55505551private static long multiply(long x, long y){5552long product = x * y;5553long ax = Math.abs(x);5554long ay = Math.abs(y);5555if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){5556return product;5557}5558return INFLATED;5559}55605561private static BigDecimal multiply(long x, long y, int scale) {5562long product = multiply(x, y);5563if(product!=INFLATED) {5564return valueOf(product,scale);5565}5566return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0);5567}55685569private static BigDecimal multiply(long x, BigInteger y, int scale) {5570if(x==0) {5571return zeroValueOf(scale);5572}5573return new BigDecimal(y.multiply(x),INFLATED,scale,0);5574}55755576private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) {5577return new BigDecimal(x.multiply(y),INFLATED,scale,0);5578}55795580/**5581* Multiplies two long values and rounds according {@code MathContext}5582*/5583private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {5584long product = multiply(x, y);5585if(product!=INFLATED) {5586return doRound(product, scale, mc);5587}5588// attempt to do it in 128 bits5589int rsign = 1;5590if(x < 0) {5591x = -x;5592rsign = -1;5593}5594if(y < 0) {5595y = -y;5596rsign *= -1;5597}5598// multiply dividend0 * dividend15599long m0_hi = x >>> 32;5600long m0_lo = x & LONG_MASK;5601long m1_hi = y >>> 32;5602long m1_lo = y & LONG_MASK;5603product = m0_lo * m1_lo;5604long m0 = product & LONG_MASK;5605long m1 = product >>> 32;5606product = m0_hi * m1_lo + m1;5607m1 = product & LONG_MASK;5608long m2 = product >>> 32;5609product = m0_lo * m1_hi + m1;5610m1 = product & LONG_MASK;5611m2 += product >>> 32;5612long m3 = m2>>>32;5613m2 &= LONG_MASK;5614product = m0_hi*m1_hi + m2;5615m2 = product & LONG_MASK;5616m3 = ((product>>>32) + m3) & LONG_MASK;5617final long mHi = make64(m3,m2);5618final long mLo = make64(m1,m0);5619BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);5620if(res!=null) {5621return res;5622}5623res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);5624return doRound(res,mc);5625}56265627private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) {5628if(x==0) {5629return zeroValueOf(scale);5630}5631return doRound(y.multiply(x), scale, mc);5632}56335634private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) {5635return doRound(x.multiply(y), scale, mc);5636}56375638/**5639* rounds 128-bit value according {@code MathContext}5640* returns null if result can't be repsented as compact BigDecimal.5641*/5642private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {5643int mcp = mc.precision;5644int drop;5645BigDecimal res = null;5646if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {5647scale = checkScaleNonZero((long)scale - drop);5648res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);5649}5650if(res!=null) {5651return doRound(res,mc);5652}5653return null;5654}56555656private static final long[][] LONGLONG_TEN_POWERS_TABLE = {5657{ 0L, 0x8AC7230489E80000L }, //10^195658{ 0x5L, 0x6bc75e2d63100000L }, //10^205659{ 0x36L, 0x35c9adc5dea00000L }, //10^215660{ 0x21eL, 0x19e0c9bab2400000L }, //10^225661{ 0x152dL, 0x02c7e14af6800000L }, //10^235662{ 0xd3c2L, 0x1bcecceda1000000L }, //10^245663{ 0x84595L, 0x161401484a000000L }, //10^255664{ 0x52b7d2L, 0xdcc80cd2e4000000L }, //10^265665{ 0x33b2e3cL, 0x9fd0803ce8000000L }, //10^275666{ 0x204fce5eL, 0x3e25026110000000L }, //10^285667{ 0x1431e0faeL, 0x6d7217caa0000000L }, //10^295668{ 0xc9f2c9cd0L, 0x4674edea40000000L }, //10^305669{ 0x7e37be2022L, 0xc0914b2680000000L }, //10^315670{ 0x4ee2d6d415bL, 0x85acef8100000000L }, //10^325671{ 0x314dc6448d93L, 0x38c15b0a00000000L }, //10^335672{ 0x1ed09bead87c0L, 0x378d8e6400000000L }, //10^345673{ 0x13426172c74d82L, 0x2b878fe800000000L }, //10^355674{ 0xc097ce7bc90715L, 0xb34b9f1000000000L }, //10^365675{ 0x785ee10d5da46d9L, 0x00f436a000000000L }, //10^375676{ 0x4b3b4ca85a86c47aL, 0x098a224000000000L }, //10^385677};56785679/*5680* returns precision of 128-bit value5681*/5682private static int precision(long hi, long lo){5683if(hi==0) {5684if(lo>=0) {5685return longDigitLength(lo);5686}5687return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19;5688// 0x8AC7230489E80000L = unsigned 2^195689}5690int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12;5691int idx = r-19;5692return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo,5693LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1;5694}56955696/*5697* returns true if 128 bit number <hi0,lo0> is less than <hi1,lo1>5698* hi0 & hi1 should be non-negative5699*/5700private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) {5701if(hi0!=hi1) {5702return hi0<hi1;5703}5704return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE);5705}57065707private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {5708if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5709int newScale = scale + divisorScale;5710int raise = newScale - dividendScale;5711if(raise<LONG_TEN_POWERS_TABLE.length) {5712long xs = dividend;5713if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) {5714return divideAndRound(xs, divisor, scale, roundingMode, scale);5715}5716BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale);5717if(q!=null) {5718return q;5719}5720}5721BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5722return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5723} else {5724int newScale = checkScale(divisor,(long)dividendScale - scale);5725int raise = newScale - divisorScale;5726if(raise<LONG_TEN_POWERS_TABLE.length) {5727long ys = divisor;5728if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {5729return divideAndRound(dividend, ys, scale, roundingMode, scale);5730}5731}5732BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5733return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);5734}5735}57365737private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) {5738if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5739int newScale = scale + divisorScale;5740int raise = newScale - dividendScale;5741BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5742return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5743} else {5744int newScale = checkScale(divisor,(long)dividendScale - scale);5745int raise = newScale - divisorScale;5746if(raise<LONG_TEN_POWERS_TABLE.length) {5747long ys = divisor;5748if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) {5749return divideAndRound(dividend, ys, scale, roundingMode, scale);5750}5751}5752BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5753return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);5754}5755}57565757private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {5758if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5759int newScale = scale + divisorScale;5760int raise = newScale - dividendScale;5761BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5762return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5763} else {5764int newScale = checkScale(divisor,(long)dividendScale - scale);5765int raise = newScale - divisorScale;5766BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5767return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale);5768}5769}57705771private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) {5772if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) {5773int newScale = scale + divisorScale;5774int raise = newScale - dividendScale;5775BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise);5776return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale);5777} else {5778int newScale = checkScale(divisor,(long)dividendScale - scale);5779int raise = newScale - divisorScale;5780BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise);5781return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale);5782}5783}57845785}578657875788