Source Code Cross Referenced for BigDecimal.java in  » 6.0-JDK-Core » math » java » math » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » math » java.math 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001        /*
0002         * Portions Copyright 1996-2007 Sun Microsystems, Inc.  All Rights Reserved.
0003         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0004         * 
0005         * This code is free software; you can redistribute it and/or modify it
0006         * under the terms of the GNU General Public License version 2 only, as
0007         * published by the Free Software Foundation.  Sun designates this
0008         * particular file as subject to the "Classpath" exception as provided
0009         * by Sun in the LICENSE file that accompanied this code.
0010         *  
0011         * This code is distributed in the hope that it will be useful, but WITHOUT
0012         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0013         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
0014         * version 2 for more details (a copy is included in the LICENSE file that
0015         * accompanied this code).
0016         *  
0017         * You should have received a copy of the GNU General Public License version
0018         * 2 along with this work; if not, write to the Free Software Foundation,
0019         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0020         *  
0021         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0022         * CA 95054 USA or visit www.sun.com if you need additional information or
0023         * have any questions.
0024         */
0025
0026        /*
0027         * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
0028         */
0029
0030        package java.math;
0031
0032        /**
0033         * Immutable, arbitrary-precision signed decimal numbers.  A
0034         * {@code BigDecimal} consists of an arbitrary precision integer
0035         * <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  If zero
0036         * or positive, the scale is the number of digits to the right of the
0037         * decimal point.  If negative, the unscaled value of the number is
0038         * multiplied by ten to the power of the negation of the scale.  The
0039         * value of the number represented by the {@code BigDecimal} is
0040         * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
0041         * 
0042         * <p>The {@code BigDecimal} class provides operations for
0043         * arithmetic, scale manipulation, rounding, comparison, hashing, and
0044         * format conversion.  The {@link #toString} method provides a
0045         * canonical representation of a {@code BigDecimal}.
0046         * 
0047         * <p>The {@code BigDecimal} class gives its user complete control
0048         * over rounding behavior.  If no rounding mode is specified and the
0049         * exact result cannot be represented, an exception is thrown;
0050         * otherwise, calculations can be carried out to a chosen precision
0051         * and rounding mode by supplying an appropriate {@link MathContext}
0052         * object to the operation.  In either case, eight <em>rounding
0053         * modes</em> are provided for the control of rounding.  Using the
0054         * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
0055         * represent rounding mode is largely obsolete; the enumeration values
0056         * of the {@code RoundingMode} {@code enum}, (such as {@link
0057         * RoundingMode#HALF_UP}) should be used instead.
0058         * 
0059         * <p>When a {@code MathContext} object is supplied with a precision
0060         * setting of 0 (for example, {@link MathContext#UNLIMITED}),
0061         * arithmetic operations are exact, as are the arithmetic methods
0062         * which take no {@code MathContext} object.  (This is the only
0063         * behavior that was supported in releases prior to 5.)  As a
0064         * corollary of computing the exact result, the rounding mode setting
0065         * of a {@code MathContext} object with a precision setting of 0 is
0066         * not used and thus irrelevant.  In the case of divide, the exact
0067         * quotient could have an infinitely long decimal expansion; for
0068         * example, 1 divided by 3.  If the quotient has a nonterminating
0069         * decimal expansion and the operation is specified to return an exact
0070         * result, an {@code ArithmeticException} is thrown.  Otherwise, the
0071         * exact result of the division is returned, as done for other
0072         * operations.
0073         *
0074         * <p>When the precision setting is not 0, the rules of
0075         * {@code BigDecimal} arithmetic are broadly compatible with selected
0076         * modes of operation of the arithmetic defined in ANSI X3.274-1996
0077         * and ANSI X3.274-1996/AM 1-2000 (section 7.4).  Unlike those
0078         * standards, {@code BigDecimal} includes many rounding modes, which
0079         * were mandatory for division in {@code BigDecimal} releases prior
0080         * to 5.  Any conflicts between these ANSI standards and the
0081         * {@code BigDecimal} specification are resolved in favor of
0082         * {@code BigDecimal}.  
0083         *
0084         * <p>Since the same numerical value can have different
0085         * representations (with different scales), the rules of arithmetic
0086         * and rounding must specify both the numerical result and the scale
0087         * used in the result's representation.
0088         *
0089         *
0090         * <p>In general the rounding modes and precision setting determine
0091         * how operations return results with a limited number of digits when
0092         * the exact result has more digits (perhaps infinitely many in the
0093         * case of division) than the number of digits returned.
0094         *
0095         * First, the
0096         * total number of digits to return is specified by the
0097         * {@code MathContext}'s {@code precision} setting; this determines
0098         * the result's <i>precision</i>.  The digit count starts from the
0099         * leftmost nonzero digit of the exact result.  The rounding mode
0100         * determines how any discarded trailing digits affect the returned
0101         * result.
0102         *
0103         * <p>For all arithmetic operators , the operation is carried out as
0104         * though an exact intermediate result were first calculated and then
0105         * rounded to the number of digits specified by the precision setting
0106         * (if necessary), using the selected rounding mode.  If the exact
0107         * result is not returned, some digit positions of the exact result
0108         * are discarded.  When rounding increases the magnitude of the
0109         * returned result, it is possible for a new digit position to be
0110         * created by a carry propagating to a leading {@literal "9"} digit.
0111         * For example, rounding the value 999.9 to three digits rounding up
0112         * would be numerically equal to one thousand, represented as
0113         * 100&times;10<sup>1</sup>.  In such cases, the new {@literal "1"} is
0114         * the leading digit position of the returned result.
0115         *
0116         * <p>Besides a logical exact result, each arithmetic operation has a
0117         * preferred scale for representing a result.  The preferred
0118         * scale for each operation is listed in the table below.
0119         *
0120         * <table border>
0121         * <caption top><h3>Preferred Scales for Results of Arithmetic Operations
0122         * </h3></caption>
0123         * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
0124         * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
0125         * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
0126         * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
0127         * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
0128         * </table>
0129         *
0130         * These scales are the ones used by the methods which return exact
0131         * arithmetic results; except that an exact divide may have to use a
0132         * larger scale since the exact result may have more digits.  For
0133         * example, {@code 1/32} is {@code 0.03125}.
0134         *
0135         * <p>Before rounding, the scale of the logical exact intermediate
0136         * result is the preferred scale for that operation.  If the exact
0137         * numerical result cannot be represented in {@code precision}
0138         * digits, rounding selects the set of digits to return and the scale
0139         * of the result is reduced from the scale of the intermediate result
0140         * to the least scale which can represent the {@code precision}
0141         * digits actually returned.  If the exact result can be represented
0142         * with at most {@code precision} digits, the representation
0143         * of the result with the scale closest to the preferred scale is
0144         * returned.  In particular, an exactly representable quotient may be
0145         * represented in fewer than {@code precision} digits by removing
0146         * trailing zeros and decreasing the scale.  For example, rounding to
0147         * three digits using the {@linkplain RoundingMode#FLOOR floor}
0148         * rounding mode, <br>
0149         *
0150         * {@code 19/100 = 0.19   // integer=19,  scale=2} <br>
0151         *
0152         * but<br>
0153         *
0154         * {@code 21/110 = 0.190  // integer=190, scale=3} <br>
0155         *
0156         * <p>Note that for add, subtract, and multiply, the reduction in
0157         * scale will equal the number of digit positions of the exact result
0158         * which are discarded. If the rounding causes a carry propagation to
0159         * create a new high-order digit position, an additional digit of the
0160         * result is discarded than when no new digit position is created.
0161         *
0162         * <p>Other methods may have slightly different rounding semantics.
0163         * For example, the result of the {@code pow} method using the
0164         * {@linkplain #pow(int, MathContext) specified algorithm} can
0165         * occasionally differ from the rounded mathematical result by more
0166         * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
0167         *
0168         * <p>Two types of operations are provided for manipulating the scale
0169         * of a {@code BigDecimal}: scaling/rounding operations and decimal
0170         * point motion operations.  Scaling/rounding operations ({@link
0171         * #setScale setScale} and {@link #round round}) return a
0172         * {@code BigDecimal} whose value is approximately (or exactly) equal
0173         * to that of the operand, but whose scale or precision is the
0174         * specified value; that is, they increase or decrease the precision
0175         * of the stored number with minimal effect on its value.  Decimal
0176         * point motion operations ({@link #movePointLeft movePointLeft} and
0177         * {@link #movePointRight movePointRight}) return a
0178         * {@code BigDecimal} created from the operand by moving the decimal
0179         * point a specified distance in the specified direction.
0180         * 
0181         * <p>For the sake of brevity and clarity, pseudo-code is used
0182         * throughout the descriptions of {@code BigDecimal} methods.  The
0183         * pseudo-code expression {@code (i + j)} is shorthand for "a
0184         * {@code BigDecimal} whose value is that of the {@code BigDecimal}
0185         * {@code i} added to that of the {@code BigDecimal}
0186         * {@code j}." The pseudo-code expression {@code (i == j)} is
0187         * shorthand for "{@code true} if and only if the
0188         * {@code BigDecimal} {@code i} represents the same value as the
0189         * {@code BigDecimal} {@code j}." Other pseudo-code expressions
0190         * are interpreted similarly.  Square brackets are used to represent
0191         * the particular {@code BigInteger} and scale pair defining a
0192         * {@code BigDecimal} value; for example [19, 2] is the
0193         * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
0194         *
0195         * <p>Note: care should be exercised if {@code BigDecimal} objects
0196         * are used as keys in a {@link java.util.SortedMap SortedMap} or
0197         * elements in a {@link java.util.SortedSet SortedSet} since
0198         * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
0199         * with equals</i>.  See {@link Comparable}, {@link
0200         * java.util.SortedMap} or {@link java.util.SortedSet} for more
0201         * information.
0202         * 
0203         * <p>All methods and constructors for this class throw
0204         * {@code NullPointerException} when passed a {@code null} object
0205         * reference for any input parameter.
0206         *
0207         * @see     BigInteger
0208         * @see     MathContext
0209         * @see     RoundingMode
0210         * @see     java.util.SortedMap
0211         * @see     java.util.SortedSet
0212         * @author  Josh Bloch
0213         * @author  Mike Cowlishaw
0214         * @author  Joseph D. Darcy
0215         */
0216        public class BigDecimal extends Number implements 
0217                Comparable<BigDecimal> {
0218            /**
0219             * The unscaled value of this BigDecimal, as returned by {@link
0220             * #unscaledValue}.
0221             *
0222             * @serial
0223             * @see #unscaledValue
0224             */
0225            private volatile BigInteger intVal;
0226
0227            /**
0228             * The scale of this BigDecimal, as returned by {@link #scale}.
0229             *
0230             * @serial
0231             * @see #scale
0232             */
0233            private int scale = 0; // Note: this may have any value, so
0234            // calculations must be done in longs
0235            /**
0236             * The number of decimal digits in this BigDecimal, or 0 if the
0237             * number of digits are not known (lookaside information).  If
0238             * nonzero, the value is guaranteed correct.  Use the precision()
0239             * method to obtain and set the value if it might be 0.  This
0240             * field is mutable until set nonzero.
0241             *
0242             * @since  1.5
0243             */
0244            private volatile transient int precision = 0;
0245
0246            /**
0247             * Used to store the canonical string representation, if computed.
0248             */
0249            private volatile transient String stringCache = null;
0250
0251            /**
0252             * Sentinel value for {@link #intCompact} indicating the
0253             * significand information is only available from {@code intVal}.
0254             */
0255            private static final long INFLATED = Long.MIN_VALUE;
0256
0257            /**
0258             * If the absolute value of the significand of this BigDecimal is
0259             * less than or equal to {@code Long.MAX_VALUE}, the value can be
0260             * compactly stored in this field and used in computations.
0261             */
0262            private transient long intCompact = INFLATED;
0263
0264            // All 18-digit base ten strings fit into a long; not all 19-digit
0265            // strings will
0266            private static final int MAX_COMPACT_DIGITS = 18;
0267
0268            private static final int MAX_BIGINT_BITS = 62;
0269
0270            /* Appease the serialization gods */
0271            private static final long serialVersionUID = 6108874887143696463L;
0272
0273            // Cache of common small BigDecimal values.
0274            private static final BigDecimal zeroThroughTen[] = {
0275                    new BigDecimal(BigInteger.ZERO, 0, 0),
0276                    new BigDecimal(BigInteger.ONE, 1, 0),
0277                    new BigDecimal(BigInteger.valueOf(2), 2, 0),
0278                    new BigDecimal(BigInteger.valueOf(3), 3, 0),
0279                    new BigDecimal(BigInteger.valueOf(4), 4, 0),
0280                    new BigDecimal(BigInteger.valueOf(5), 5, 0),
0281                    new BigDecimal(BigInteger.valueOf(6), 6, 0),
0282                    new BigDecimal(BigInteger.valueOf(7), 7, 0),
0283                    new BigDecimal(BigInteger.valueOf(8), 8, 0),
0284                    new BigDecimal(BigInteger.valueOf(9), 9, 0),
0285                    new BigDecimal(BigInteger.TEN, 10, 0), };
0286
0287            // Constants
0288            /**
0289             * The value 0, with a scale of 0.
0290             *
0291             * @since  1.5
0292             */
0293            public static final BigDecimal ZERO = zeroThroughTen[0];
0294
0295            /**
0296             * The value 1, with a scale of 0.
0297             *
0298             * @since  1.5
0299             */
0300            public static final BigDecimal ONE = zeroThroughTen[1];
0301
0302            /**
0303             * The value 10, with a scale of 0.
0304             *
0305             * @since  1.5
0306             */
0307            public static final BigDecimal TEN = zeroThroughTen[10];
0308
0309            // Constructors
0310
0311            /**
0312             * Translates a character array representation of a
0313             * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0314             * same sequence of characters as the {@link #BigDecimal(String)}
0315             * constructor, while allowing a sub-array to be specified.
0316             * 
0317             * <p>Note that if the sequence of characters is already available
0318             * within a character array, using this constructor is faster than
0319             * converting the {@code char} array to string and using the
0320             * {@code BigDecimal(String)} constructor .
0321             *
0322             * @param  in {@code char} array that is the source of characters.
0323             * @param  offset first character in the array to inspect.
0324             * @param  len number of characters to consider.
0325             * @throws NumberFormatException if {@code in} is not a valid
0326             *         representation of a {@code BigDecimal} or the defined subarray
0327             *         is not wholly within {@code in}.
0328             * @since  1.5
0329             */
0330            public BigDecimal(char[] in, int offset, int len) {
0331                // This is the primary string to BigDecimal constructor; all
0332                // incoming strings end up here; it uses explicit (inline)
0333                // parsing for speed and generates at most one intermediate
0334                // (temporary) object (a char[] array).
0335
0336                // use array bounds checking to handle too-long, len == 0,
0337                // bad offset, etc.
0338                try {
0339                    // handle the sign
0340                    boolean isneg = false; // assume positive
0341                    if (in[offset] == '-') {
0342                        isneg = true; // leading minus means negative
0343                        offset++;
0344                        len--;
0345                    } else if (in[offset] == '+') { // leading + allowed
0346                        offset++;
0347                        len--;
0348                    }
0349
0350                    // should now be at numeric part of the significand
0351                    int dotoff = -1; // '.' offset, -1 if none
0352                    int cfirst = offset; // record start of integer
0353                    long exp = 0; // exponent
0354                    if (len > in.length) // protect against huge length
0355                        throw new NumberFormatException();
0356                    char coeff[] = new char[len]; // integer significand array
0357                    char c; // work
0358
0359                    for (; len > 0; offset++, len--) {
0360                        c = in[offset];
0361                        if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
0362                            // have digit
0363                            coeff[precision] = c;
0364                            precision++; // count of digits
0365                            continue;
0366                        }
0367                        if (c == '.') {
0368                            // have dot
0369                            if (dotoff >= 0) // two dots
0370                                throw new NumberFormatException();
0371                            dotoff = offset;
0372                            continue;
0373                        }
0374                        // exponent expected
0375                        if ((c != 'e') && (c != 'E'))
0376                            throw new NumberFormatException();
0377                        offset++;
0378                        c = in[offset];
0379                        len--;
0380                        boolean negexp = false;
0381                        // optional sign
0382                        if (c == '-' || c == '+') {
0383                            negexp = (c == '-');
0384                            offset++;
0385                            c = in[offset];
0386                            len--;
0387                        }
0388                        if (len <= 0) // no exponent digits
0389                            throw new NumberFormatException();
0390                        // skip leading zeros in the exponent 
0391                        while (len > 10 && Character.digit(c, 10) == 0) {
0392                            offset++;
0393                            c = in[offset];
0394                            len--;
0395                        }
0396                        if (len > 10) // too many nonzero exponent digits
0397                            throw new NumberFormatException();
0398                        // c now holds first digit of exponent
0399                        for (;; len--) {
0400                            int v;
0401                            if (c >= '0' && c <= '9') {
0402                                v = c - '0';
0403                            } else {
0404                                v = Character.digit(c, 10);
0405                                if (v < 0) // not a digit
0406                                    throw new NumberFormatException();
0407                            }
0408                            exp = exp * 10 + v;
0409                            if (len == 1)
0410                                break; // that was final character
0411                            offset++;
0412                            c = in[offset];
0413                        }
0414                        if (negexp) // apply sign
0415                            exp = -exp;
0416                        // Next test is required for backwards compatibility
0417                        if ((int) exp != exp) // overflow
0418                            throw new NumberFormatException();
0419                        break; // [saves a test]
0420                    }
0421                    // here when no characters left
0422                    if (precision == 0) // no digits found
0423                        throw new NumberFormatException();
0424
0425                    if (dotoff >= 0) { // had dot; set scale
0426                        scale = precision - (dotoff - cfirst);
0427                        // [cannot overflow]
0428                    }
0429                    if (exp != 0) { // had significant exponent
0430                        try {
0431                            scale = checkScale(-exp + scale); // adjust
0432                        } catch (ArithmeticException e) {
0433                            throw new NumberFormatException(
0434                                    "Scale out of range.");
0435                        }
0436                    }
0437
0438                    // Remove leading zeros from precision (digits count)
0439                    int first = 0;
0440                    for (; (coeff[first] == '0' || Character.digit(
0441                            coeff[first], 10) == 0)
0442                            && precision > 1; first++)
0443                        precision--;
0444
0445                    // Set the significand ..
0446                    // Copy significand to exact-sized array, with sign if
0447                    // negative
0448                    // Later use: BigInteger(coeff, first, precision) for
0449                    //   both cases, by allowing an extra char at the front of
0450                    //   coeff.
0451                    char quick[];
0452                    if (!isneg) {
0453                        quick = new char[precision];
0454                        System.arraycopy(coeff, first, quick, 0, precision);
0455                    } else {
0456                        quick = new char[precision + 1];
0457                        quick[0] = '-';
0458                        System.arraycopy(coeff, first, quick, 1, precision);
0459                    }
0460                    if (precision <= MAX_COMPACT_DIGITS)
0461                        intCompact = Long.parseLong(new String(quick));
0462                    else
0463                        intVal = new BigInteger(quick);
0464                    // System.out.println(" new: " +intVal+" ["+scale+"] "+precision);
0465                } catch (ArrayIndexOutOfBoundsException e) {
0466                    throw new NumberFormatException();
0467                } catch (NegativeArraySizeException e) {
0468                    throw new NumberFormatException();
0469                }
0470            }
0471
0472            /**
0473             * Translates a character array representation of a
0474             * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0475             * same sequence of characters as the {@link #BigDecimal(String)}
0476             * constructor, while allowing a sub-array to be specified and
0477             * with rounding according to the context settings.
0478             * 
0479             * <p>Note that if the sequence of characters is already available
0480             * within a character array, using this constructor is faster than
0481             * converting the {@code char} array to string and using the
0482             * {@code BigDecimal(String)} constructor .
0483             *
0484             * @param  in {@code char} array that is the source of characters.
0485             * @param  offset first character in the array to inspect.
0486             * @param  len number of characters to consider..
0487             * @param  mc the context to use.
0488             * @throws ArithmeticException if the result is inexact but the
0489             *         rounding mode is {@code UNNECESSARY}.
0490             * @throws NumberFormatException if {@code in} is not a valid
0491             *         representation of a {@code BigDecimal} or the defined subarray
0492             *         is not wholly within {@code in}.
0493             * @since  1.5
0494             */
0495            public BigDecimal(char[] in, int offset, int len, MathContext mc) {
0496                this (in, offset, len);
0497                if (mc.precision > 0)
0498                    roundThis(mc);
0499            }
0500
0501            /**
0502             * Translates a character array representation of a
0503             * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0504             * same sequence of characters as the {@link #BigDecimal(String)}
0505             * constructor.
0506             * 
0507             * <p>Note that if the sequence of characters is already available
0508             * as a character array, using this constructor is faster than
0509             * converting the {@code char} array to string and using the
0510             * {@code BigDecimal(String)} constructor .
0511             *
0512             * @param in {@code char} array that is the source of characters.
0513             * @throws NumberFormatException if {@code in} is not a valid
0514             *         representation of a {@code BigDecimal}.
0515             * @since  1.5
0516             */
0517            public BigDecimal(char[] in) {
0518                this (in, 0, in.length);
0519            }
0520
0521            /**
0522             * Translates a character array representation of a
0523             * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0524             * same sequence of characters as the {@link #BigDecimal(String)}
0525             * constructor and with rounding according to the context
0526             * settings.
0527             * 
0528             * <p>Note that if the sequence of characters is already available
0529             * as a character array, using this constructor is faster than
0530             * converting the {@code char} array to string and using the
0531             * {@code BigDecimal(String)} constructor .
0532             *
0533             * @param  in {@code char} array that is the source of characters.
0534             * @param  mc the context to use.
0535             * @throws ArithmeticException if the result is inexact but the
0536             *         rounding mode is {@code UNNECESSARY}.
0537             * @throws NumberFormatException if {@code in} is not a valid
0538             *         representation of a {@code BigDecimal}.
0539             * @since  1.5
0540             */
0541            public BigDecimal(char[] in, MathContext mc) {
0542                this (in, 0, in.length, mc);
0543            }
0544
0545            /**
0546             * Translates the string representation of a {@code BigDecimal}
0547             * into a {@code BigDecimal}.  The string representation consists
0548             * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
0549             * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
0550             * zero or more decimal digits ("the integer"), optionally
0551             * followed by a fraction, optionally followed by an exponent.
0552             * 
0553             * <p>The fraction consists of a decimal point followed by zero
0554             * or more decimal digits.  The string must contain at least one
0555             * digit in either the integer or the fraction.  The number formed
0556             * by the sign, the integer and the fraction is referred to as the
0557             * <i>significand</i>.
0558             *
0559             * <p>The exponent consists of the character {@code 'e'}
0560             * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
0561             * followed by one or more decimal digits.  The value of the
0562             * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
0563             * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
0564             *
0565             * <p>More formally, the strings this constructor accepts are
0566             * described by the following grammar:
0567             * <blockquote>
0568             * <dl>
0569             * <dt><i>BigDecimalString:</i>
0570             * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
0571             * <p>
0572             * <dt><i>Sign:</i>
0573             * <dd>{@code +}
0574             * <dd>{@code -}
0575             * <p>
0576             * <dt><i>Significand:</i>
0577             * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
0578             * <dd>{@code .} <i>FractionPart</i>
0579             * <dd><i>IntegerPart</i>
0580             * <p>
0581             * <dt><i>IntegerPart:
0582             * <dd>Digits</i>
0583             * <p>
0584             * <dt><i>FractionPart:
0585             * <dd>Digits</i>
0586             * <p>
0587             * <dt><i>Exponent:
0588             * <dd>ExponentIndicator SignedInteger</i>
0589             * <p>
0590             * <dt><i>ExponentIndicator:</i>
0591             * <dd>{@code e}
0592             * <dd>{@code E}
0593             * <p>
0594             * <dt><i>SignedInteger:
0595             * <dd>Sign<sub>opt</sub> Digits</i>
0596             * <p>
0597             * <dt><i>Digits:
0598             * <dd>Digit
0599             * <dd>Digits Digit</i>
0600             * <p>
0601             * <dt><i>Digit:</i>
0602             * <dd>any character for which {@link Character#isDigit}
0603             * returns {@code true}, including 0, 1, 2 ...
0604             * </dl>
0605             * </blockquote>
0606             *
0607             * <p>The scale of the returned {@code BigDecimal} will be the
0608             * number of digits in the fraction, or zero if the string
0609             * contains no decimal point, subject to adjustment for any
0610             * exponent; if the string contains an exponent, the exponent is
0611             * subtracted from the scale.  The value of the resulting scale
0612             * must lie between {@code Integer.MIN_VALUE} and
0613             * {@code Integer.MAX_VALUE}, inclusive.
0614             *
0615             * <p>The character-to-digit mapping is provided by {@link
0616             * java.lang.Character#digit} set to convert to radix 10.  The
0617             * String may not contain any extraneous characters (whitespace,
0618             * for example).
0619             *
0620             * <p><b>Examples:</b><br>
0621             * The value of the returned {@code BigDecimal} is equal to
0622             * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.  
0623             * For each string on the left, the resulting representation
0624             * [{@code BigInteger}, {@code scale}] is shown on the right.
0625             * <pre>
0626             * "0"            [0,0]
0627             * "0.00"         [0,2]
0628             * "123"          [123,0]
0629             * "-123"         [-123,0]
0630             * "1.23E3"       [123,-1]
0631             * "1.23E+3"      [123,-1]
0632             * "12.3E+7"      [123,-6]
0633             * "12.0"         [120,1]
0634             * "12.3"         [123,1]
0635             * "0.00123"      [123,5]
0636             * "-1.23E-12"    [-123,14]
0637             * "1234.5E-4"    [12345,5]
0638             * "0E+7"         [0,-7]
0639             * "-0"           [0,0]
0640             * </pre>
0641             *
0642             * <p>Note: For values other than {@code float} and
0643             * {@code double} NaN and &plusmn;Infinity, this constructor is
0644             * compatible with the values returned by {@link Float#toString}
0645             * and {@link Double#toString}.  This is generally the preferred
0646             * way to convert a {@code float} or {@code double} into a
0647             * BigDecimal, as it doesn't suffer from the unpredictability of
0648             * the {@link #BigDecimal(double)} constructor.
0649             *
0650             * @param val String representation of {@code BigDecimal}.
0651             *
0652             * @throws NumberFormatException if {@code val} is not a valid 
0653             *	       representation of a {@code BigDecimal}.
0654             */
0655            public BigDecimal(String val) {
0656                this (val.toCharArray(), 0, val.length());
0657            }
0658
0659            /**
0660             * Translates the string representation of a {@code BigDecimal}
0661             * into a {@code BigDecimal}, accepting the same strings as the
0662             * {@link #BigDecimal(String)} constructor, with rounding
0663             * according to the context settings.
0664             * 
0665             * @param  val string representation of a {@code BigDecimal}.
0666             * @param  mc the context to use.
0667             * @throws ArithmeticException if the result is inexact but the
0668             *         rounding mode is {@code UNNECESSARY}.
0669             * @throws NumberFormatException if {@code val} is not a valid
0670             *         representation of a BigDecimal.
0671             * @since  1.5
0672             */
0673            public BigDecimal(String val, MathContext mc) {
0674                this (val.toCharArray(), 0, val.length());
0675                if (mc.precision > 0)
0676                    roundThis(mc);
0677            }
0678
0679            /**
0680             * Translates a {@code double} into a {@code BigDecimal} which
0681             * is the exact decimal representation of the {@code double}'s
0682             * binary floating-point value.  The scale of the returned
0683             * {@code BigDecimal} is the smallest value such that
0684             * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
0685             * <p>
0686             * <b>Notes:</b>
0687             * <ol>
0688             * <li>
0689             * The results of this constructor can be somewhat unpredictable.
0690             * One might assume that writing {@code new BigDecimal(0.1)} in
0691             * Java creates a {@code BigDecimal} which is exactly equal to
0692             * 0.1 (an unscaled value of 1, with a scale of 1), but it is
0693             * actually equal to
0694             * 0.1000000000000000055511151231257827021181583404541015625.
0695             * This is because 0.1 cannot be represented exactly as a
0696             * {@code double} (or, for that matter, as a binary fraction of
0697             * any finite length).  Thus, the value that is being passed
0698             * <i>in</i> to the constructor is not exactly equal to 0.1,
0699             * appearances notwithstanding.
0700             *
0701             * <li>
0702             * The {@code String} constructor, on the other hand, is
0703             * perfectly predictable: writing {@code new BigDecimal("0.1")}
0704             * creates a {@code BigDecimal} which is <i>exactly</i> equal to
0705             * 0.1, as one would expect.  Therefore, it is generally
0706             * recommended that the {@linkplain #BigDecimal(String)
0707             * <tt>String</tt> constructor} be used in preference to this one.
0708             *
0709             * <li>
0710             * When a {@code double} must be used as a source for a
0711             * {@code BigDecimal}, note that this constructor provides an
0712             * exact conversion; it does not give the same result as
0713             * converting the {@code double} to a {@code String} using the
0714             * {@link Double#toString(double)} method and then using the
0715             * {@link #BigDecimal(String)} constructor.  To get that result,
0716             * use the {@code static} {@link #valueOf(double)} method.
0717             * </ol>
0718             *
0719             * @param val {@code double} value to be converted to 
0720             *        {@code BigDecimal}.
0721             * @throws NumberFormatException if {@code val} is infinite or NaN.
0722             */
0723            public BigDecimal(double val) {
0724                if (Double.isInfinite(val) || Double.isNaN(val))
0725                    throw new NumberFormatException("Infinite or NaN");
0726
0727                // Translate the double into sign, exponent and significand, according
0728                // to the formulae in JLS, Section 20.10.22.
0729                long valBits = Double.doubleToLongBits(val);
0730                int sign = ((valBits >> 63) == 0 ? 1 : -1);
0731                int exponent = (int) ((valBits >> 52) & 0x7ffL);
0732                long significand = (exponent == 0 ? (valBits & ((1L << 52) - 1)) << 1
0733                        : (valBits & ((1L << 52) - 1)) | (1L << 52));
0734                exponent -= 1075;
0735                // At this point, val == sign * significand * 2**exponent.
0736
0737                /*
0738                 * Special case zero to supress nonterminating normalization
0739                 * and bogus scale calculation.
0740                 */
0741                if (significand == 0) {
0742                    intVal = BigInteger.ZERO;
0743                    intCompact = 0;
0744                    precision = 1;
0745                    return;
0746                }
0747
0748                // Normalize
0749                while ((significand & 1) == 0) { //  i.e., significand is even
0750                    significand >>= 1;
0751                    exponent++;
0752                }
0753
0754                // Calculate intVal and scale
0755                intVal = BigInteger.valueOf(sign * significand);
0756                if (exponent < 0) {
0757                    intVal = intVal.multiply(BigInteger.valueOf(5).pow(
0758                            -exponent));
0759                    scale = -exponent;
0760                } else if (exponent > 0) {
0761                    intVal = intVal.multiply(BigInteger.valueOf(2)
0762                            .pow(exponent));
0763                }
0764                if (intVal.bitLength() <= MAX_BIGINT_BITS) {
0765                    intCompact = intVal.longValue();
0766                }
0767            }
0768
0769            /**
0770             * Translates a {@code double} into a {@code BigDecimal}, with
0771             * rounding according to the context settings.  The scale of the
0772             * {@code BigDecimal} is the smallest value such that
0773             * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
0774             * 
0775             * <p>The results of this constructor can be somewhat unpredictable
0776             * and its use is generally not recommended; see the notes under
0777             * the {@link #BigDecimal(double)} constructor.
0778             *
0779             * @param  val {@code double} value to be converted to 
0780             *         {@code BigDecimal}.
0781             * @param  mc the context to use.
0782             * @throws ArithmeticException if the result is inexact but the
0783             *         RoundingMode is UNNECESSARY.
0784             * @throws NumberFormatException if {@code val} is infinite or NaN.
0785             * @since  1.5
0786             */
0787            public BigDecimal(double val, MathContext mc) {
0788                this (val);
0789                if (mc.precision > 0)
0790                    roundThis(mc);
0791            }
0792
0793            /**
0794             * Translates a {@code BigInteger} into a {@code BigDecimal}.
0795             * The scale of the {@code BigDecimal} is zero.
0796             *
0797             * @param val {@code BigInteger} value to be converted to
0798             *            {@code BigDecimal}.
0799             */
0800            public BigDecimal(BigInteger val) {
0801                intVal = val;
0802                if (val.bitLength() <= MAX_BIGINT_BITS) {
0803                    intCompact = val.longValue();
0804                }
0805            }
0806
0807            /**
0808             * Translates a {@code BigInteger} into a {@code BigDecimal}
0809             * rounding according to the context settings.  The scale of the
0810             * {@code BigDecimal} is zero.
0811             * 
0812             * @param val {@code BigInteger} value to be converted to
0813             *            {@code BigDecimal}.
0814             * @param  mc the context to use.
0815             * @throws ArithmeticException if the result is inexact but the
0816             *         rounding mode is {@code UNNECESSARY}.
0817             * @since  1.5
0818             */
0819            public BigDecimal(BigInteger val, MathContext mc) {
0820                intVal = val;
0821                if (mc.precision > 0)
0822                    roundThis(mc);
0823            }
0824
0825            /**
0826             * Translates a {@code BigInteger} unscaled value and an
0827             * {@code int} scale into a {@code BigDecimal}.  The value of
0828             * the {@code BigDecimal} is
0829             * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
0830             *
0831             * @param unscaledVal unscaled value of the {@code BigDecimal}.
0832             * @param scale scale of the {@code BigDecimal}.
0833             */
0834            public BigDecimal(BigInteger unscaledVal, int scale) {
0835                // Negative scales are now allowed
0836                intVal = unscaledVal;
0837                this .scale = scale;
0838                if (unscaledVal.bitLength() <= MAX_BIGINT_BITS) {
0839                    intCompact = unscaledVal.longValue();
0840                }
0841            }
0842
0843            /**
0844             * Translates a {@code BigInteger} unscaled value and an
0845             * {@code int} scale into a {@code BigDecimal}, with rounding
0846             * according to the context settings.  The value of the
0847             * {@code BigDecimal} is <tt>(unscaledVal &times;
0848             * 10<sup>-scale</sup>)</tt>, rounded according to the
0849             * {@code precision} and rounding mode settings.
0850             *
0851             * @param  unscaledVal unscaled value of the {@code BigDecimal}.
0852             * @param  scale scale of the {@code BigDecimal}.
0853             * @param  mc the context to use.
0854             * @throws ArithmeticException if the result is inexact but the
0855             *         rounding mode is {@code UNNECESSARY}.
0856             * @since  1.5
0857             */
0858            public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
0859                intVal = unscaledVal;
0860                this .scale = scale;
0861                if (mc.precision > 0)
0862                    roundThis(mc);
0863            }
0864
0865            /**
0866             * Translates an {@code int} into a {@code BigDecimal}.  The
0867             * scale of the {@code BigDecimal} is zero.
0868             *
0869             * @param val {@code int} value to be converted to
0870             *            {@code BigDecimal}.
0871             * @since  1.5
0872             */
0873            public BigDecimal(int val) {
0874                intCompact = val;
0875            }
0876
0877            /**
0878             * Translates an {@code int} into a {@code BigDecimal}, with
0879             * rounding according to the context settings.  The scale of the
0880             * {@code BigDecimal}, before any rounding, is zero.
0881             * 
0882             * @param  val {@code int} value to be converted to {@code BigDecimal}.
0883             * @param  mc the context to use.
0884             * @throws ArithmeticException if the result is inexact but the
0885             *         rounding mode is {@code UNNECESSARY}.
0886             * @since  1.5
0887             */
0888            public BigDecimal(int val, MathContext mc) {
0889                intCompact = val;
0890                if (mc.precision > 0)
0891                    roundThis(mc);
0892            }
0893
0894            /**
0895             * Translates a {@code long} into a {@code BigDecimal}.  The
0896             * scale of the {@code BigDecimal} is zero.
0897             *
0898             * @param val {@code long} value to be converted to {@code BigDecimal}.
0899             * @since  1.5
0900             */
0901            public BigDecimal(long val) {
0902                if (compactLong(val))
0903                    intCompact = val;
0904                else
0905                    intVal = BigInteger.valueOf(val);
0906            }
0907
0908            /**
0909             * Translates a {@code long} into a {@code BigDecimal}, with
0910             * rounding according to the context settings.  The scale of the
0911             * {@code BigDecimal}, before any rounding, is zero.
0912             * 
0913             * @param  val {@code long} value to be converted to {@code BigDecimal}.
0914             * @param  mc the context to use.
0915             * @throws ArithmeticException if the result is inexact but the
0916             *         rounding mode is {@code UNNECESSARY}.
0917             * @since  1.5
0918             */
0919            public BigDecimal(long val, MathContext mc) {
0920                if (compactLong(val))
0921                    intCompact = val;
0922                else
0923                    intVal = BigInteger.valueOf(val);
0924                if (mc.precision > 0)
0925                    roundThis(mc);
0926            }
0927
0928            /**
0929             * Trusted internal constructor
0930             */
0931            private BigDecimal(long val, int scale) {
0932                this .intCompact = val;
0933                this .scale = scale;
0934            }
0935
0936            /**
0937             * Trusted internal constructor
0938             */
0939            private BigDecimal(BigInteger intVal, long val, int scale) {
0940                this .intVal = intVal;
0941                this .intCompact = val;
0942                this .scale = scale;
0943            }
0944
0945            // Static Factory Methods
0946
0947            /**
0948             * Translates a {@code long} unscaled value and an
0949             * {@code int} scale into a {@code BigDecimal}.  This
0950             * {@literal "static factory method"} is provided in preference to
0951             * a ({@code long}, {@code int}) constructor because it
0952             * allows for reuse of frequently used {@code BigDecimal} values..
0953             *
0954             * @param unscaledVal unscaled value of the {@code BigDecimal}.
0955             * @param scale scale of the {@code BigDecimal}.
0956             * @return a {@code BigDecimal} whose value is
0957             *	       <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
0958             */
0959            public static BigDecimal valueOf(long unscaledVal, int scale) {
0960                if (scale == 0 && unscaledVal >= 0 && unscaledVal <= 10) {
0961                    return zeroThroughTen[(int) unscaledVal];
0962                }
0963                if (compactLong(unscaledVal))
0964                    return new BigDecimal(unscaledVal, scale);
0965                return new BigDecimal(BigInteger.valueOf(unscaledVal), scale);
0966            }
0967
0968            /**
0969             * Translates a {@code long} value into a {@code BigDecimal}
0970             * with a scale of zero.  This {@literal "static factory method"}
0971             * is provided in preference to a ({@code long}) constructor
0972             * because it allows for reuse of frequently used
0973             * {@code BigDecimal} values.
0974             *
0975             * @param val value of the {@code BigDecimal}.
0976             * @return a {@code BigDecimal} whose value is {@code val}.
0977             */
0978            public static BigDecimal valueOf(long val) {
0979                return valueOf(val, 0);
0980            }
0981
0982            /**
0983             * Translates a {@code double} into a {@code BigDecimal}, using
0984             * the {@code double}'s canonical string representation provided
0985             * by the {@link Double#toString(double)} method.
0986             * 
0987             * <p><b>Note:</b> This is generally the preferred way to convert
0988             * a {@code double} (or {@code float}) into a
0989             * {@code BigDecimal}, as the value returned is equal to that
0990             * resulting from constructing a {@code BigDecimal} from the
0991             * result of using {@link Double#toString(double)}.
0992             *
0993             * @param  val {@code double} to convert to a {@code BigDecimal}.
0994             * @return a {@code BigDecimal} whose value is equal to or approximately
0995             *         equal to the value of {@code val}.
0996             * @throws NumberFormatException if {@code val} is infinite or NaN.
0997             * @since  1.5
0998             */
0999            public static BigDecimal valueOf(double val) {
1000                // Reminder: a zero double returns '0.0', so we cannot fastpath
1001                // to use the constant ZERO.  This might be important enough to
1002                // justify a factory approach, a cache, or a few private
1003                // constants, later.
1004                return new BigDecimal(Double.toString(val));
1005            }
1006
1007            // Arithmetic Operations
1008            /**
1009             * Returns a {@code BigDecimal} whose value is {@code (this +
1010             * augend)}, and whose scale is {@code max(this.scale(),
1011             * augend.scale())}.
1012             *
1013             * @param  augend value to be added to this {@code BigDecimal}.
1014             * @return {@code this + augend}
1015             */
1016            public BigDecimal add(BigDecimal augend) {
1017                BigDecimal arg[] = { this , augend };
1018                matchScale(arg);
1019
1020                long x = arg[0].intCompact;
1021                long y = arg[1].intCompact;
1022
1023                // Might be able to do a more clever check incorporating the
1024                // inflated check into the overflow computation.
1025                if (x != INFLATED && y != INFLATED) {
1026                    long sum = x + y;
1027                    /*
1028                     * If the sum is not an overflowed value, continue to use
1029                     * the compact representation.  if either of x or y is
1030                     * INFLATED, the sum should also be regarded as an
1031                     * overflow.  See "Hacker's Delight" section 2-12 for
1032                     * explanation of the overflow test.
1033                     */
1034                    if ((((sum ^ x) & (sum ^ y)) >> 63) == 0L) // not overflowed
1035                        return BigDecimal.valueOf(sum, arg[0].scale);
1036                }
1037                return new BigDecimal(arg[0].inflate().intVal.add(arg[1]
1038                        .inflate().intVal), arg[0].scale);
1039            }
1040
1041            /**
1042             * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1043             * with rounding according to the context settings.
1044             *
1045             * If either number is zero and the precision setting is nonzero then
1046             * the other number, rounded if necessary, is used as the result.
1047             *
1048             * @param  augend value to be added to this {@code BigDecimal}.
1049             * @param  mc the context to use.
1050             * @return {@code this + augend}, rounded as necessary.
1051             * @throws ArithmeticException if the result is inexact but the
1052             *         rounding mode is {@code UNNECESSARY}.
1053             * @since  1.5
1054             */
1055            public BigDecimal add(BigDecimal augend, MathContext mc) {
1056                if (mc.precision == 0)
1057                    return add(augend);
1058                BigDecimal lhs = this ;
1059
1060                // Could optimize if values are compact
1061                this .inflate();
1062                augend.inflate();
1063
1064                // If either number is zero then the other number, rounded and
1065                // scaled if necessary, is used as the result.
1066                {
1067                    boolean lhsIsZero = lhs.signum() == 0;
1068                    boolean augendIsZero = augend.signum() == 0;
1069
1070                    if (lhsIsZero || augendIsZero) {
1071                        int preferredScale = Math.max(lhs.scale(), augend
1072                                .scale());
1073                        BigDecimal result;
1074
1075                        // Could use a factory for zero instead of a new object
1076                        if (lhsIsZero && augendIsZero)
1077                            return new BigDecimal(BigInteger.ZERO, 0,
1078                                    preferredScale);
1079
1080                        result = lhsIsZero ? augend.doRound(mc) : lhs
1081                                .doRound(mc);
1082
1083                        if (result.scale() == preferredScale)
1084                            return result;
1085                        else if (result.scale() > preferredScale)
1086                            return new BigDecimal(result.intVal,
1087                                    result.intCompact, result.scale)
1088                                    .stripZerosToMatchScale(preferredScale);
1089                        else { // result.scale < preferredScale
1090                            int precisionDiff = mc.precision
1091                                    - result.precision();
1092                            int scaleDiff = preferredScale - result.scale();
1093
1094                            if (precisionDiff >= scaleDiff)
1095                                return result.setScale(preferredScale); // can achieve target scale
1096                            else
1097                                return result.setScale(result.scale()
1098                                        + precisionDiff);
1099                        }
1100                    }
1101                }
1102
1103                long padding = (long) lhs.scale - augend.scale;
1104                if (padding != 0) { // scales differ; alignment needed
1105                    BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1106                    matchScale(arg);
1107                    lhs = arg[0];
1108                    augend = arg[1];
1109                }
1110
1111                return new BigDecimal(lhs.inflate().intVal
1112                        .add(augend.inflate().intVal), lhs.scale).doRound(mc);
1113            }
1114
1115            /**
1116             * Returns an array of length two, the sum of whose entries is
1117             * equal to the rounded sum of the {@code BigDecimal} arguments.
1118             *
1119             * <p>If the digit positions of the arguments have a sufficient
1120             * gap between them, the value smaller in magnitude can be
1121             * condensed into a {@literal "sticky bit"} and the end result will
1122             * round the same way <em>if</em> the precision of the final
1123             * result does not include the high order digit of the small
1124             * magnitude operand.
1125             *
1126             * <p>Note that while strictly speaking this is an optimization,
1127             * it makes a much wider range of additions practical.
1128             * 
1129             * <p>This corresponds to a pre-shift operation in a fixed
1130             * precision floating-point adder; this method is complicated by
1131             * variable precision of the result as determined by the
1132             * MathContext.  A more nuanced operation could implement a
1133             * {@literal "right shift"} on the smaller magnitude operand so
1134             * that the number of digits of the smaller operand could be
1135             * reduced even though the significands partially overlapped.
1136             */
1137            private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
1138                    long padding, MathContext mc) {
1139                assert padding != 0;
1140                BigDecimal big;
1141                BigDecimal small;
1142
1143                if (padding < 0) { // lhs is big;   augend is small
1144                    big = lhs;
1145                    small = augend;
1146                } else { // lhs is small; augend is big
1147                    big = augend;
1148                    small = lhs;
1149                }
1150
1151                /*
1152                 * This is the estimated scale of an ulp of the result; it
1153                 * assumes that the result doesn't have a carry-out on a true
1154                 * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1155                 * on borrowing (e.g. 100 - 1.2 => 98.8)
1156                 */
1157                long estResultUlpScale = (long) big.scale - big.precision()
1158                        + mc.precision;
1159
1160                /*
1161                 * The low-order digit position of big is big.scale().  This
1162                 * is true regardless of whether big has a positive or
1163                 * negative scale.  The high-order digit position of small is
1164                 * small.scale - (small.precision() - 1).  To do the full
1165                 * condensation, the digit positions of big and small must be
1166                 * disjoint *and* the digit positions of small should not be
1167                 * directly visible in the result.
1168                 */
1169                long smallHighDigitPos = (long) small.scale - small.precision()
1170                        + 1;
1171                if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1172                        smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1173                    small = BigDecimal.valueOf(small.signum(),
1174                            this .checkScale(Math.max(big.scale,
1175                                    estResultUlpScale) + 3));
1176                }
1177
1178                // Since addition is symmetric, preserving input order in
1179                // returned operands doesn't matter
1180                BigDecimal[] result = { big, small };
1181                return result;
1182            }
1183
1184            /**
1185             * Returns a {@code BigDecimal} whose value is {@code (this -
1186             * subtrahend)}, and whose scale is {@code max(this.scale(),
1187             * subtrahend.scale())}.
1188             *
1189             * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1190             * @return {@code this - subtrahend}
1191             */
1192            public BigDecimal subtract(BigDecimal subtrahend) {
1193                BigDecimal arg[] = { this , subtrahend };
1194                matchScale(arg);
1195
1196                long x = arg[0].intCompact;
1197                long y = arg[1].intCompact;
1198
1199                // Might be able to do a more clever check incorporating the
1200                // inflated check into the overflow computation.
1201                if (x != INFLATED && y != INFLATED) {
1202                    long difference = x - y;
1203                    /*
1204                     * If the difference is not an overflowed value, continue
1205                     * to use the compact representation.  if either of x or y
1206                     * is INFLATED, the difference should also be regarded as
1207                     * an overflow.  See "Hacker's Delight" section 2-12 for
1208                     * explanation of the overflow test.
1209                     */
1210                    if (((x ^ y) & (difference ^ x)) >> 63 == 0L) // not overflowed
1211                        return BigDecimal.valueOf(difference, arg[0].scale);
1212                }
1213                return new BigDecimal(arg[0].inflate().intVal.subtract(arg[1]
1214                        .inflate().intVal), arg[0].scale);
1215            }
1216
1217            /**
1218             * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1219             * with rounding according to the context settings.
1220             *
1221             * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1222             * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
1223             *
1224             * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
1225             * @param  mc the context to use.
1226             * @return {@code this - subtrahend}, rounded as necessary.
1227             * @throws ArithmeticException if the result is inexact but the
1228             *         rounding mode is {@code UNNECESSARY}.
1229             * @since  1.5
1230             */
1231            public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1232                if (mc.precision == 0)
1233                    return subtract(subtrahend);
1234                // share the special rounding code in add()
1235                this .inflate();
1236                subtrahend.inflate();
1237                BigDecimal rhs = new BigDecimal(subtrahend.intVal.negate(),
1238                        subtrahend.scale);
1239                rhs.precision = subtrahend.precision;
1240                return add(rhs, mc);
1241            }
1242
1243            /**
1244             * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1245             * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1246             * multiplicand.scale())}.
1247             *
1248             * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1249             * @return {@code this * multiplicand}
1250             */
1251            public BigDecimal multiply(BigDecimal multiplicand) {
1252                long x = this .intCompact;
1253                long y = multiplicand.intCompact;
1254                int productScale = checkScale((long) scale + multiplicand.scale);
1255
1256                // Might be able to do a more clever check incorporating the
1257                // inflated check into the overflow computation.
1258                if (x != INFLATED && y != INFLATED) {
1259                    /*
1260                     * If the product is not an overflowed value, continue
1261                     * to use the compact representation.  if either of x or y
1262                     * is INFLATED, the product should also be regarded as
1263                     * an overflow.  See "Hacker's Delight" section 2-12 for
1264                     * explanation of the overflow test.
1265                     */
1266                    long product = x * y;
1267                    if (!(y != 0L && product / y != x)) // not overflowed
1268                        return BigDecimal.valueOf(product, productScale);
1269                }
1270
1271                BigDecimal result = new BigDecimal(this .inflate().intVal
1272                        .multiply(multiplicand.inflate().intVal), productScale);
1273                return result;
1274            }
1275
1276            /**
1277             * Returns a {@code BigDecimal} whose value is <tt>(this &times;
1278             * multiplicand)</tt>, with rounding according to the context settings.
1279             *
1280             * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
1281             * @param  mc the context to use.
1282             * @return {@code this * multiplicand}, rounded as necessary.
1283             * @throws ArithmeticException if the result is inexact but the
1284             *         rounding mode is {@code UNNECESSARY}.
1285             * @since  1.5
1286             */
1287            public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1288                if (mc.precision == 0)
1289                    return multiply(multiplicand);
1290                BigDecimal lhs = this ;
1291                return lhs.inflate().multiply(multiplicand.inflate()).doRound(
1292                        mc);
1293            }
1294
1295            /**
1296             * Returns a {@code BigDecimal} whose value is {@code (this /
1297             * divisor)}, and whose scale is as specified.  If rounding must
1298             * be performed to generate a result with the specified scale, the
1299             * specified rounding mode is applied.
1300             * 
1301             * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1302             * should be used in preference to this legacy method.
1303             * 
1304             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1305             * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1306             * @param  roundingMode rounding mode to apply.
1307             * @return {@code this / divisor}
1308             * @throws ArithmeticException if {@code divisor} is zero,
1309             *         {@code roundingMode==ROUND_UNNECESSARY} and
1310             *         the specified scale is insufficient to represent the result
1311             *         of the division exactly.
1312             * @throws IllegalArgumentException if {@code roundingMode} does not
1313             *         represent a valid rounding mode.
1314             * @see    #ROUND_UP
1315             * @see    #ROUND_DOWN
1316             * @see    #ROUND_CEILING
1317             * @see    #ROUND_FLOOR
1318             * @see    #ROUND_HALF_UP
1319             * @see    #ROUND_HALF_DOWN
1320             * @see    #ROUND_HALF_EVEN
1321             * @see    #ROUND_UNNECESSARY
1322             */
1323            public BigDecimal divide(BigDecimal divisor, int scale,
1324                    int roundingMode) {
1325                /* 
1326                 * IMPLEMENTATION NOTE: This method *must* return a new object
1327                 * since dropDigits uses divide to generate a value whose
1328                 * scale is then modified.
1329                 */
1330                if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1331                    throw new IllegalArgumentException("Invalid rounding mode");
1332                /*
1333                 * Rescale dividend or divisor (whichever can be "upscaled" to
1334                 * produce correctly scaled quotient).
1335                 * Take care to detect out-of-range scales
1336                 */
1337                BigDecimal dividend;
1338                if (checkScale((long) scale + divisor.scale) >= this .scale) {
1339                    dividend = this .setScale(scale + divisor.scale);
1340                } else {
1341                    dividend = this ;
1342                    divisor = divisor.setScale(checkScale((long) this .scale
1343                            - scale));
1344                }
1345
1346                boolean compact = dividend.intCompact != INFLATED
1347                        && divisor.intCompact != INFLATED;
1348                long div = INFLATED;
1349                long rem = INFLATED;
1350                ;
1351                BigInteger q = null, r = null;
1352
1353                if (compact) {
1354                    div = dividend.intCompact / divisor.intCompact;
1355                    rem = dividend.intCompact % divisor.intCompact;
1356                } else {
1357                    // Do the division and return result if it's exact.
1358                    BigInteger i[] = dividend.inflate().intVal
1359                            .divideAndRemainder(divisor.inflate().intVal);
1360                    q = i[0];
1361                    r = i[1];
1362                }
1363
1364                // Check for exact result
1365                if (compact) {
1366                    if (rem == 0)
1367                        return new BigDecimal(div, scale);
1368                } else {
1369                    if (r.signum() == 0)
1370                        return new BigDecimal(q, scale);
1371                }
1372
1373                if (roundingMode == ROUND_UNNECESSARY) // Rounding prohibited
1374                    throw new ArithmeticException("Rounding necessary");
1375
1376                /* Round as appropriate */
1377                int signum = dividend.signum() * divisor.signum(); // Sign of result
1378                boolean increment;
1379                if (roundingMode == ROUND_UP) { // Away from zero
1380                    increment = true;
1381                } else if (roundingMode == ROUND_DOWN) { // Towards zero
1382                    increment = false;
1383                } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1384                    increment = (signum > 0);
1385                } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
1386                    increment = (signum < 0);
1387                } else { // Remaining modes based on nearest-neighbor determination
1388                    int cmpFracHalf;
1389                    if (compact) {
1390                        cmpFracHalf = longCompareTo(Math.abs(2 * rem), Math
1391                                .abs(divisor.intCompact));
1392                    } else {
1393                        // add(r) here is faster than multiply(2) or shiftLeft(1)
1394                        cmpFracHalf = r.add(r).abs().compareTo(
1395                                divisor.intVal.abs());
1396                    }
1397                    if (cmpFracHalf < 0) { // We're closer to higher digit
1398                        increment = false;
1399                    } else if (cmpFracHalf > 0) { // We're closer to lower digit
1400                        increment = true;
1401                    } else { // We're dead-center
1402                        if (roundingMode == ROUND_HALF_UP)
1403                            increment = true;
1404                        else if (roundingMode == ROUND_HALF_DOWN)
1405                            increment = false;
1406                        else { // roundingMode == ROUND_HALF_EVEN
1407                            if (compact)
1408                                increment = (div & 1L) != 0L;
1409                            else
1410                                increment = q.testBit(0); // true iff q is odd
1411                        }
1412                    }
1413                }
1414
1415                if (compact) {
1416                    if (increment)
1417                        div += signum; // guaranteed not to overflow
1418                    return new BigDecimal(div, scale);
1419                } else {
1420                    return (increment ? new BigDecimal(q.add(BigInteger
1421                            .valueOf(signum)), scale)
1422                            : new BigDecimal(q, scale));
1423                }
1424            }
1425
1426            /**
1427             * Returns a {@code BigDecimal} whose value is {@code (this /
1428             * divisor)}, and whose scale is as specified.  If rounding must
1429             * be performed to generate a result with the specified scale, the
1430             * specified rounding mode is applied.
1431             * 
1432             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1433             * @param  scale scale of the {@code BigDecimal} quotient to be returned.
1434             * @param  roundingMode rounding mode to apply.
1435             * @return {@code this / divisor}
1436             * @throws ArithmeticException if {@code divisor} is zero,
1437             *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1438             *         the specified scale is insufficient to represent the result
1439             *         of the division exactly.
1440             * @since 1.5
1441             */
1442            public BigDecimal divide(BigDecimal divisor, int scale,
1443                    RoundingMode roundingMode) {
1444                return divide(divisor, scale, roundingMode.oldMode);
1445            }
1446
1447            /**
1448             * Returns a {@code BigDecimal} whose value is {@code (this /
1449             * divisor)}, and whose scale is {@code this.scale()}.  If
1450             * rounding must be performed to generate a result with the given
1451             * scale, the specified rounding mode is applied.
1452             * 
1453             * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1454             * should be used in preference to this legacy method.
1455             * 
1456             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1457             * @param  roundingMode rounding mode to apply.
1458             * @return {@code this / divisor}
1459             * @throws ArithmeticException if {@code divisor==0}, or
1460             *         {@code roundingMode==ROUND_UNNECESSARY} and
1461             *         {@code this.scale()} is insufficient to represent the result
1462             *         of the division exactly.
1463             * @throws IllegalArgumentException if {@code roundingMode} does not
1464             *         represent a valid rounding mode.
1465             * @see    #ROUND_UP
1466             * @see    #ROUND_DOWN
1467             * @see    #ROUND_CEILING
1468             * @see    #ROUND_FLOOR
1469             * @see    #ROUND_HALF_UP
1470             * @see    #ROUND_HALF_DOWN
1471             * @see    #ROUND_HALF_EVEN
1472             * @see    #ROUND_UNNECESSARY
1473             */
1474            public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1475                return this .divide(divisor, scale, roundingMode);
1476            }
1477
1478            /**
1479             * Returns a {@code BigDecimal} whose value is {@code (this /
1480             * divisor)}, and whose scale is {@code this.scale()}.  If
1481             * rounding must be performed to generate a result with the given
1482             * scale, the specified rounding mode is applied.
1483             * 
1484             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1485             * @param  roundingMode rounding mode to apply.
1486             * @return {@code this / divisor}
1487             * @throws ArithmeticException if {@code divisor==0}, or
1488             *         {@code roundingMode==RoundingMode.UNNECESSARY} and
1489             *         {@code this.scale()} is insufficient to represent the result
1490             *         of the division exactly.
1491             * @since 1.5
1492             */
1493            public BigDecimal divide(BigDecimal divisor,
1494                    RoundingMode roundingMode) {
1495                return this .divide(divisor, scale, roundingMode.oldMode);
1496            }
1497
1498            /**
1499             * Returns a {@code BigDecimal} whose value is {@code (this /
1500             * divisor)}, and whose preferred scale is {@code (this.scale() -
1501             * divisor.scale())}; if the exact quotient cannot be
1502             * represented (because it has a non-terminating decimal
1503             * expansion) an {@code ArithmeticException} is thrown.
1504             *
1505             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1506             * @throws ArithmeticException if the exact quotient does not have a
1507             *         terminating decimal expansion
1508             * @return {@code this / divisor}
1509             * @since 1.5
1510             * @author Joseph D. Darcy
1511             */
1512            public BigDecimal divide(BigDecimal divisor) {
1513                /*
1514                 * Handle zero cases first.
1515                 */
1516                if (divisor.signum() == 0) { // x/0
1517                    if (this .signum() == 0) // 0/0
1518                        throw new ArithmeticException("Division undefined"); // NaN
1519                    throw new ArithmeticException("Division by zero");
1520                }
1521
1522                // Calculate preferred scale
1523                int preferredScale = (int) Math.max(Math.min((long) this 
1524                        .scale()
1525                        - divisor.scale(), Integer.MAX_VALUE),
1526                        Integer.MIN_VALUE);
1527                if (this .signum() == 0) // 0/y
1528                    return new BigDecimal(0, preferredScale);
1529                else {
1530                    this .inflate();
1531                    divisor.inflate();
1532                    /*
1533                     * If the quotient this/divisor has a terminating decimal
1534                     * expansion, the expansion can have no more than
1535                     * (a.precision() + ceil(10*b.precision)/3) digits.
1536                     * Therefore, create a MathContext object with this
1537                     * precision and do a divide with the UNNECESSARY rounding
1538                     * mode.
1539                     */
1540                    MathContext mc = new MathContext((int) Math.min(this 
1541                            .precision()
1542                            + (long) Math
1543                                    .ceil(10.0 * divisor.precision() / 3.0),
1544                            Integer.MAX_VALUE), RoundingMode.UNNECESSARY);
1545                    BigDecimal quotient;
1546                    try {
1547                        quotient = this .divide(divisor, mc);
1548                    } catch (ArithmeticException e) {
1549                        throw new ArithmeticException(
1550                                "Non-terminating decimal expansion; "
1551                                        + "no exact representable decimal result.");
1552                    }
1553
1554                    int quotientScale = quotient.scale();
1555
1556                    // divide(BigDecimal, mc) tries to adjust the quotient to
1557                    // the desired one by removing trailing zeros; since the
1558                    // exact divide method does not have an explicit digit
1559                    // limit, we can add zeros too.
1560
1561                    if (preferredScale > quotientScale)
1562                        return quotient.setScale(preferredScale);
1563
1564                    return quotient;
1565                }
1566            }
1567
1568            /**
1569             * Returns a {@code BigDecimal} whose value is {@code (this /
1570             * divisor)}, with rounding according to the context settings.
1571             *
1572             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1573             * @param  mc the context to use.
1574             * @return {@code this / divisor}, rounded as necessary.
1575             * @throws ArithmeticException if the result is inexact but the
1576             *         rounding mode is {@code UNNECESSARY} or 
1577             *         {@code mc.precision == 0} and the quotient has a 
1578             *         non-terminating decimal expansion.
1579             * @since  1.5
1580             */
1581            public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1582                if (mc.precision == 0)
1583                    return divide(divisor);
1584                BigDecimal lhs = this .inflate(); // left-hand-side
1585                BigDecimal rhs = divisor.inflate(); // right-hand-side
1586                BigDecimal result; // work
1587
1588                long preferredScale = (long) lhs.scale() - rhs.scale();
1589
1590                // Now calculate the answer.  We use the existing
1591                // divide-and-round method, but as this rounds to scale we have
1592                // to normalize the values here to achieve the desired result.
1593                // For x/y we first handle y=0 and x=0, and then normalize x and
1594                // y to give x' and y' with the following constraints:
1595                //   (a) 0.1 <= x' < 1
1596                //   (b)  x' <= y' < 10*x'
1597                // Dividing x'/y' with the required scale set to mc.precision then
1598                // will give a result in the range 0.1 to 1 rounded to exactly
1599                // the right number of digits (except in the case of a result of
1600                // 1.000... which can arise when x=y, or when rounding overflows
1601                // The 1.000... case will reduce properly to 1.
1602                if (rhs.signum() == 0) { // x/0
1603                    if (lhs.signum() == 0) // 0/0
1604                        throw new ArithmeticException("Division undefined"); // NaN
1605                    throw new ArithmeticException("Division by zero");
1606                }
1607                if (lhs.signum() == 0) // 0/y
1608                    return new BigDecimal(BigInteger.ZERO, (int) Math.max(Math
1609                            .min(preferredScale, Integer.MAX_VALUE),
1610                            Integer.MIN_VALUE));
1611
1612                BigDecimal xprime = new BigDecimal(lhs.intVal.abs(), lhs
1613                        .precision());
1614                BigDecimal yprime = new BigDecimal(rhs.intVal.abs(), rhs
1615                        .precision());
1616                // xprime and yprime are now both in range 0.1 through 0.999...
1617                if (mc.roundingMode == RoundingMode.CEILING
1618                        || mc.roundingMode == RoundingMode.FLOOR) {
1619                    // The floor (round toward negative infinity) and ceil
1620                    // (round toward positive infinity) rounding modes are not
1621                    // invariant under a sign flip.  If xprime/yprime has a
1622                    // different sign than lhs/rhs, the rounding mode must be
1623                    // changed.
1624                    if ((xprime.signum() != lhs.signum())
1625                            ^ (yprime.signum() != rhs.signum())) {
1626                        mc = new MathContext(
1627                                mc.precision,
1628                                (mc.roundingMode == RoundingMode.CEILING) ? RoundingMode.FLOOR
1629                                        : RoundingMode.CEILING);
1630                    }
1631                }
1632
1633                if (xprime.compareTo(yprime) > 0) // satisfy constraint (b)
1634                    yprime.scale -= 1; // [that is, yprime *= 10]
1635                result = xprime.divide(yprime, mc.precision,
1636                        mc.roundingMode.oldMode);
1637                // correct the scale of the result...
1638                result.scale = checkScale((long) yprime.scale - xprime.scale
1639                        - (rhs.scale - lhs.scale) + mc.precision);
1640                // apply the sign
1641                if (lhs.signum() != rhs.signum())
1642                    result = result.negate();
1643                // doRound, here, only affects 1000000000 case.
1644                result = result.doRound(mc);
1645
1646                if (result.multiply(divisor).compareTo(this ) == 0) {
1647                    // Apply preferred scale rules for exact quotients
1648                    return result.stripZerosToMatchScale(preferredScale);
1649                } else {
1650                    return result;
1651                }
1652            }
1653
1654            /**
1655             * Returns a {@code BigDecimal} whose value is the integer part
1656             * of the quotient {@code (this / divisor)} rounded down.  The
1657             * preferred scale of the result is {@code (this.scale() -
1658             * divisor.scale())}.
1659             *
1660             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1661             * @return The integer part of {@code this / divisor}.
1662             * @throws ArithmeticException if {@code divisor==0}
1663             * @since  1.5
1664             */
1665            public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1666                // Calculate preferred scale
1667                int preferredScale = (int) Math.max(Math.min((long) this 
1668                        .scale()
1669                        - divisor.scale(), Integer.MAX_VALUE),
1670                        Integer.MIN_VALUE);
1671                this .inflate();
1672                divisor.inflate();
1673                if (this .abs().compareTo(divisor.abs()) < 0) {
1674                    // much faster when this << divisor
1675                    return BigDecimal.valueOf(0, preferredScale);
1676                }
1677
1678                if (this .signum() == 0 && divisor.signum() != 0)
1679                    return this .setScale(preferredScale);
1680
1681                // Perform a divide with enough digits to round to a correct
1682                // integer value; then remove any fractional digits
1683
1684                int maxDigits = (int) Math.min(this .precision()
1685                        + (long) Math.ceil(10.0 * divisor.precision() / 3.0)
1686                        + Math.abs((long) this .scale() - divisor.scale()) + 2,
1687                        Integer.MAX_VALUE);
1688
1689                BigDecimal quotient = this .divide(divisor, new MathContext(
1690                        maxDigits, RoundingMode.DOWN));
1691                if (quotient.scale > 0) {
1692                    quotient = quotient.setScale(0, RoundingMode.DOWN)
1693                            .stripZerosToMatchScale(preferredScale);
1694                }
1695
1696                if (quotient.scale < preferredScale) {
1697                    // pad with zeros if necessary
1698                    quotient = quotient.setScale(preferredScale);
1699                }
1700
1701                return quotient;
1702            }
1703
1704            /**
1705             * Returns a {@code BigDecimal} whose value is the integer part
1706             * of {@code (this / divisor)}.  Since the integer part of the
1707             * exact quotient does not depend on the rounding mode, the
1708             * rounding mode does not affect the values returned by this
1709             * method.  The preferred scale of the result is
1710             * {@code (this.scale() - divisor.scale())}.  An
1711             * {@code ArithmeticException} is thrown if the integer part of
1712             * the exact quotient needs more than {@code mc.precision}
1713             * digits.
1714             *
1715             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1716             * @param  mc the context to use.
1717             * @return The integer part of {@code this / divisor}.
1718             * @throws ArithmeticException if {@code divisor==0}
1719             * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1720             *         requires a precision of more than {@code mc.precision} digits.
1721             * @since  1.5
1722             * @author Joseph D. Darcy
1723             */
1724            public BigDecimal divideToIntegralValue(BigDecimal divisor,
1725                    MathContext mc) {
1726                if (mc.precision == 0 || // exact result
1727                        (this .abs().compareTo(divisor.abs()) < 0)) // zero result
1728                    return divideToIntegralValue(divisor);
1729
1730                // Calculate preferred scale
1731                int preferredScale = (int) Math.max(Math.min((long) this 
1732                        .scale()
1733                        - divisor.scale(), Integer.MAX_VALUE),
1734                        Integer.MIN_VALUE);
1735
1736                /*
1737                 * Perform a normal divide to mc.precision digits.  If the
1738                 * remainder has absolute value less than the divisor, the
1739                 * integer portion of the quotient fits into mc.precision
1740                 * digits.  Next, remove any fractional digits from the
1741                 * quotient and adjust the scale to the preferred value.
1742                 */
1743                BigDecimal result = this .divide(divisor, new MathContext(
1744                        mc.precision, RoundingMode.DOWN));
1745                int resultScale = result.scale();
1746
1747                if (result.scale() < 0) {
1748                    /*
1749                     * Result is an integer. See if quotient represents the
1750                     * full integer portion of the exact quotient; if it does,
1751                     * the computed remainder will be less than the divisor.
1752                     */
1753                    BigDecimal product = result.multiply(divisor);
1754                    // If the quotient is the full integer value,
1755                    // |dividend-product| < |divisor|.
1756                    if (this .subtract(product).abs().compareTo(divisor.abs()) >= 0) {
1757                        throw new ArithmeticException("Division impossible");
1758                    }
1759                } else if (result.scale() > 0) {
1760                    /*
1761                     * Integer portion of quotient will fit into precision
1762                     * digits; recompute quotient to scale 0 to avoid double
1763                     * rounding and then try to adjust, if necessary.
1764                     */
1765                    result = result.setScale(0, RoundingMode.DOWN);
1766                }
1767                // else result.scale() == 0; 
1768
1769                int precisionDiff;
1770                if ((preferredScale > result.scale())
1771                        && (precisionDiff = mc.precision - result.precision()) > 0) {
1772                    return result.setScale(result.scale()
1773                            + Math.min(precisionDiff, preferredScale
1774                                    - result.scale));
1775                } else
1776                    return result.stripZerosToMatchScale(preferredScale);
1777            }
1778
1779            /**
1780             * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1781             * 
1782             * <p>The remainder is given by
1783             * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1784             * Note that this is not the modulo operation (the result can be
1785             * negative).
1786             *
1787             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1788             * @return {@code this % divisor}.
1789             * @throws ArithmeticException if {@code divisor==0}
1790             * @since  1.5
1791             */
1792            public BigDecimal remainder(BigDecimal divisor) {
1793                BigDecimal divrem[] = this .divideAndRemainder(divisor);
1794                return divrem[1];
1795            }
1796
1797            /**
1798             * Returns a {@code BigDecimal} whose value is {@code (this %
1799             * divisor)}, with rounding according to the context settings.
1800             * The {@code MathContext} settings affect the implicit divide
1801             * used to compute the remainder.  The remainder computation
1802             * itself is by definition exact.  Therefore, the remainder may
1803             * contain more than {@code mc.getPrecision()} digits.
1804             * 
1805             * <p>The remainder is given by
1806             * {@code this.subtract(this.divideToIntegralValue(divisor,
1807             * mc).multiply(divisor))}.  Note that this is not the modulo
1808             * operation (the result can be negative).
1809             *
1810             * @param  divisor value by which this {@code BigDecimal} is to be divided.
1811             * @param  mc the context to use.
1812             * @return {@code this % divisor}, rounded as necessary.
1813             * @throws ArithmeticException if {@code divisor==0}
1814             * @throws ArithmeticException if the result is inexact but the
1815             *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 
1816             *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 
1817             *         require a precision of more than {@code mc.precision} digits.
1818             * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1819             * @since  1.5
1820             */
1821            public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1822                BigDecimal divrem[] = this .divideAndRemainder(divisor, mc);
1823                return divrem[1];
1824            }
1825
1826            /**
1827             * Returns a two-element {@code BigDecimal} array containing the
1828             * result of {@code divideToIntegralValue} followed by the result of
1829             * {@code remainder} on the two operands.
1830             * 
1831             * <p>Note that if both the integer quotient and remainder are
1832             * needed, this method is faster than using the
1833             * {@code divideToIntegralValue} and {@code remainder} methods
1834             * separately because the division need only be carried out once.
1835             *
1836             * @param  divisor value by which this {@code BigDecimal} is to be divided, 
1837             *         and the remainder computed.
1838             * @return a two element {@code BigDecimal} array: the quotient 
1839             *         (the result of {@code divideToIntegralValue}) is the initial element 
1840             *         and the remainder is the final element.
1841             * @throws ArithmeticException if {@code divisor==0}
1842             * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1843             * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1844             * @since  1.5
1845             */
1846            public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1847                // we use the identity  x = i * y + r to determine r
1848                BigDecimal[] result = new BigDecimal[2];
1849
1850                result[0] = this .divideToIntegralValue(divisor);
1851                result[1] = this .subtract(result[0].multiply(divisor));
1852                return result;
1853            }
1854
1855            /**
1856             * Returns a two-element {@code BigDecimal} array containing the
1857             * result of {@code divideToIntegralValue} followed by the result of
1858             * {@code remainder} on the two operands calculated with rounding
1859             * according to the context settings.
1860             * 
1861             * <p>Note that if both the integer quotient and remainder are
1862             * needed, this method is faster than using the
1863             * {@code divideToIntegralValue} and {@code remainder} methods
1864             * separately because the division need only be carried out once.
1865             *
1866             * @param  divisor value by which this {@code BigDecimal} is to be divided, 
1867             *         and the remainder computed.
1868             * @param  mc the context to use.
1869             * @return a two element {@code BigDecimal} array: the quotient 
1870             *         (the result of {@code divideToIntegralValue}) is the 
1871             *         initial element and the remainder is the final element.
1872             * @throws ArithmeticException if {@code divisor==0}
1873             * @throws ArithmeticException if the result is inexact but the
1874             *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 
1875             *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 
1876             *         require a precision of more than {@code mc.precision} digits.
1877             * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1878             * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
1879             * @since  1.5
1880             */
1881            public BigDecimal[] divideAndRemainder(BigDecimal divisor,
1882                    MathContext mc) {
1883                if (mc.precision == 0)
1884                    return divideAndRemainder(divisor);
1885
1886                BigDecimal[] result = new BigDecimal[2];
1887                BigDecimal lhs = this ;
1888
1889                result[0] = lhs.divideToIntegralValue(divisor, mc);
1890                result[1] = lhs.subtract(result[0].multiply(divisor));
1891                return result;
1892            }
1893
1894            /**
1895             * Returns a {@code BigDecimal} whose value is
1896             * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
1897             * unlimited precision.
1898             * 
1899             * <p>The parameter {@code n} must be in the range 0 through
1900             * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
1901             * #ONE}.
1902             *
1903             * Note that future releases may expand the allowable exponent
1904             * range of this method.
1905             *
1906             * @param  n power to raise this {@code BigDecimal} to.
1907             * @return <tt>this<sup>n</sup></tt>
1908             * @throws ArithmeticException if {@code n} is out of range.
1909             * @since  1.5
1910             */
1911            public BigDecimal pow(int n) {
1912                if (n < 0 || n > 999999999)
1913                    throw new ArithmeticException("Invalid operation");
1914                // No need to calculate pow(n) if result will over/underflow.
1915                // Don't attempt to support "supernormal" numbers.
1916                int newScale = checkScale((long) scale * n);
1917                this .inflate();
1918                return new BigDecimal(intVal.pow(n), newScale);
1919            }
1920
1921            /**
1922             * Returns a {@code BigDecimal} whose value is
1923             * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
1924             * the core algorithm defined in ANSI standard X3.274-1996 with
1925             * rounding according to the context settings.  In general, the
1926             * returned numerical value is within two ulps of the exact
1927             * numerical value for the chosen precision.  Note that future
1928             * releases may use a different algorithm with a decreased
1929             * allowable error bound and increased allowable exponent range.
1930             *
1931             * <p>The X3.274-1996 algorithm is:
1932             *
1933             * <ul>
1934             * <li> An {@code ArithmeticException} exception is thrown if
1935             *  <ul>
1936             *    <li>{@code abs(n) > 999999999}
1937             *    <li>{@code mc.precision == 0} and {@code n < 0}
1938             *    <li>{@code mc.precision > 0} and {@code n} has more than
1939             *    {@code mc.precision} decimal digits
1940             *  </ul>
1941             *
1942             * <li> if {@code n} is zero, {@link #ONE} is returned even if
1943             * {@code this} is zero, otherwise
1944             * <ul>
1945             *   <li> if {@code n} is positive, the result is calculated via
1946             *   the repeated squaring technique into a single accumulator.
1947             *   The individual multiplications with the accumulator use the
1948             *   same math context settings as in {@code mc} except for a
1949             *   precision increased to {@code mc.precision + elength + 1}
1950             *   where {@code elength} is the number of decimal digits in
1951             *   {@code n}.
1952             *
1953             *   <li> if {@code n} is negative, the result is calculated as if
1954             *   {@code n} were positive; this value is then divided into one
1955             *   using the working precision specified above.
1956             *
1957             *   <li> The final value from either the positive or negative case
1958             *   is then rounded to the destination precision.
1959             *   </ul>
1960             * </ul>
1961             *
1962             * @param  n power to raise this {@code BigDecimal} to.
1963             * @param  mc the context to use.
1964             * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
1965             *         algorithm
1966             * @throws ArithmeticException if the result is inexact but the
1967             *         rounding mode is {@code UNNECESSARY}, or {@code n} is out 
1968             *         of range.
1969             * @since  1.5
1970             */
1971            public BigDecimal pow(int n, MathContext mc) {
1972                if (mc.precision == 0)
1973                    return pow(n);
1974                if (n < -999999999 || n > 999999999)
1975                    throw new ArithmeticException("Invalid operation");
1976                if (n == 0)
1977                    return ONE; // x**0 == 1 in X3.274
1978                this .inflate();
1979                BigDecimal lhs = this ;
1980                MathContext workmc = mc; // working settings
1981                int mag = Math.abs(n); // magnitude of n
1982                if (mc.precision > 0) {
1983
1984                    int elength = intLength(mag); // length of n in digits
1985                    if (elength > mc.precision) // X3.274 rule
1986                        throw new ArithmeticException("Invalid operation");
1987                    workmc = new MathContext(mc.precision + elength + 1,
1988                            mc.roundingMode);
1989                }
1990                // ready to carry out power calculation...
1991                BigDecimal acc = ONE; // accumulator
1992                boolean seenbit = false; // set once we've seen a 1-bit
1993                for (int i = 1;; i++) { // for each bit [top bit ignored]
1994                    mag += mag; // shift left 1 bit
1995                    if (mag < 0) { // top bit is set
1996                        seenbit = true; // OK, we're off
1997                        acc = acc.multiply(lhs, workmc); // acc=acc*x
1998                    }
1999                    if (i == 31)
2000                        break; // that was the last bit
2001                    if (seenbit)
2002                        acc = acc.multiply(acc, workmc); // acc=acc*acc [square]
2003                    // else (!seenbit) no point in squaring ONE
2004                }
2005                // if negative n, calculate the reciprocal using working precision
2006                if (n < 0) // [hence mc.precision>0]
2007                    acc = ONE.divide(acc, workmc);
2008                // round to final precision and strip zeros
2009                return acc.doRound(mc);
2010            }
2011
2012            /**
2013             * Returns a {@code BigDecimal} whose value is the absolute value
2014             * of this {@code BigDecimal}, and whose scale is
2015             * {@code this.scale()}.
2016             *
2017             * @return {@code abs(this)}
2018             */
2019            public BigDecimal abs() {
2020                return (signum() < 0 ? negate() : this );
2021            }
2022
2023            /**
2024             * Returns a {@code BigDecimal} whose value is the absolute value
2025             * of this {@code BigDecimal}, with rounding according to the
2026             * context settings.
2027             *
2028             * @param mc the context to use.
2029             * @return {@code abs(this)}, rounded as necessary.
2030             * @throws ArithmeticException if the result is inexact but the
2031             *         rounding mode is {@code UNNECESSARY}.
2032             * @since 1.5
2033             */
2034            public BigDecimal abs(MathContext mc) {
2035                return (signum() < 0 ? negate(mc) : plus(mc));
2036            }
2037
2038            /**
2039             * Returns a {@code BigDecimal} whose value is {@code (-this)},
2040             * and whose scale is {@code this.scale()}.
2041             *
2042             * @return {@code -this}.
2043             */
2044            public BigDecimal negate() {
2045                BigDecimal result;
2046                if (intCompact != INFLATED)
2047                    result = BigDecimal.valueOf(-intCompact, scale);
2048                else {
2049                    result = new BigDecimal(intVal.negate(), scale);
2050                    result.precision = precision;
2051                }
2052                return result;
2053            }
2054
2055            /**
2056             * Returns a {@code BigDecimal} whose value is {@code (-this)},
2057             * with rounding according to the context settings.
2058             *
2059             * @param mc the context to use.
2060             * @return {@code -this}, rounded as necessary.
2061             * @throws ArithmeticException if the result is inexact but the 
2062             *         rounding mode is {@code UNNECESSARY}.
2063             * @since  1.5
2064             */
2065            public BigDecimal negate(MathContext mc) {
2066                return negate().plus(mc);
2067            }
2068
2069            /**
2070             * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2071             * scale is {@code this.scale()}.
2072             * 
2073             * <p>This method, which simply returns this {@code BigDecimal}
2074             * is included for symmetry with the unary minus method {@link
2075             * #negate()}.
2076             * 
2077             * @return {@code this}.
2078             * @see #negate()
2079             * @since  1.5
2080             */
2081            public BigDecimal plus() {
2082                return this ;
2083            }
2084
2085            /**
2086             * Returns a {@code BigDecimal} whose value is {@code (+this)},
2087             * with rounding according to the context settings.
2088             * 
2089             * <p>The effect of this method is identical to that of the {@link
2090             * #round(MathContext)} method.
2091             *
2092             * @param mc the context to use.
2093             * @return {@code this}, rounded as necessary.  A zero result will
2094             *         have a scale of 0.
2095             * @throws ArithmeticException if the result is inexact but the
2096             *         rounding mode is {@code UNNECESSARY}.
2097             * @see    #round(MathContext)
2098             * @since  1.5
2099             */
2100            public BigDecimal plus(MathContext mc) {
2101                if (mc.precision == 0) // no rounding please
2102                    return this ;
2103                return this .doRound(mc);
2104            }
2105
2106            /**
2107             * Returns the signum function of this {@code BigDecimal}.
2108             *
2109             * @return -1, 0, or 1 as the value of this {@code BigDecimal} 
2110             *         is negative, zero, or positive.
2111             */
2112            public int signum() {
2113                return (intCompact != INFLATED) ? Long.signum(intCompact)
2114                        : intVal.signum();
2115            }
2116
2117            /**
2118             * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
2119             * or positive, the scale is the number of digits to the right of
2120             * the decimal point.  If negative, the unscaled value of the
2121             * number is multiplied by ten to the power of the negation of the
2122             * scale.  For example, a scale of {@code -3} means the unscaled
2123             * value is multiplied by 1000.
2124             *
2125             * @return the scale of this {@code BigDecimal}.
2126             */
2127            public int scale() {
2128                return scale;
2129            }
2130
2131            /**
2132             * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
2133             * precision is the number of digits in the unscaled value.)
2134             *
2135             * <p>The precision of a zero value is 1.
2136             *
2137             * @return the precision of this {@code BigDecimal}.
2138             * @since  1.5
2139             */
2140            public int precision() {
2141                int result = precision;
2142                if (result == 0) {
2143                    result = digitLength();
2144                    precision = result;
2145                }
2146                return result;
2147            }
2148
2149            /**
2150             * Returns a {@code BigInteger} whose value is the <i>unscaled
2151             * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
2152             * 10<sup>this.scale()</sup>)</tt>.)
2153             *
2154             * @return the unscaled value of this {@code BigDecimal}.
2155             * @since  1.2
2156             */
2157            public BigInteger unscaledValue() {
2158                return this .inflate().intVal;
2159            }
2160
2161            // Rounding Modes
2162
2163            /**
2164             * Rounding mode to round away from zero.  Always increments the
2165             * digit prior to a nonzero discarded fraction.  Note that this rounding
2166             * mode never decreases the magnitude of the calculated value.
2167             */
2168            public final static int ROUND_UP = 0;
2169
2170            /**
2171             * Rounding mode to round towards zero.  Never increments the digit
2172             * prior to a discarded fraction (i.e., truncates).  Note that this
2173             * rounding mode never increases the magnitude of the calculated value.
2174             */
2175            public final static int ROUND_DOWN = 1;
2176
2177            /**
2178             * Rounding mode to round towards positive infinity.  If the
2179             * {@code BigDecimal} is positive, behaves as for
2180             * {@code ROUND_UP}; if negative, behaves as for
2181             * {@code ROUND_DOWN}.  Note that this rounding mode never
2182             * decreases the calculated value.
2183             */
2184            public final static int ROUND_CEILING = 2;
2185
2186            /**
2187             * Rounding mode to round towards negative infinity.  If the
2188             * {@code BigDecimal} is positive, behave as for
2189             * {@code ROUND_DOWN}; if negative, behave as for
2190             * {@code ROUND_UP}.  Note that this rounding mode never
2191             * increases the calculated value.
2192             */
2193            public final static int ROUND_FLOOR = 3;
2194
2195            /**
2196             * Rounding mode to round towards {@literal "nearest neighbor"}
2197             * unless both neighbors are equidistant, in which case round up.
2198             * Behaves as for {@code ROUND_UP} if the discarded fraction is
2199             * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
2200             * that this is the rounding mode that most of us were taught in
2201             * grade school.
2202             */
2203            public final static int ROUND_HALF_UP = 4;
2204
2205            /**
2206             * Rounding mode to round towards {@literal "nearest neighbor"}
2207             * unless both neighbors are equidistant, in which case round
2208             * down.  Behaves as for {@code ROUND_UP} if the discarded
2209             * fraction is {@literal >} 0.5; otherwise, behaves as for
2210             * {@code ROUND_DOWN}.
2211             */
2212            public final static int ROUND_HALF_DOWN = 5;
2213
2214            /**
2215             * Rounding mode to round towards the {@literal "nearest neighbor"}
2216             * unless both neighbors are equidistant, in which case, round
2217             * towards the even neighbor.  Behaves as for
2218             * {@code ROUND_HALF_UP} if the digit to the left of the
2219             * discarded fraction is odd; behaves as for
2220             * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
2221             * rounding mode that minimizes cumulative error when applied
2222             * repeatedly over a sequence of calculations.
2223             */
2224            public final static int ROUND_HALF_EVEN = 6;
2225
2226            /**
2227             * Rounding mode to assert that the requested operation has an exact
2228             * result, hence no rounding is necessary.  If this rounding mode is
2229             * specified on an operation that yields an inexact result, an
2230             * {@code ArithmeticException} is thrown.
2231             */
2232            public final static int ROUND_UNNECESSARY = 7;
2233
2234            // Scaling/Rounding Operations
2235
2236            /**
2237             * Returns a {@code BigDecimal} rounded according to the
2238             * {@code MathContext} settings.  If the precision setting is 0 then
2239             * no rounding takes place.
2240             * 
2241             * <p>The effect of this method is identical to that of the
2242             * {@link #plus(MathContext)} method.
2243             *
2244             * @param mc the context to use.
2245             * @return a {@code BigDecimal} rounded according to the 
2246             *         {@code MathContext} settings.
2247             * @throws ArithmeticException if the rounding mode is
2248             *         {@code UNNECESSARY} and the
2249             *         {@code BigDecimal}  operation would require rounding.
2250             * @see    #plus(MathContext)
2251             * @since  1.5
2252             */
2253            public BigDecimal round(MathContext mc) {
2254                return plus(mc);
2255            }
2256
2257            /**
2258             * Returns a {@code BigDecimal} whose scale is the specified
2259             * value, and whose unscaled value is determined by multiplying or
2260             * dividing this {@code BigDecimal}'s unscaled value by the
2261             * appropriate power of ten to maintain its overall value.  If the
2262             * scale is reduced by the operation, the unscaled value must be
2263             * divided (rather than multiplied), and the value may be changed;
2264             * in this case, the specified rounding mode is applied to the
2265             * division.
2266             *
2267             * <p>Note that since BigDecimal objects are immutable, calls of
2268             * this method do <i>not</i> result in the original object being
2269             * modified, contrary to the usual convention of having methods
2270             * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2271             * Instead, {@code setScale} returns an object with the proper
2272             * scale; the returned object may or may not be newly allocated.
2273             * 
2274             * @param  newScale scale of the {@code BigDecimal} value to be returned.
2275             * @param  roundingMode The rounding mode to apply.
2276             * @return a {@code BigDecimal} whose scale is the specified value, 
2277             *         and whose unscaled value is determined by multiplying or 
2278             *         dividing this {@code BigDecimal}'s unscaled value by the 
2279             *         appropriate power of ten to maintain its overall value.
2280             * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2281             *         and the specified scaling operation would require
2282             *         rounding.
2283             * @see    RoundingMode
2284             * @since  1.5
2285             */
2286            public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2287                return setScale(newScale, roundingMode.oldMode);
2288            }
2289
2290            /**
2291             * Returns a {@code BigDecimal} whose scale is the specified
2292             * value, and whose unscaled value is determined by multiplying or
2293             * dividing this {@code BigDecimal}'s unscaled value by the
2294             * appropriate power of ten to maintain its overall value.  If the
2295             * scale is reduced by the operation, the unscaled value must be
2296             * divided (rather than multiplied), and the value may be changed;
2297             * in this case, the specified rounding mode is applied to the
2298             * division.
2299             * 
2300             * <p>Note that since BigDecimal objects are immutable, calls of
2301             * this method do <i>not</i> result in the original object being
2302             * modified, contrary to the usual convention of having methods
2303             * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2304             * Instead, {@code setScale} returns an object with the proper
2305             * scale; the returned object may or may not be newly allocated.
2306             * 
2307             * <p>The new {@link #setScale(int, RoundingMode)} method should
2308             * be used in preference to this legacy method.
2309             * 
2310             * @param  newScale scale of the {@code BigDecimal} value to be returned.
2311             * @param  roundingMode The rounding mode to apply.
2312             * @return a {@code BigDecimal} whose scale is the specified value, 
2313             *         and whose unscaled value is determined by multiplying or 
2314             *         dividing this {@code BigDecimal}'s unscaled value by the 
2315             *         appropriate power of ten to maintain its overall value.
2316             * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2317             *         and the specified scaling operation would require
2318             *         rounding.
2319             * @throws IllegalArgumentException if {@code roundingMode} does not
2320             *         represent a valid rounding mode.
2321             * @see    #ROUND_UP
2322             * @see    #ROUND_DOWN
2323             * @see    #ROUND_CEILING
2324             * @see    #ROUND_FLOOR
2325             * @see    #ROUND_HALF_UP
2326             * @see    #ROUND_HALF_DOWN
2327             * @see    #ROUND_HALF_EVEN
2328             * @see    #ROUND_UNNECESSARY
2329             */
2330            public BigDecimal setScale(int newScale, int roundingMode) {
2331                if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2332                    throw new IllegalArgumentException("Invalid rounding mode");
2333
2334                if (newScale == this .scale) // easy case
2335                    return this ;
2336                if (this .signum() == 0) // zero can have any scale
2337                    return BigDecimal.valueOf(0, newScale);
2338                if (newScale > this .scale) {
2339                    // [we can use checkScale to assure multiplier is valid]
2340                    int raise = checkScale((long) newScale - this .scale);
2341
2342                    if (intCompact != INFLATED) {
2343                        long scaledResult = longTenToThe(intCompact, raise);
2344                        if (scaledResult != INFLATED)
2345                            return BigDecimal.valueOf(scaledResult, newScale);
2346                        this .inflate();
2347                    }
2348
2349                    BigDecimal result = new BigDecimal(intVal
2350                            .multiply(tenToThe(raise)), newScale);
2351                    if (this .precision > 0)
2352                        result.precision = this .precision + newScale
2353                                - this .scale;
2354                    return result;
2355                }
2356                // scale < this.scale
2357                // we cannot perfectly predict the precision after rounding
2358                return divide(ONE, newScale, roundingMode);
2359            }
2360
2361            /**
2362             * Returns a {@code BigDecimal} whose scale is the specified
2363             * value, and whose value is numerically equal to this
2364             * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
2365             * if this is not possible.
2366             * 
2367             * <p>This call is typically used to increase the scale, in which
2368             * case it is guaranteed that there exists a {@code BigDecimal}
2369             * of the specified scale and the correct value.  The call can
2370             * also be used to reduce the scale if the caller knows that the
2371             * {@code BigDecimal} has sufficiently many zeros at the end of
2372             * its fractional part (i.e., factors of ten in its integer value)
2373             * to allow for the rescaling without changing its value.
2374             * 
2375             * <p>This method returns the same result as the two-argument
2376             * versions of {@code setScale}, but saves the caller the trouble
2377             * of specifying a rounding mode in cases where it is irrelevant.
2378             * 
2379             * <p>Note that since {@code BigDecimal} objects are immutable,
2380             * calls of this method do <i>not</i> result in the original
2381             * object being modified, contrary to the usual convention of
2382             * having methods named <tt>set<i>X</i></tt> mutate field
2383             * <i>{@code X}</i>.  Instead, {@code setScale} returns an
2384             * object with the proper scale; the returned object may or may
2385             * not be newly allocated.
2386             *
2387             * @param  newScale scale of the {@code BigDecimal} value to be returned.
2388             * @return a {@code BigDecimal} whose scale is the specified value, and 
2389             *         whose unscaled value is determined by multiplying or dividing 
2390             *         this {@code BigDecimal}'s unscaled value by the appropriate 
2391             *         power of ten to maintain its overall value.
2392             * @throws ArithmeticException if the specified scaling operation would
2393             *         require rounding.
2394             * @see    #setScale(int, int)
2395             * @see    #setScale(int, RoundingMode)
2396             */
2397            public BigDecimal setScale(int newScale) {
2398                return setScale(newScale, ROUND_UNNECESSARY);
2399            }
2400
2401            // Decimal Point Motion Operations
2402
2403            /**
2404             * Returns a {@code BigDecimal} which is equivalent to this one
2405             * with the decimal point moved {@code n} places to the left.  If
2406             * {@code n} is non-negative, the call merely adds {@code n} to
2407             * the scale.  If {@code n} is negative, the call is equivalent
2408             * to {@code movePointRight(-n)}.  The {@code BigDecimal}
2409             * returned by this call has value <tt>(this &times;
2410             * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
2411             * 0)}.
2412             *
2413             * @param  n number of places to move the decimal point to the left.
2414             * @return a {@code BigDecimal} which is equivalent to this one with the 
2415             *         decimal point moved {@code n} places to the left.
2416             * @throws ArithmeticException if scale overflows.
2417             */
2418            public BigDecimal movePointLeft(int n) {
2419                // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2420                int newScale = checkScale((long) scale + n);
2421                BigDecimal num;
2422                if (intCompact != INFLATED)
2423                    num = BigDecimal.valueOf(intCompact, newScale);
2424                else
2425                    num = new BigDecimal(intVal, newScale);
2426                return (num.scale < 0 ? num.setScale(0) : num);
2427            }
2428
2429            /**
2430             * Returns a {@code BigDecimal} which is equivalent to this one
2431             * with the decimal point moved {@code n} places to the right.
2432             * If {@code n} is non-negative, the call merely subtracts
2433             * {@code n} from the scale.  If {@code n} is negative, the call
2434             * is equivalent to {@code movePointLeft(-n)}.  The
2435             * {@code BigDecimal} returned by this call has value <tt>(this
2436             * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
2437             * 0)}.
2438             *
2439             * @param  n number of places to move the decimal point to the right.
2440             * @return a {@code BigDecimal} which is equivalent to this one
2441             *         with the decimal point moved {@code n} places to the right.
2442             * @throws ArithmeticException if scale overflows.
2443             */
2444            public BigDecimal movePointRight(int n) {
2445                // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2446                int newScale = checkScale((long) scale - n);
2447                BigDecimal num;
2448                if (intCompact != INFLATED)
2449                    num = BigDecimal.valueOf(intCompact, newScale);
2450                else
2451                    num = new BigDecimal(intVal, newScale);
2452                return (num.scale < 0 ? num.setScale(0) : num);
2453            }
2454
2455            /**
2456             * Returns a BigDecimal whose numerical value is equal to
2457             * ({@code this} * 10<sup>n</sup>).  The scale of
2458             * the result is {@code (this.scale() - n)}.
2459             *
2460             * @throws ArithmeticException if the scale would be
2461             *         outside the range of a 32-bit integer.
2462             *
2463             * @since 1.5
2464             */
2465            public BigDecimal scaleByPowerOfTen(int n) {
2466                this .inflate();
2467                BigDecimal num = new BigDecimal(intVal, checkScale((long) scale
2468                        - n));
2469                num.precision = precision;
2470                return num;
2471            }
2472
2473            /**
2474             * Returns a {@code BigDecimal} which is numerically equal to
2475             * this one but with any trailing zeros removed from the
2476             * representation.  For example, stripping the trailing zeros from
2477             * the {@code BigDecimal} value {@code 600.0}, which has
2478             * [{@code BigInteger}, {@code scale}] components equals to
2479             * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2480             * {@code scale}] components equals to [6, -2]
2481             *
2482             * @return a numerically equal {@code BigDecimal} with any
2483             * trailing zeros removed.
2484             * @since 1.5
2485             */
2486            public BigDecimal stripTrailingZeros() {
2487                this .inflate();
2488                return (new BigDecimal(intVal, scale))
2489                        .stripZerosToMatchScale(Long.MIN_VALUE);
2490            }
2491
2492            // Comparison Operations
2493
2494            /**
2495             * Compares this {@code BigDecimal} with the specified
2496             * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
2497             * equal in value but have a different scale (like 2.0 and 2.00)
2498             * are considered equal by this method.  This method is provided
2499             * in preference to individual methods for each of the six boolean
2500             * comparison operators ({@literal <}, ==,
2501             * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
2502             * suggested idiom for performing these comparisons is:
2503             * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
2504             * &lt;<i>op</i>&gt; is one of the six comparison operators.
2505             *
2506             * @param  val {@code BigDecimal} to which this {@code BigDecimal} is 
2507             *         to be compared.
2508             * @return -1, 0, or 1 as this {@code BigDecimal} is numerically 
2509             *          less than, equal to, or greater than {@code val}.
2510             */
2511            public int compareTo(BigDecimal val) {
2512                if (this .scale == val.scale && this .intCompact != INFLATED
2513                        && val.intCompact != INFLATED)
2514                    return longCompareTo(this .intCompact, val.intCompact);
2515
2516                // Optimization: would run fine without the next three lines
2517                int sigDiff = signum() - val.signum();
2518                if (sigDiff != 0)
2519                    return (sigDiff > 0 ? 1 : -1);
2520
2521                // If the (adjusted) exponents are different we do not need to
2522                // expensively match scales and compare the significands
2523                int aethis  = this .precision() - this .scale; // [-1]
2524                int aeval = val.precision() - val.scale; // [-1]
2525                if (aethis  < aeval)
2526                    return -this .signum();
2527                else if (aethis  > aeval)
2528                    return this .signum();
2529
2530                // Scale and compare intVals
2531                BigDecimal arg[] = { this , val };
2532                matchScale(arg);
2533                if (arg[0].intCompact != INFLATED
2534                        && arg[1].intCompact != INFLATED)
2535                    return longCompareTo(arg[0].intCompact, arg[1].intCompact);
2536                return arg[0].inflate().intVal
2537                        .compareTo(arg[1].inflate().intVal);
2538            }
2539
2540            /**
2541             * Compares this {@code BigDecimal} with the specified
2542             * {@code Object} for equality.  Unlike {@link
2543             * #compareTo(BigDecimal) compareTo}, this method considers two
2544             * {@code BigDecimal} objects equal only if they are equal in
2545             * value and scale (thus 2.0 is not equal to 2.00 when compared by
2546             * this method).
2547             *
2548             * @param  x {@code Object} to which this {@code BigDecimal} is 
2549             *         to be compared.
2550             * @return {@code true} if and only if the specified {@code Object} is a
2551             *         {@code BigDecimal} whose value and scale are equal to this 
2552             *         {@code BigDecimal}'s.
2553             * @see    #compareTo(java.math.BigDecimal)
2554             * @see    #hashCode
2555             */
2556            public boolean equals(Object x) {
2557                if (!(x instanceof  BigDecimal))
2558                    return false;
2559                BigDecimal xDec = (BigDecimal) x;
2560                if (scale != xDec.scale)
2561                    return false;
2562                if (this .intCompact != INFLATED && xDec.intCompact != INFLATED)
2563                    return this .intCompact == xDec.intCompact;
2564                return this .inflate().intVal.equals(xDec.inflate().intVal);
2565            }
2566
2567            /**
2568             * Returns the minimum of this {@code BigDecimal} and
2569             * {@code val}.
2570             *
2571             * @param  val value with which the minimum is to be computed.
2572             * @return the {@code BigDecimal} whose value is the lesser of this 
2573             *         {@code BigDecimal} and {@code val}.  If they are equal, 
2574             *         as defined by the {@link #compareTo(BigDecimal) compareTo}  
2575             *         method, {@code this} is returned.
2576             * @see    #compareTo(java.math.BigDecimal)
2577             */
2578            public BigDecimal min(BigDecimal val) {
2579                return (compareTo(val) <= 0 ? this  : val);
2580            }
2581
2582            /**
2583             * Returns the maximum of this {@code BigDecimal} and {@code val}.
2584             *
2585             * @param  val value with which the maximum is to be computed.
2586             * @return the {@code BigDecimal} whose value is the greater of this 
2587             *         {@code BigDecimal} and {@code val}.  If they are equal, 
2588             *         as defined by the {@link #compareTo(BigDecimal) compareTo} 
2589             *         method, {@code this} is returned.
2590             * @see    #compareTo(java.math.BigDecimal)
2591             */
2592            public BigDecimal max(BigDecimal val) {
2593                return (compareTo(val) >= 0 ? this  : val);
2594            }
2595
2596            // Hash Function
2597
2598            /**
2599             * Returns the hash code for this {@code BigDecimal}.  Note that
2600             * two {@code BigDecimal} objects that are numerically equal but
2601             * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2602             * have the same hash code.
2603             *
2604             * @return hash code for this {@code BigDecimal}.
2605             * @see #equals(Object)
2606             */
2607            public int hashCode() {
2608                if (intCompact != INFLATED) {
2609                    long val2 = (intCompact < 0) ? -intCompact : intCompact;
2610                    int temp = (int) (((int) (val2 >>> 32)) * 31 + (val2 & 0xffffffffL));
2611                    return 31 * ((intCompact < 0) ? -temp : temp) + scale;
2612                } else
2613                    return 31 * intVal.hashCode() + scale;
2614            }
2615
2616            // Format Converters
2617
2618            /**
2619             * Returns the string representation of this {@code BigDecimal},
2620             * using scientific notation if an exponent is needed.
2621             * 
2622             * <p>A standard canonical string form of the {@code BigDecimal}
2623             * is created as though by the following steps: first, the
2624             * absolute value of the unscaled value of the {@code BigDecimal}
2625             * is converted to a string in base ten using the characters
2626             * {@code '0'} through {@code '9'} with no leading zeros (except
2627             * if its value is zero, in which case a single {@code '0'}
2628             * character is used).
2629             * 
2630             * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2631             * negated scale, plus the number of characters in the converted
2632             * unscaled value, less one.  That is,
2633             * {@code -scale+(ulength-1)}, where {@code ulength} is the
2634             * length of the absolute value of the unscaled value in decimal
2635             * digits (its <i>precision</i>).
2636             * 
2637             * <p>If the scale is greater than or equal to zero and the
2638             * adjusted exponent is greater than or equal to {@code -6}, the
2639             * number will be converted to a character form without using
2640             * exponential notation.  In this case, if the scale is zero then
2641             * no decimal point is added and if the scale is positive a
2642             * decimal point will be inserted with the scale specifying the
2643             * number of characters to the right of the decimal point.
2644             * {@code '0'} characters are added to the left of the converted
2645             * unscaled value as necessary.  If no character precedes the
2646             * decimal point after this insertion then a conventional
2647             * {@code '0'} character is prefixed.
2648             * 
2649             * <p>Otherwise (that is, if the scale is negative, or the
2650             * adjusted exponent is less than {@code -6}), the number will be
2651             * converted to a character form using exponential notation.  In
2652             * this case, if the converted {@code BigInteger} has more than
2653             * one digit a decimal point is inserted after the first digit.
2654             * An exponent in character form is then suffixed to the converted
2655             * unscaled value (perhaps with inserted decimal point); this
2656             * comprises the letter {@code 'E'} followed immediately by the
2657             * adjusted exponent converted to a character form.  The latter is
2658             * in base ten, using the characters {@code '0'} through
2659             * {@code '9'} with no leading zeros, and is always prefixed by a
2660             * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the
2661             * adjusted exponent is negative, {@code '+'}
2662             * (<tt>'&#92;u002B'</tt>) otherwise).
2663             * 
2664             * <p>Finally, the entire string is prefixed by a minus sign
2665             * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled
2666             * value is less than zero.  No sign character is prefixed if the
2667             * unscaled value is zero or positive.
2668             * 
2669             * <p><b>Examples:</b>
2670             * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2671             * on the left, the resulting string is shown on the right.
2672             * <pre>
2673             * [123,0]      "123"
2674             * [-123,0]     "-123"
2675             * [123,-1]     "1.23E+3"
2676             * [123,-3]     "1.23E+5"
2677             * [123,1]      "12.3"
2678             * [123,5]      "0.00123"
2679             * [123,10]     "1.23E-8"
2680             * [-123,12]    "-1.23E-10"
2681             * </pre>
2682             *
2683             * <b>Notes:</b>
2684             * <ol>
2685             *
2686             * <li>There is a one-to-one mapping between the distinguishable
2687             * {@code BigDecimal} values and the result of this conversion.
2688             * That is, every distinguishable {@code BigDecimal} value
2689             * (unscaled value and scale) has a unique string representation
2690             * as a result of using {@code toString}.  If that string
2691             * representation is converted back to a {@code BigDecimal} using
2692             * the {@link #BigDecimal(String)} constructor, then the original
2693             * value will be recovered.
2694             * 
2695             * <li>The string produced for a given number is always the same;
2696             * it is not affected by locale.  This means that it can be used
2697             * as a canonical string representation for exchanging decimal
2698             * data, or as a key for a Hashtable, etc.  Locale-sensitive
2699             * number formatting and parsing is handled by the {@link
2700             * java.text.NumberFormat} class and its subclasses.
2701             * 
2702             * <li>The {@link #toEngineeringString} method may be used for
2703             * presenting numbers with exponents in engineering notation, and the
2704             * {@link #setScale(int,RoundingMode) setScale} method may be used for
2705             * rounding a {@code BigDecimal} so it has a known number of digits after
2706             * the decimal point.
2707             * 
2708             * <li>The digit-to-character mapping provided by
2709             * {@code Character.forDigit} is used.
2710             *
2711             * </ol>
2712             *
2713             * @return string representation of this {@code BigDecimal}.
2714             * @see    Character#forDigit
2715             * @see    #BigDecimal(java.lang.String)
2716             */
2717            public String toString() {
2718                if (stringCache == null)
2719                    stringCache = layoutChars(true);
2720                return stringCache;
2721            }
2722
2723            /**
2724             * Returns a string representation of this {@code BigDecimal},
2725             * using engineering notation if an exponent is needed.
2726             * 
2727             * <p>Returns a string that represents the {@code BigDecimal} as
2728             * described in the {@link #toString()} method, except that if
2729             * exponential notation is used, the power of ten is adjusted to
2730             * be a multiple of three (engineering notation) such that the
2731             * integer part of nonzero values will be in the range 1 through
2732             * 999.  If exponential notation is used for zero values, a
2733             * decimal point and one or two fractional zero digits are used so
2734             * that the scale of the zero value is preserved.  Note that
2735             * unlike the output of {@link #toString()}, the output of this
2736             * method is <em>not</em> guaranteed to recover the same [integer,
2737             * scale] pair of this {@code BigDecimal} if the output string is
2738             * converting back to a {@code BigDecimal} using the {@linkplain
2739             * #BigDecimal(String) string constructor}.  The result of this method meets
2740             * the weaker constraint of always producing a numerically equal
2741             * result from applying the string constructor to the method's output.
2742             *
2743             * @return string representation of this {@code BigDecimal}, using
2744             *         engineering notation if an exponent is needed.
2745             * @since  1.5
2746             */
2747            public String toEngineeringString() {
2748                return layoutChars(false);
2749            }
2750
2751            /**
2752             * Returns a string representation of this {@code BigDecimal}
2753             * without an exponent field.  For values with a positive scale,
2754             * the number of digits to the right of the decimal point is used
2755             * to indicate scale.  For values with a zero or negative scale,
2756             * the resulting string is generated as if the value were
2757             * converted to a numerically equal value with zero scale and as
2758             * if all the trailing zeros of the zero scale value were present
2759             * in the result.
2760             *
2761             * The entire string is prefixed by a minus sign character '-'
2762             * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
2763             * zero. No sign character is prefixed if the unscaled value is
2764             * zero or positive.
2765             *
2766             * Note that if the result of this method is passed to the
2767             * {@linkplain #BigDecimal(String) string constructor}, only the
2768             * numerical value of this {@code BigDecimal} will necessarily be
2769             * recovered; the representation of the new {@code BigDecimal}
2770             * may have a different scale.  In particular, if this
2771             * {@code BigDecimal} has a negative scale, the string resulting
2772             * from this method will have a scale of zero when processed by
2773             * the string constructor.
2774             *
2775             * (This method behaves analogously to the {@code toString}
2776             * method in 1.4 and earlier releases.)
2777             *
2778             * @return a string representation of this {@code BigDecimal}
2779             * without an exponent field.
2780             * @since 1.5
2781             * @see #toString()
2782             * @see #toEngineeringString()
2783             */
2784            public String toPlainString() {
2785                BigDecimal bd = this ;
2786                if (bd.scale < 0)
2787                    bd = bd.setScale(0);
2788                bd.inflate();
2789                if (bd.scale == 0) // No decimal point
2790                    return bd.intVal.toString();
2791                return bd.getValueString(bd.signum(), bd.intVal.abs()
2792                        .toString(), bd.scale);
2793            }
2794
2795            /* Returns a digit.digit string */
2796            private String getValueString(int signum, String intString,
2797                    int scale) {
2798                /* Insert decimal point */
2799                StringBuilder buf;
2800                int insertionPoint = intString.length() - scale;
2801                if (insertionPoint == 0) { /* Point goes right before intVal */
2802                    return (signum < 0 ? "-0." : "0.") + intString;
2803                } else if (insertionPoint > 0) { /* Point goes inside intVal */
2804                    buf = new StringBuilder(intString);
2805                    buf.insert(insertionPoint, '.');
2806                    if (signum < 0)
2807                        buf.insert(0, '-');
2808                } else { /* We must insert zeros between point and intVal */
2809                    buf = new StringBuilder(3 - insertionPoint
2810                            + intString.length());
2811                    buf.append(signum < 0 ? "-0." : "0.");
2812                    for (int i = 0; i < -insertionPoint; i++)
2813                        buf.append('0');
2814                    buf.append(intString);
2815                }
2816                return buf.toString();
2817            }
2818
2819            /**
2820             * Converts this {@code BigDecimal} to a {@code BigInteger}.
2821             * This conversion is analogous to a <a
2822             * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2823             * primitive conversion</i></a> from {@code double} to
2824             * {@code long} as defined in the <a
2825             * href="http://java.sun.com/docs/books/jls/html/">Java Language
2826             * Specification</a>: any fractional part of this
2827             * {@code BigDecimal} will be discarded.  Note that this
2828             * conversion can lose information about the precision of the
2829             * {@code BigDecimal} value.
2830             * <p>
2831             * To have an exception thrown if the conversion is inexact (in
2832             * other words if a nonzero fractional part is discarded), use the
2833             * {@link #toBigIntegerExact()} method.
2834             *
2835             * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2836             */
2837            public BigInteger toBigInteger() {
2838                // force to an integer, quietly
2839                return this .setScale(0, ROUND_DOWN).inflate().intVal;
2840            }
2841
2842            /**
2843             * Converts this {@code BigDecimal} to a {@code BigInteger},
2844             * checking for lost information.  An exception is thrown if this
2845             * {@code BigDecimal} has a nonzero fractional part.
2846             *
2847             * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2848             * @throws ArithmeticException if {@code this} has a nonzero
2849             *         fractional part.
2850             * @since  1.5
2851             */
2852            public BigInteger toBigIntegerExact() {
2853                // round to an integer, with Exception if decimal part non-0
2854                return this .setScale(0, ROUND_UNNECESSARY).inflate().intVal;
2855            }
2856
2857            /**
2858             * Converts this {@code BigDecimal} to a {@code long}.  This
2859             * conversion is analogous to a <a
2860             * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2861             * primitive conversion</i></a> from {@code double} to
2862             * {@code short} as defined in the <a
2863             * href="http://java.sun.com/docs/books/jls/html/">Java Language
2864             * Specification</a>: any fractional part of this
2865             * {@code BigDecimal} will be discarded, and if the resulting
2866             * "{@code BigInteger}" is too big to fit in a
2867             * {@code long}, only the low-order 64 bits are returned.
2868             * Note that this conversion can lose information about the
2869             * overall magnitude and precision of this {@code BigDecimal} value as well
2870             * as return a result with the opposite sign.
2871             * 
2872             * @return this {@code BigDecimal} converted to a {@code long}.
2873             */
2874            public long longValue() {
2875                return (intCompact != INFLATED && scale == 0) ? intCompact
2876                        : toBigInteger().longValue();
2877            }
2878
2879            /**
2880             * Converts this {@code BigDecimal} to a {@code long}, checking
2881             * for lost information.  If this {@code BigDecimal} has a
2882             * nonzero fractional part or is out of the possible range for a
2883             * {@code long} result then an {@code ArithmeticException} is
2884             * thrown.
2885             *
2886             * @return this {@code BigDecimal} converted to a {@code long}.
2887             * @throws ArithmeticException if {@code this} has a nonzero
2888             *         fractional part, or will not fit in a {@code long}.
2889             * @since  1.5
2890             */
2891            public long longValueExact() {
2892                if (intCompact != INFLATED && scale == 0)
2893                    return intCompact;
2894                // If more than 19 digits in integer part it cannot possibly fit
2895                if ((precision() - scale) > 19) // [OK for negative scale too]
2896                    throw new java.lang.ArithmeticException("Overflow");
2897                // Fastpath zero and < 1.0 numbers (the latter can be very slow
2898                // to round if very small)
2899                if (this .signum() == 0)
2900                    return 0;
2901                if ((this .precision() - this .scale) <= 0)
2902                    throw new ArithmeticException("Rounding necessary");
2903                // round to an integer, with Exception if decimal part non-0
2904                BigDecimal num = this .setScale(0, ROUND_UNNECESSARY).inflate();
2905                if (num.precision() >= 19) // need to check carefully
2906                    LongOverflow.check(num);
2907                return num.intVal.longValue();
2908            }
2909
2910            private static class LongOverflow {
2911                /** BigInteger equal to Long.MIN_VALUE. */
2912                private static final BigInteger LONGMIN = BigInteger
2913                        .valueOf(Long.MIN_VALUE);
2914
2915                /** BigInteger equal to Long.MAX_VALUE. */
2916                private static final BigInteger LONGMAX = BigInteger
2917                        .valueOf(Long.MAX_VALUE);
2918
2919                public static void check(BigDecimal num) {
2920                    if ((num.intVal.compareTo(LONGMIN) < 0)
2921                            || (num.intVal.compareTo(LONGMAX) > 0))
2922                        throw new java.lang.ArithmeticException("Overflow");
2923                }
2924            }
2925
2926            /**
2927             * Converts this {@code BigDecimal} to an {@code int}.  This
2928             * conversion is analogous to a <a
2929             * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
2930             * primitive conversion</i></a> from {@code double} to
2931             * {@code short} as defined in the <a
2932             * href="http://java.sun.com/docs/books/jls/html/">Java Language
2933             * Specification</a>: any fractional part of this
2934             * {@code BigDecimal} will be discarded, and if the resulting
2935             * "{@code BigInteger}" is too big to fit in an
2936             * {@code int}, only the low-order 32 bits are returned.
2937             * Note that this conversion can lose information about the
2938             * overall magnitude and precision of this {@code BigDecimal}
2939             * value as well as return a result with the opposite sign.
2940             * 
2941             * @return this {@code BigDecimal} converted to an {@code int}.
2942             */
2943            public int intValue() {
2944                return (intCompact != INFLATED && scale == 0) ? (int) intCompact
2945                        : toBigInteger().intValue();
2946            }
2947
2948            /**
2949             * Converts this {@code BigDecimal} to an {@code int}, checking
2950             * for lost information.  If this {@code BigDecimal} has a
2951             * nonzero fractional part or is out of the possible range for an
2952             * {@code int} result then an {@code ArithmeticException} is
2953             * thrown.
2954             *
2955             * @return this {@code BigDecimal} converted to an {@code int}.
2956             * @throws ArithmeticException if {@code this} has a nonzero
2957             *         fractional part, or will not fit in an {@code int}.
2958             * @since  1.5
2959             */
2960            public int intValueExact() {
2961                long num;
2962                num = this .longValueExact(); // will check decimal part
2963                if ((int) num != num)
2964                    throw new java.lang.ArithmeticException("Overflow");
2965                return (int) num;
2966            }
2967
2968            /**
2969             * Converts this {@code BigDecimal} to a {@code short}, checking
2970             * for lost information.  If this {@code BigDecimal} has a
2971             * nonzero fractional part or is out of the possible range for a
2972             * {@code short} result then an {@code ArithmeticException} is
2973             * thrown.
2974             *
2975             * @return this {@code BigDecimal} converted to a {@code short}.
2976             * @throws ArithmeticException if {@code this} has a nonzero
2977             *         fractional part, or will not fit in a {@code short}.
2978             * @since  1.5
2979             */
2980            public short shortValueExact() {
2981                long num;
2982                num = this .longValueExact(); // will check decimal part
2983                if ((short) num != num)
2984                    throw new java.lang.ArithmeticException("Overflow");
2985                return (short) num;
2986            }
2987
2988            /**
2989             * Converts this {@code BigDecimal} to a {@code byte}, checking
2990             * for lost information.  If this {@code BigDecimal} has a
2991             * nonzero fractional part or is out of the possible range for a
2992             * {@code byte} result then an {@code ArithmeticException} is
2993             * thrown.
2994             *
2995             * @return this {@code BigDecimal} converted to a {@code byte}.
2996             * @throws ArithmeticException if {@code this} has a nonzero
2997             *         fractional part, or will not fit in a {@code byte}.
2998             * @since  1.5
2999             */
3000            public byte byteValueExact() {
3001                long num;
3002                num = this .longValueExact(); // will check decimal part
3003                if ((byte) num != num)
3004                    throw new java.lang.ArithmeticException("Overflow");
3005                return (byte) num;
3006            }
3007
3008            /**
3009             * Converts this {@code BigDecimal} to a {@code float}.
3010             * This conversion is similar to the <a
3011             * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
3012             * primitive conversion</i></a> from {@code double} to
3013             * {@code float} defined in the <a
3014             * href="http://java.sun.com/docs/books/jls/html/">Java Language
3015             * Specification</a>: if this {@code BigDecimal} has too great a
3016             * magnitude to represent as a {@code float}, it will be
3017             * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3018             * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
3019             * the return value is finite, this conversion can lose
3020             * information about the precision of the {@code BigDecimal}
3021             * value.
3022             * 
3023             * @return this {@code BigDecimal} converted to a {@code float}.
3024             */
3025            public float floatValue() {
3026                if (scale == 0 && intCompact != INFLATED)
3027                    return (float) intCompact;
3028                // Somewhat inefficient, but guaranteed to work.
3029                return Float.parseFloat(this .toString());
3030            }
3031
3032            /**
3033             * Converts this {@code BigDecimal} to a {@code double}.
3034             * This conversion is similar to the <a
3035             * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing
3036             * primitive conversion</i></a> from {@code double} to
3037             * {@code float} as defined in the <a
3038             * href="http://java.sun.com/docs/books/jls/html/">Java Language
3039             * Specification</a>: if this {@code BigDecimal} has too great a
3040             * magnitude represent as a {@code double}, it will be
3041             * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3042             * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
3043             * the return value is finite, this conversion can lose
3044             * information about the precision of the {@code BigDecimal}
3045             * value.
3046             * 
3047             * @return this {@code BigDecimal} converted to a {@code double}.
3048             */
3049            public double doubleValue() {
3050                if (scale == 0 && intCompact != INFLATED)
3051                    return (double) intCompact;
3052                // Somewhat inefficient, but guaranteed to work.
3053                return Double.parseDouble(this .toString());
3054            }
3055
3056            /**
3057             * Returns the size of an ulp, a unit in the last place, of this
3058             * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
3059             * value is the positive distance between this value and the
3060             * {@code BigDecimal} value next larger in magnitude with the
3061             * same number of digits.  An ulp of a zero value is numerically
3062             * equal to 1 with the scale of {@code this}.  The result is
3063             * stored with the same scale as {@code this} so the result
3064             * for zero and nonzero values is equal to {@code [1,
3065             * this.scale()]}.
3066             *
3067             * @return the size of an ulp of {@code this}
3068             * @since 1.5
3069             */
3070            public BigDecimal ulp() {
3071                return BigDecimal.valueOf(1, this .scale());
3072            }
3073
3074            // Private "Helper" Methods
3075
3076            /**
3077             * Lay out this {@code BigDecimal} into a {@code char[]} array.
3078             * The Java 1.2 equivalent to this was called {@code getValueString}.
3079             *
3080             * @param  sci {@code true} for Scientific exponential notation;
3081             *          {@code false} for Engineering
3082             * @return string with canonical string representation of this
3083             *         {@code BigDecimal}
3084             */
3085            private String layoutChars(boolean sci) {
3086                if (scale == 0) // zero scale is trivial
3087                    return (intCompact != INFLATED) ? Long.toString(intCompact)
3088                            : intVal.toString();
3089
3090                // Get the significand as an absolute value
3091                char coeff[];
3092                if (intCompact != INFLATED)
3093                    coeff = Long.toString(Math.abs(intCompact)).toCharArray();
3094                else
3095                    coeff = intVal.abs().toString().toCharArray();
3096
3097                // Construct a buffer, with sufficient capacity for all cases.
3098                // If E-notation is needed, length will be: +1 if negative, +1
3099                // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3100                // Otherwise it could have +1 if negative, plus leading "0.00000"
3101                StringBuilder buf = new StringBuilder(coeff.length + 14);
3102                if (signum() < 0) // prefix '-' if negative
3103                    buf.append('-');
3104                long adjusted = -(long) scale + (coeff.length - 1);
3105                if ((scale >= 0) && (adjusted >= -6)) { // plain number
3106                    int pad = scale - coeff.length; // count of padding zeros
3107                    if (pad >= 0) { // 0.xxx form
3108                        buf.append('0');
3109                        buf.append('.');
3110                        for (; pad > 0; pad--) {
3111                            buf.append('0');
3112                        }
3113                        buf.append(coeff);
3114                    } else { // xx.xx form
3115                        buf.append(coeff, 0, -pad);
3116                        buf.append('.');
3117                        buf.append(coeff, -pad, scale);
3118                    }
3119                } else { // E-notation is needed
3120                    if (sci) { // Scientific notation
3121                        buf.append(coeff[0]); // first character
3122                        if (coeff.length > 1) { // more to come
3123                            buf.append('.');
3124                            buf.append(coeff, 1, coeff.length - 1);
3125                        }
3126                    } else { // Engineering notation
3127                        int sig = (int) (adjusted % 3);
3128                        if (sig < 0)
3129                            sig += 3; // [adjusted was negative]
3130                        adjusted -= sig; // now a multiple of 3
3131                        sig++;
3132                        if (signum() == 0) {
3133                            switch (sig) {
3134                            case 1:
3135                                buf.append('0'); // exponent is a multiple of three
3136                                break;
3137                            case 2:
3138                                buf.append("0.00");
3139                                adjusted += 3;
3140                                break;
3141                            case 3:
3142                                buf.append("0.0");
3143                                adjusted += 3;
3144                                break;
3145                            default:
3146                                throw new AssertionError(
3147                                        "Unexpected sig value " + sig);
3148                            }
3149                        } else if (sig >= coeff.length) { // significand all in integer
3150                            buf.append(coeff, 0, coeff.length);
3151                            // may need some zeros, too
3152                            for (int i = sig - coeff.length; i > 0; i--)
3153                                buf.append('0');
3154                        } else { // xx.xxE form
3155                            buf.append(coeff, 0, sig);
3156                            buf.append('.');
3157                            buf.append(coeff, sig, coeff.length - sig);
3158                        }
3159                    }
3160                    if (adjusted != 0) { // [!sci could have made 0]
3161                        buf.append('E');
3162                        if (adjusted > 0) // force sign for positive
3163                            buf.append('+');
3164                        buf.append(adjusted);
3165                    }
3166                }
3167                return buf.toString();
3168            }
3169
3170            /**
3171             * Return 10 to the power n, as a {@code BigInteger}.
3172             *
3173             * @param  n the power of ten to be returned (>=0)
3174             * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3175             */
3176            private static BigInteger tenToThe(int n) {
3177                if (n < TENPOWERS.length) // use value from constant array
3178                    return TENPOWERS[n];
3179                // BigInteger.pow is slow, so make 10**n by constructing a
3180                // BigInteger from a character string (still not very fast)
3181                char tenpow[] = new char[n + 1];
3182                tenpow[0] = '1';
3183                for (int i = 1; i <= n; i++)
3184                    tenpow[i] = '0';
3185                return new BigInteger(tenpow);
3186            }
3187
3188            private static BigInteger TENPOWERS[] = { BigInteger.ONE,
3189                    BigInteger.valueOf(10), BigInteger.valueOf(100),
3190                    BigInteger.valueOf(1000), BigInteger.valueOf(10000),
3191                    BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
3192                    BigInteger.valueOf(10000000),
3193                    BigInteger.valueOf(100000000),
3194                    BigInteger.valueOf(1000000000) };
3195
3196            /**
3197             * Compute val * 10 ^ n; return this product if it is
3198             * representable as a long, INFLATED otherwise.
3199             */
3200            private static long longTenToThe(long val, int n) {
3201                // System.err.print("\tval " + val + "\t power " + n + "\tresult ");
3202                if (n >= 0 && n < thresholds.length) {
3203                    if (Math.abs(val) <= thresholds[n][0]) {
3204                        // System.err.println(val * thresholds[n][1]);
3205                        return val * thresholds[n][1];
3206                    }
3207                }
3208                // System.err.println(INFLATED);
3209                return INFLATED;
3210            }
3211
3212            private static long thresholds[][] = { { Long.MAX_VALUE, 1L }, // 0
3213                    { Long.MAX_VALUE / 10L, 10L }, // 1
3214                    { Long.MAX_VALUE / 100L, 100L }, // 2
3215                    { Long.MAX_VALUE / 1000L, 1000L }, // 3
3216                    { Long.MAX_VALUE / 10000L, 10000L }, // 4
3217                    { Long.MAX_VALUE / 100000L, 100000L }, // 5
3218                    { Long.MAX_VALUE / 1000000L, 1000000L }, // 6
3219                    { Long.MAX_VALUE / 10000000L, 10000000L }, // 7
3220                    { Long.MAX_VALUE / 100000000L, 100000000L }, // 8
3221                    { Long.MAX_VALUE / 1000000000L, 1000000000L }, // 9
3222                    { Long.MAX_VALUE / 10000000000L, 10000000000L }, // 10
3223                    { Long.MAX_VALUE / 100000000000L, 100000000000L }, // 11
3224                    { Long.MAX_VALUE / 1000000000000L, 1000000000000L },// 12
3225                    { Long.MAX_VALUE / 100000000000000L, 10000000000000L },// 13
3226            };
3227
3228            private static boolean compactLong(long val) {
3229                return (val != Long.MIN_VALUE);
3230            }
3231
3232            /**
3233             * Assign appropriate BigInteger to intVal field if intVal is
3234             * null, i.e. the compact representation is in use.
3235             */
3236            private BigDecimal inflate() {
3237                if (intVal == null)
3238                    intVal = BigInteger.valueOf(intCompact);
3239                return this ;
3240            }
3241
3242            /**
3243             * Match the scales of two {@code BigDecimal}s to align their
3244             * least significant digits.
3245             * 
3246             * <p>If the scales of val[0] and val[1] differ, rescale
3247             * (non-destructively) the lower-scaled {@code BigDecimal} so
3248             * they match.  That is, the lower-scaled reference will be
3249             * replaced by a reference to a new object with the same scale as
3250             * the other {@code BigDecimal}.
3251             *
3252             * @param  val array of two elements referring to the two
3253             *         {@code BigDecimal}s to be aligned.
3254             */
3255            private static void matchScale(BigDecimal[] val) {
3256                if (val[0].scale < val[1].scale)
3257                    val[0] = val[0].setScale(val[1].scale);
3258                else if (val[1].scale < val[0].scale)
3259                    val[1] = val[1].setScale(val[0].scale);
3260            }
3261
3262            /**
3263             * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3264             * deserialize it).
3265             *
3266             * @param s the stream being read.
3267             */
3268            private void readObject(java.io.ObjectInputStream s)
3269                    throws java.io.IOException, ClassNotFoundException {
3270                // Read in all fields
3271                s.defaultReadObject();
3272                // validate possibly bad fields
3273                if (intVal == null) {
3274                    String message = "BigDecimal: null intVal in stream";
3275                    throw new java.io.StreamCorruptedException(message);
3276                    // [all values of scale are now allowed]
3277                }
3278                // Set intCompact to uninitialized value; could also see if the
3279                // intVal was small enough to fit as a compact value.
3280                intCompact = INFLATED;
3281            }
3282
3283            /**
3284             * Serialize this {@code BigDecimal} to the stream in question
3285             *
3286             * @param s the stream to serialize to.
3287             */
3288            private void writeObject(java.io.ObjectOutputStream s)
3289                    throws java.io.IOException {
3290                // Must inflate to maintain compatible serial form.
3291                this .inflate();
3292
3293                // Write proper fields
3294                s.defaultWriteObject();
3295            }
3296
3297            /**
3298             * Returns the length of this {@code BigDecimal}, in decimal digits.
3299             *
3300             * Notes:
3301             *<ul>
3302             * <li> This is performance-critical; most operations where a
3303             *      context is supplied will need at least one call to this
3304             *      method.
3305             *
3306             * <li> This should be a method on BigInteger; the call to this
3307             *      method in precision() can then be replaced with the
3308             *      term: intVal.digitLength().  It could also be called
3309             *      precision() in BigInteger.
3310             *
3311             *      Better still -- the precision lookaside could be moved to
3312             *      BigInteger, too.
3313             *
3314             * <li> This could/should use MutableBigIntegers directly for the
3315             *      reduction loop.
3316             *<ul>
3317             * @return the length of the unscaled value, in decimal digits
3318             */
3319            private int digitLength() {
3320                if (intCompact != INFLATED
3321                        && Math.abs(intCompact) <= Integer.MAX_VALUE)
3322                    return intLength(Math.abs((int) intCompact));
3323                if (signum() == 0) // 0 is one decimal digit
3324                    return 1;
3325                this .inflate();
3326                // we have a nonzero magnitude
3327                BigInteger work = intVal;
3328                int digits = 0; // counter
3329                for (; work.mag.length > 1;) {
3330                    // here when more than one integer in the magnitude; divide
3331                    // by a billion (reduce by 9 digits) and try again
3332                    work = work.divide(TENPOWERS[9]);
3333                    digits += 9;
3334                    if (work.signum() == 0) // the division was exact
3335                        return digits; // (a power of a billion)
3336                }
3337                // down to a simple nonzero integer
3338                digits += intLength(work.mag[0]);
3339                // System.out.println("digitLength... "+this+"  ->  "+digits);
3340                return digits;
3341            }
3342
3343            private static int[] ilogTable = { 0, 9, 99, 999, 9999, 99999,
3344                    999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE };
3345
3346            /**
3347             * Returns the length of an unsigned {@code int}, in decimal digits.
3348             * @param i the {@code int} (treated as unsigned)
3349             * @return the length of the unscaled value, in decimal digits
3350             */
3351            private int intLength(int x) {
3352                int digits;
3353                if (x < 0) { // 'negative' is 10 digits unsigned
3354                    return 10;
3355                } else { // positive integer
3356                    if (x <= 9)
3357                        return 1;
3358                    // "Hacker's Delight"  section 11-4
3359                    for (int i = -1;; i++) {
3360                        if (x <= ilogTable[i + 1])
3361                            return i + 1;
3362                    }
3363                }
3364            }
3365
3366            /**
3367             * Remove insignificant trailing zeros from this
3368             * {@code BigDecimal} until the preferred scale is reached or no
3369             * more zeros can be removed.  If the preferred scale is less than
3370             * Integer.MIN_VALUE, all the trailing zeros will be removed.
3371             *
3372             * {@code BigInteger} assistance could help, here?
3373             *
3374             * <p>WARNING: This method should only be called on new objects as
3375             * it mutates the value fields.
3376             *
3377             * @return this {@code BigDecimal} with a scale possibly reduced
3378             * to be closed to the preferred scale.
3379             */
3380            private BigDecimal stripZerosToMatchScale(long preferredScale) {
3381                boolean compact = (intCompact != INFLATED);
3382                this .inflate();
3383                BigInteger qr[]; // quotient-remainder pair
3384                while (intVal.abs().compareTo(BigInteger.TEN) >= 0
3385                        && scale > preferredScale) {
3386                    if (intVal.testBit(0))
3387                        break; // odd number cannot end in 0
3388                    qr = intVal.divideAndRemainder(BigInteger.TEN);
3389                    if (qr[1].signum() != 0)
3390                        break; // non-0 remainder
3391                    intVal = qr[0];
3392                    scale = checkScale((long) scale - 1); // could Overflow
3393                    if (precision > 0) // adjust precision if known
3394                        precision--;
3395                }
3396                if (compact)
3397                    intCompact = intVal.longValue();
3398                return this ;
3399            }
3400
3401            /**
3402             * Check a scale for Underflow or Overflow.  If this BigDecimal is
3403             * uninitialized or initialized and nonzero, throw an exception if
3404             * the scale is out of range.  If this is zero, saturate the scale
3405             * to the extreme value of the right sign if the scale is out of
3406             * range.
3407             *
3408             * @param val The new scale.
3409             * @throws ArithmeticException (overflow or underflow) if the new
3410             *         scale is out of range.
3411             * @return validated scale as an int.
3412             */
3413            private int checkScale(long val) {
3414                if ((int) val != val) {
3415                    if ((this .intCompact != INFLATED && this .intCompact != 0)
3416                            || (this .intVal != null && this .signum() != 0)
3417                            || (this .intVal == null && this .intCompact == INFLATED)) {
3418                        if (val > Integer.MAX_VALUE)
3419                            throw new ArithmeticException("Underflow");
3420                        if (val < Integer.MIN_VALUE)
3421                            throw new ArithmeticException("Overflow");
3422                    } else {
3423                        return (val > Integer.MAX_VALUE) ? Integer.MAX_VALUE
3424                                : Integer.MIN_VALUE;
3425                    }
3426                }
3427                return (int) val;
3428            }
3429
3430            /**
3431             * Round an operand; used only if digits &gt; 0.  Does not change
3432             * {@code this}; if rounding is needed a new {@code BigDecimal}
3433             * is created and returned.
3434             *
3435             * @param mc the context to use.
3436             * @throws ArithmeticException if the result is inexact but the
3437             *         rounding mode is {@code UNNECESSARY}.
3438             */
3439            private BigDecimal roundOp(MathContext mc) {
3440                BigDecimal rounded = doRound(mc);
3441                return rounded;
3442            }
3443
3444            /** Round this BigDecimal according to the MathContext settings;
3445             *  used only if precision {@literal >} 0.
3446             *
3447             * <p>WARNING: This method should only be called on new objects as
3448             * it mutates the value fields.
3449             *
3450             * @param mc the context to use.
3451             * @throws ArithmeticException if the rounding mode is
3452             *         {@code RoundingMode.UNNECESSARY} and the
3453             *         {@code BigDecimal} operation would require rounding.
3454             */
3455            private void roundThis(MathContext mc) {
3456                BigDecimal rounded = doRound(mc);
3457                if (rounded == this ) // wasn't rounded
3458                    return;
3459                this .intVal = rounded.intVal;
3460                this .intCompact = rounded.intCompact;
3461                this .scale = rounded.scale;
3462                this .precision = rounded.precision;
3463            }
3464
3465            /**
3466             * Returns a {@code BigDecimal} rounded according to the
3467             * MathContext settings; used only if {@code mc.precision > 0}.
3468             * Does not change {@code this}; if rounding is needed a new
3469             * {@code BigDecimal} is created and returned.
3470             *
3471             * @param mc the context to use.
3472             * @return a {@code BigDecimal} rounded according to the MathContext
3473             *         settings.  May return this, if no rounding needed.
3474             * @throws ArithmeticException if the rounding mode is
3475             *         {@code RoundingMode.UNNECESSARY} and the
3476             *         result is inexact.
3477             */
3478            private BigDecimal doRound(MathContext mc) {
3479                this .inflate();
3480                if (precision == 0) {
3481                    if (mc.roundingMax != null
3482                            && intVal.compareTo(mc.roundingMax) < 0
3483                            && intVal.compareTo(mc.roundingMin) > 0)
3484                        return this ; // no rounding needed
3485                    precision(); // find it
3486                }
3487                int drop = precision - mc.precision; // digits to discard
3488                if (drop <= 0) // we fit
3489                    return this ;
3490                BigDecimal rounded = dropDigits(mc, drop);
3491                // we need to double-check, in case of the 999=>1000 case
3492                return rounded.doRound(mc);
3493            }
3494
3495            /**
3496             * Removes digits from the significand of a {@code BigDecimal},
3497             * rounding according to the MathContext settings.  Does not
3498             * change {@code this}; a new {@code BigDecimal} is always
3499             * created and returned.
3500             * 
3501             * <p>Actual rounding is carried out, as before, by the divide
3502             * method, as this minimized code changes.  It might be more
3503             * efficient in most cases to move rounding to here, so we can do
3504             * a round-to-length rather than round-to-scale.
3505             *
3506             * @param mc the context to use.
3507             * @param drop the number of digits to drop, must be {@literal >} 0
3508             * @return a {@code BigDecimal} rounded according to the MathContext
3509             *         settings.  May return {@code this}, if no rounding needed.
3510             * @throws ArithmeticException if the rounding mode is
3511             *         {@code RoundingMode.UNNECESSARY} and the
3512             *         result is inexact.
3513             */
3514            private BigDecimal dropDigits(MathContext mc, int drop) {
3515                // here if we need to round; make the divisor = 10**drop)
3516                // [calculating the BigInteger here saves setScale later]
3517                BigDecimal divisor = new BigDecimal(tenToThe(drop), 0);
3518
3519                // divide to same scale to force round to length
3520                BigDecimal rounded = this .divide(divisor, scale,
3521                        mc.roundingMode.oldMode);
3522                rounded.scale = checkScale((long) rounded.scale - drop); // adjust the scale
3523                return rounded;
3524            }
3525
3526            private static int longCompareTo(long x, long y) {
3527                return (x < y) ? -1 : (x == y) ? 0 : 1;
3528            }
3529
3530            /*
3531             * Internal printing routine
3532             */
3533            private static void print(String name, BigDecimal bd) {
3534                System.err
3535                        .format(
3536                                "%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
3537                                name, bd.intCompact, bd.intVal, bd.scale,
3538                                bd.precision);
3539            }
3540
3541            /**
3542             * Check internal invariants of this BigDecimal.  These invariants
3543             * include:
3544             *
3545             * <ul>
3546             *
3547             * <li>The object must be initialized; either intCompact must not be
3548             * INFLATED or intVal is non-null.  Both of these conditions may
3549             * be true.
3550             *
3551             * <li>If both intCompact and intVal and set, their values must be
3552             * consistent.
3553             * 
3554             * <li>If precision is nonzero, it must have the right value.
3555             * </ul>
3556             */
3557            private BigDecimal audit() {
3558                // Check precision
3559                if (precision > 0) {
3560                    if (precision != digitLength()) {
3561                        print("audit", this );
3562                        throw new AssertionError("precision mismatch");
3563                    }
3564                }
3565
3566                if (intCompact == INFLATED) {
3567                    if (intVal == null) {
3568                        print("audit", this );
3569                        throw new AssertionError("null intVal");
3570                    }
3571                } else {
3572                    if (intVal != null) {
3573                        long val = intVal.longValue();
3574                        if (val != intCompact) {
3575                            print("audit", this );
3576                            throw new AssertionError(
3577                                    "Inconsistent state, intCompact="
3578                                            + intCompact + "\t intVal=" + val);
3579                        }
3580                    }
3581                }
3582                return this;
3583            }
3584        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.