0N/A/*
3475N/A * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
0N/A */
0N/A
0N/Apackage java.math;
0N/A
1246N/Aimport java.util.Arrays;
1246N/Aimport static java.math.BigInteger.LONG_MASK;
1246N/A
0N/A/**
0N/A * Immutable, arbitrary-precision signed decimal numbers. A
0N/A * {@code BigDecimal} consists of an arbitrary precision integer
0N/A * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
0N/A * or positive, the scale is the number of digits to the right of the
0N/A * decimal point. If negative, the unscaled value of the number is
0N/A * multiplied by ten to the power of the negation of the scale. The
0N/A * value of the number represented by the {@code BigDecimal} is
0N/A * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
0N/A *
0N/A * <p>The {@code BigDecimal} class provides operations for
0N/A * arithmetic, scale manipulation, rounding, comparison, hashing, and
0N/A * format conversion. The {@link #toString} method provides a
0N/A * canonical representation of a {@code BigDecimal}.
0N/A *
0N/A * <p>The {@code BigDecimal} class gives its user complete control
0N/A * over rounding behavior. If no rounding mode is specified and the
0N/A * exact result cannot be represented, an exception is thrown;
0N/A * otherwise, calculations can be carried out to a chosen precision
0N/A * and rounding mode by supplying an appropriate {@link MathContext}
0N/A * object to the operation. In either case, eight <em>rounding
0N/A * modes</em> are provided for the control of rounding. Using the
0N/A * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
0N/A * represent rounding mode is largely obsolete; the enumeration values
0N/A * of the {@code RoundingMode} {@code enum}, (such as {@link
0N/A * RoundingMode#HALF_UP}) should be used instead.
0N/A *
0N/A * <p>When a {@code MathContext} object is supplied with a precision
0N/A * setting of 0 (for example, {@link MathContext#UNLIMITED}),
0N/A * arithmetic operations are exact, as are the arithmetic methods
0N/A * which take no {@code MathContext} object. (This is the only
0N/A * behavior that was supported in releases prior to 5.) As a
0N/A * corollary of computing the exact result, the rounding mode setting
0N/A * of a {@code MathContext} object with a precision setting of 0 is
0N/A * not used and thus irrelevant. In the case of divide, the exact
0N/A * quotient could have an infinitely long decimal expansion; for
0N/A * example, 1 divided by 3. If the quotient has a nonterminating
0N/A * decimal expansion and the operation is specified to return an exact
0N/A * result, an {@code ArithmeticException} is thrown. Otherwise, the
0N/A * exact result of the division is returned, as done for other
0N/A * operations.
0N/A *
0N/A * <p>When the precision setting is not 0, the rules of
0N/A * {@code BigDecimal} arithmetic are broadly compatible with selected
0N/A * modes of operation of the arithmetic defined in ANSI X3.274-1996
0N/A * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
0N/A * standards, {@code BigDecimal} includes many rounding modes, which
0N/A * were mandatory for division in {@code BigDecimal} releases prior
0N/A * to 5. Any conflicts between these ANSI standards and the
0N/A * {@code BigDecimal} specification are resolved in favor of
0N/A * {@code BigDecimal}.
0N/A *
0N/A * <p>Since the same numerical value can have different
0N/A * representations (with different scales), the rules of arithmetic
0N/A * and rounding must specify both the numerical result and the scale
0N/A * used in the result's representation.
0N/A *
0N/A *
0N/A * <p>In general the rounding modes and precision setting determine
0N/A * how operations return results with a limited number of digits when
0N/A * the exact result has more digits (perhaps infinitely many in the
0N/A * case of division) than the number of digits returned.
0N/A *
0N/A * First, the
0N/A * total number of digits to return is specified by the
0N/A * {@code MathContext}'s {@code precision} setting; this determines
0N/A * the result's <i>precision</i>. The digit count starts from the
0N/A * leftmost nonzero digit of the exact result. The rounding mode
0N/A * determines how any discarded trailing digits affect the returned
0N/A * result.
0N/A *
0N/A * <p>For all arithmetic operators , the operation is carried out as
0N/A * though an exact intermediate result were first calculated and then
0N/A * rounded to the number of digits specified by the precision setting
0N/A * (if necessary), using the selected rounding mode. If the exact
0N/A * result is not returned, some digit positions of the exact result
0N/A * are discarded. When rounding increases the magnitude of the
0N/A * returned result, it is possible for a new digit position to be
0N/A * created by a carry propagating to a leading {@literal "9"} digit.
0N/A * For example, rounding the value 999.9 to three digits rounding up
0N/A * would be numerically equal to one thousand, represented as
0N/A * 100&times;10<sup>1</sup>. In such cases, the new {@literal "1"} is
0N/A * the leading digit position of the returned result.
0N/A *
0N/A * <p>Besides a logical exact result, each arithmetic operation has a
0N/A * preferred scale for representing a result. The preferred
0N/A * scale for each operation is listed in the table below.
0N/A *
0N/A * <table border>
3475N/A * <caption><b>Preferred Scales for Results of Arithmetic Operations
3475N/A * </b></caption>
0N/A * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
0N/A * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
0N/A * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
0N/A * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
0N/A * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
0N/A * </table>
0N/A *
0N/A * These scales are the ones used by the methods which return exact
0N/A * arithmetic results; except that an exact divide may have to use a
0N/A * larger scale since the exact result may have more digits. For
0N/A * example, {@code 1/32} is {@code 0.03125}.
0N/A *
0N/A * <p>Before rounding, the scale of the logical exact intermediate
0N/A * result is the preferred scale for that operation. If the exact
0N/A * numerical result cannot be represented in {@code precision}
0N/A * digits, rounding selects the set of digits to return and the scale
0N/A * of the result is reduced from the scale of the intermediate result
0N/A * to the least scale which can represent the {@code precision}
0N/A * digits actually returned. If the exact result can be represented
0N/A * with at most {@code precision} digits, the representation
0N/A * of the result with the scale closest to the preferred scale is
0N/A * returned. In particular, an exactly representable quotient may be
0N/A * represented in fewer than {@code precision} digits by removing
0N/A * trailing zeros and decreasing the scale. For example, rounding to
0N/A * three digits using the {@linkplain RoundingMode#FLOOR floor}
0N/A * rounding mode, <br>
0N/A *
0N/A * {@code 19/100 = 0.19 // integer=19, scale=2} <br>
0N/A *
0N/A * but<br>
0N/A *
0N/A * {@code 21/110 = 0.190 // integer=190, scale=3} <br>
0N/A *
0N/A * <p>Note that for add, subtract, and multiply, the reduction in
0N/A * scale will equal the number of digit positions of the exact result
0N/A * which are discarded. If the rounding causes a carry propagation to
0N/A * create a new high-order digit position, an additional digit of the
0N/A * result is discarded than when no new digit position is created.
0N/A *
0N/A * <p>Other methods may have slightly different rounding semantics.
0N/A * For example, the result of the {@code pow} method using the
0N/A * {@linkplain #pow(int, MathContext) specified algorithm} can
0N/A * occasionally differ from the rounded mathematical result by more
0N/A * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
0N/A *
0N/A * <p>Two types of operations are provided for manipulating the scale
0N/A * of a {@code BigDecimal}: scaling/rounding operations and decimal
0N/A * point motion operations. Scaling/rounding operations ({@link
0N/A * #setScale setScale} and {@link #round round}) return a
0N/A * {@code BigDecimal} whose value is approximately (or exactly) equal
0N/A * to that of the operand, but whose scale or precision is the
0N/A * specified value; that is, they increase or decrease the precision
0N/A * of the stored number with minimal effect on its value. Decimal
0N/A * point motion operations ({@link #movePointLeft movePointLeft} and
0N/A * {@link #movePointRight movePointRight}) return a
0N/A * {@code BigDecimal} created from the operand by moving the decimal
0N/A * point a specified distance in the specified direction.
0N/A *
0N/A * <p>For the sake of brevity and clarity, pseudo-code is used
0N/A * throughout the descriptions of {@code BigDecimal} methods. The
0N/A * pseudo-code expression {@code (i + j)} is shorthand for "a
0N/A * {@code BigDecimal} whose value is that of the {@code BigDecimal}
0N/A * {@code i} added to that of the {@code BigDecimal}
0N/A * {@code j}." The pseudo-code expression {@code (i == j)} is
0N/A * shorthand for "{@code true} if and only if the
0N/A * {@code BigDecimal} {@code i} represents the same value as the
0N/A * {@code BigDecimal} {@code j}." Other pseudo-code expressions
0N/A * are interpreted similarly. Square brackets are used to represent
0N/A * the particular {@code BigInteger} and scale pair defining a
0N/A * {@code BigDecimal} value; for example [19, 2] is the
0N/A * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
0N/A *
0N/A * <p>Note: care should be exercised if {@code BigDecimal} objects
0N/A * are used as keys in a {@link java.util.SortedMap SortedMap} or
0N/A * elements in a {@link java.util.SortedSet SortedSet} since
0N/A * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
0N/A * with equals</i>. See {@link Comparable}, {@link
0N/A * java.util.SortedMap} or {@link java.util.SortedSet} for more
0N/A * information.
0N/A *
0N/A * <p>All methods and constructors for this class throw
0N/A * {@code NullPointerException} when passed a {@code null} object
0N/A * reference for any input parameter.
0N/A *
0N/A * @see BigInteger
0N/A * @see MathContext
0N/A * @see RoundingMode
0N/A * @see java.util.SortedMap
0N/A * @see java.util.SortedSet
0N/A * @author Josh Bloch
0N/A * @author Mike Cowlishaw
0N/A * @author Joseph D. Darcy
0N/A */
0N/Apublic class BigDecimal extends Number implements Comparable<BigDecimal> {
0N/A /**
0N/A * The unscaled value of this BigDecimal, as returned by {@link
0N/A * #unscaledValue}.
0N/A *
0N/A * @serial
0N/A * @see #unscaledValue
0N/A */
0N/A private volatile BigInteger intVal;
0N/A
0N/A /**
0N/A * The scale of this BigDecimal, as returned by {@link #scale}.
0N/A *
0N/A * @serial
0N/A * @see #scale
0N/A */
1246N/A private int scale; // Note: this may have any value, so
1246N/A // calculations must be done in longs
0N/A /**
0N/A * The number of decimal digits in this BigDecimal, or 0 if the
0N/A * number of digits are not known (lookaside information). If
0N/A * nonzero, the value is guaranteed correct. Use the precision()
0N/A * method to obtain and set the value if it might be 0. This
0N/A * field is mutable until set nonzero.
0N/A *
0N/A * @since 1.5
0N/A */
1246N/A private transient int precision;
0N/A
0N/A /**
0N/A * Used to store the canonical string representation, if computed.
0N/A */
1246N/A private transient String stringCache;
0N/A
0N/A /**
0N/A * Sentinel value for {@link #intCompact} indicating the
0N/A * significand information is only available from {@code intVal}.
0N/A */
1246N/A static final long INFLATED = Long.MIN_VALUE;
0N/A
0N/A /**
0N/A * If the absolute value of the significand of this BigDecimal is
0N/A * less than or equal to {@code Long.MAX_VALUE}, the value can be
0N/A * compactly stored in this field and used in computations.
0N/A */
1246N/A private transient long intCompact;
0N/A
0N/A // All 18-digit base ten strings fit into a long; not all 19-digit
0N/A // strings will
0N/A private static final int MAX_COMPACT_DIGITS = 18;
0N/A
0N/A private static final int MAX_BIGINT_BITS = 62;
0N/A
0N/A /* Appease the serialization gods */
0N/A private static final long serialVersionUID = 6108874887143696463L;
0N/A
1246N/A private static final ThreadLocal<StringBuilderHelper>
1246N/A threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
1246N/A @Override
1246N/A protected StringBuilderHelper initialValue() {
1246N/A return new StringBuilderHelper();
1246N/A }
1246N/A };
1246N/A
0N/A // Cache of common small BigDecimal values.
0N/A private static final BigDecimal zeroThroughTen[] = {
1246N/A new BigDecimal(BigInteger.ZERO, 0, 0, 1),
1246N/A new BigDecimal(BigInteger.ONE, 1, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
1246N/A new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
1246N/A new BigDecimal(BigInteger.TEN, 10, 0, 2),
1246N/A };
1246N/A
1246N/A // Cache of zero scaled by 0 - 15
1246N/A private static final BigDecimal[] ZERO_SCALED_BY = {
1246N/A zeroThroughTen[0],
1246N/A new BigDecimal(BigInteger.ZERO, 0, 1, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 2, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 3, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 4, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 5, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 6, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 7, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 8, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 9, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 10, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 11, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 12, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 13, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 14, 1),
1246N/A new BigDecimal(BigInteger.ZERO, 0, 15, 1),
0N/A };
0N/A
1598N/A // Half of Long.MIN_VALUE & Long.MAX_VALUE.
1598N/A private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
1598N/A private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
1598N/A
0N/A // Constants
0N/A /**
0N/A * The value 0, with a scale of 0.
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public static final BigDecimal ZERO =
0N/A zeroThroughTen[0];
0N/A
0N/A /**
0N/A * The value 1, with a scale of 0.
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public static final BigDecimal ONE =
0N/A zeroThroughTen[1];
0N/A
0N/A /**
0N/A * The value 10, with a scale of 0.
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public static final BigDecimal TEN =
0N/A zeroThroughTen[10];
0N/A
0N/A // Constructors
0N/A
0N/A /**
1246N/A * Trusted package private constructor.
1246N/A * Trusted simply means if val is INFLATED, intVal could not be null and
1246N/A * if intVal is null, val could not be INFLATED.
1246N/A */
1246N/A BigDecimal(BigInteger intVal, long val, int scale, int prec) {
1246N/A this.scale = scale;
1246N/A this.precision = prec;
1246N/A this.intCompact = val;
1246N/A this.intVal = intVal;
1246N/A }
1246N/A
1246N/A /**
0N/A * Translates a character array representation of a
0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0N/A * same sequence of characters as the {@link #BigDecimal(String)}
0N/A * constructor, while allowing a sub-array to be specified.
0N/A *
0N/A * <p>Note that if the sequence of characters is already available
0N/A * within a character array, using this constructor is faster than
0N/A * converting the {@code char} array to string and using the
0N/A * {@code BigDecimal(String)} constructor .
0N/A *
0N/A * @param in {@code char} array that is the source of characters.
0N/A * @param offset first character in the array to inspect.
0N/A * @param len number of characters to consider.
0N/A * @throws NumberFormatException if {@code in} is not a valid
0N/A * representation of a {@code BigDecimal} or the defined subarray
0N/A * is not wholly within {@code in}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(char[] in, int offset, int len) {
1246N/A // protect against huge length.
1246N/A if (offset+len > in.length || offset < 0)
1246N/A throw new NumberFormatException();
0N/A // This is the primary string to BigDecimal constructor; all
0N/A // incoming strings end up here; it uses explicit (inline)
0N/A // parsing for speed and generates at most one intermediate
1246N/A // (temporary) object (a char[] array) for non-compact case.
1246N/A
1246N/A // Use locals for all fields values until completion
1246N/A int prec = 0; // record precision value
1246N/A int scl = 0; // record scale value
1246N/A long rs = 0; // the compact value in long
1246N/A BigInteger rb = null; // the inflated value in BigInteger
0N/A
0N/A // use array bounds checking to handle too-long, len == 0,
0N/A // bad offset, etc.
0N/A try {
0N/A // handle the sign
0N/A boolean isneg = false; // assume positive
0N/A if (in[offset] == '-') {
0N/A isneg = true; // leading minus means negative
0N/A offset++;
0N/A len--;
0N/A } else if (in[offset] == '+') { // leading + allowed
0N/A offset++;
0N/A len--;
0N/A }
0N/A
0N/A // should now be at numeric part of the significand
1246N/A boolean dot = false; // true when there is a '.'
0N/A int cfirst = offset; // record start of integer
0N/A long exp = 0; // exponent
1246N/A char c; // current character
1246N/A
1246N/A boolean isCompact = (len <= MAX_COMPACT_DIGITS);
1246N/A // integer significand array & idx is the index to it. The array
1246N/A // is ONLY used when we can't use a compact representation.
1246N/A char coeff[] = isCompact ? null : new char[len];
1246N/A int idx = 0;
0N/A
0N/A for (; len > 0; offset++, len--) {
0N/A c = in[offset];
1246N/A // have digit
0N/A if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
1246N/A // First compact case, we need not to preserve the character
1246N/A // and we can just compute the value in place.
1246N/A if (isCompact) {
1246N/A int digit = Character.digit(c, 10);
1246N/A if (digit == 0) {
1246N/A if (prec == 0)
1246N/A prec = 1;
1246N/A else if (rs != 0) {
1246N/A rs *= 10;
1246N/A ++prec;
1246N/A } // else digit is a redundant leading zero
1246N/A } else {
1246N/A if (prec != 1 || rs != 0)
1246N/A ++prec; // prec unchanged if preceded by 0s
1246N/A rs = rs * 10 + digit;
1246N/A }
1246N/A } else { // the unscaled value is likely a BigInteger object.
1246N/A if (c == '0' || Character.digit(c, 10) == 0) {
1246N/A if (prec == 0) {
1246N/A coeff[idx] = c;
1246N/A prec = 1;
1246N/A } else if (idx != 0) {
1246N/A coeff[idx++] = c;
1246N/A ++prec;
1246N/A } // else c must be a redundant leading zero
1246N/A } else {
1246N/A if (prec != 1 || idx != 0)
1246N/A ++prec; // prec unchanged if preceded by 0s
1246N/A coeff[idx++] = c;
1246N/A }
1246N/A }
1246N/A if (dot)
1246N/A ++scl;
0N/A continue;
0N/A }
1246N/A // have dot
0N/A if (c == '.') {
0N/A // have dot
1246N/A if (dot) // two dots
0N/A throw new NumberFormatException();
1246N/A dot = true;
0N/A continue;
0N/A }
0N/A // exponent expected
0N/A if ((c != 'e') && (c != 'E'))
0N/A throw new NumberFormatException();
0N/A offset++;
0N/A c = in[offset];
0N/A len--;
1246N/A boolean negexp = (c == '-');
0N/A // optional sign
1246N/A if (negexp || c == '+') {
0N/A offset++;
0N/A c = in[offset];
0N/A len--;
0N/A }
0N/A if (len <= 0) // no exponent digits
0N/A throw new NumberFormatException();
0N/A // skip leading zeros in the exponent
0N/A while (len > 10 && Character.digit(c, 10) == 0) {
1246N/A offset++;
1246N/A c = in[offset];
1246N/A len--;
0N/A }
0N/A if (len > 10) // too many nonzero exponent digits
0N/A throw new NumberFormatException();
0N/A // c now holds first digit of exponent
0N/A for (;; len--) {
0N/A int v;
0N/A if (c >= '0' && c <= '9') {
0N/A v = c - '0';
0N/A } else {
0N/A v = Character.digit(c, 10);
0N/A if (v < 0) // not a digit
0N/A throw new NumberFormatException();
0N/A }
0N/A exp = exp * 10 + v;
0N/A if (len == 1)
0N/A break; // that was final character
0N/A offset++;
0N/A c = in[offset];
0N/A }
0N/A if (negexp) // apply sign
0N/A exp = -exp;
0N/A // Next test is required for backwards compatibility
0N/A if ((int)exp != exp) // overflow
0N/A throw new NumberFormatException();
0N/A break; // [saves a test]
1246N/A }
0N/A // here when no characters left
1246N/A if (prec == 0) // no digits found
0N/A throw new NumberFormatException();
0N/A
1246N/A // Adjust scale if exp is not zero.
0N/A if (exp != 0) { // had significant exponent
1246N/A // Can't call checkScale which relies on proper fields value
1246N/A long adjustedScale = scl - exp;
1246N/A if (adjustedScale > Integer.MAX_VALUE ||
1246N/A adjustedScale < Integer.MIN_VALUE)
0N/A throw new NumberFormatException("Scale out of range.");
1246N/A scl = (int)adjustedScale;
0N/A }
0N/A
0N/A // Remove leading zeros from precision (digits count)
1246N/A if (isCompact) {
1246N/A rs = isneg ? -rs : rs;
0N/A } else {
1246N/A char quick[];
1246N/A if (!isneg) {
1246N/A quick = (coeff.length != prec) ?
1246N/A Arrays.copyOf(coeff, prec) : coeff;
1246N/A } else {
1246N/A quick = new char[prec + 1];
1246N/A quick[0] = '-';
1246N/A System.arraycopy(coeff, 0, quick, 1, prec);
1246N/A }
1246N/A rb = new BigInteger(quick);
1246N/A rs = compactValFor(rb);
0N/A }
0N/A } catch (ArrayIndexOutOfBoundsException e) {
0N/A throw new NumberFormatException();
0N/A } catch (NegativeArraySizeException e) {
0N/A throw new NumberFormatException();
0N/A }
1246N/A this.scale = scl;
1246N/A this.precision = prec;
1246N/A this.intCompact = rs;
1246N/A this.intVal = (rs != INFLATED) ? null : rb;
0N/A }
0N/A
0N/A /**
0N/A * Translates a character array representation of a
0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0N/A * same sequence of characters as the {@link #BigDecimal(String)}
0N/A * constructor, while allowing a sub-array to be specified and
0N/A * with rounding according to the context settings.
0N/A *
0N/A * <p>Note that if the sequence of characters is already available
0N/A * within a character array, using this constructor is faster than
0N/A * converting the {@code char} array to string and using the
0N/A * {@code BigDecimal(String)} constructor .
0N/A *
0N/A * @param in {@code char} array that is the source of characters.
0N/A * @param offset first character in the array to inspect.
0N/A * @param len number of characters to consider..
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @throws NumberFormatException if {@code in} is not a valid
0N/A * representation of a {@code BigDecimal} or the defined subarray
0N/A * is not wholly within {@code in}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(char[] in, int offset, int len, MathContext mc) {
0N/A this(in, offset, len);
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates a character array representation of a
0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0N/A * same sequence of characters as the {@link #BigDecimal(String)}
0N/A * constructor.
0N/A *
0N/A * <p>Note that if the sequence of characters is already available
0N/A * as a character array, using this constructor is faster than
0N/A * converting the {@code char} array to string and using the
0N/A * {@code BigDecimal(String)} constructor .
0N/A *
0N/A * @param in {@code char} array that is the source of characters.
0N/A * @throws NumberFormatException if {@code in} is not a valid
0N/A * representation of a {@code BigDecimal}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(char[] in) {
0N/A this(in, 0, in.length);
0N/A }
0N/A
0N/A /**
0N/A * Translates a character array representation of a
0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the
0N/A * same sequence of characters as the {@link #BigDecimal(String)}
0N/A * constructor and with rounding according to the context
0N/A * settings.
0N/A *
0N/A * <p>Note that if the sequence of characters is already available
0N/A * as a character array, using this constructor is faster than
0N/A * converting the {@code char} array to string and using the
0N/A * {@code BigDecimal(String)} constructor .
0N/A *
0N/A * @param in {@code char} array that is the source of characters.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @throws NumberFormatException if {@code in} is not a valid
0N/A * representation of a {@code BigDecimal}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(char[] in, MathContext mc) {
0N/A this(in, 0, in.length, mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates the string representation of a {@code BigDecimal}
0N/A * into a {@code BigDecimal}. The string representation consists
0N/A * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
0N/A * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
0N/A * zero or more decimal digits ("the integer"), optionally
0N/A * followed by a fraction, optionally followed by an exponent.
0N/A *
0N/A * <p>The fraction consists of a decimal point followed by zero
0N/A * or more decimal digits. The string must contain at least one
0N/A * digit in either the integer or the fraction. The number formed
0N/A * by the sign, the integer and the fraction is referred to as the
0N/A * <i>significand</i>.
0N/A *
0N/A * <p>The exponent consists of the character {@code 'e'}
0N/A * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
0N/A * followed by one or more decimal digits. The value of the
0N/A * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
0N/A * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
0N/A *
0N/A * <p>More formally, the strings this constructor accepts are
0N/A * described by the following grammar:
0N/A * <blockquote>
0N/A * <dl>
0N/A * <dt><i>BigDecimalString:</i>
0N/A * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
0N/A * <p>
0N/A * <dt><i>Sign:</i>
0N/A * <dd>{@code +}
0N/A * <dd>{@code -}
0N/A * <p>
0N/A * <dt><i>Significand:</i>
0N/A * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
0N/A * <dd>{@code .} <i>FractionPart</i>
0N/A * <dd><i>IntegerPart</i>
0N/A * <p>
3475N/A * <dt><i>IntegerPart:</i>
3475N/A * <dd><i>Digits</i>
0N/A * <p>
3475N/A * <dt><i>FractionPart:</i>
3475N/A * <dd><i>Digits</i>
0N/A * <p>
3475N/A * <dt><i>Exponent:</i>
3475N/A * <dd><i>ExponentIndicator SignedInteger</i>
0N/A * <p>
0N/A * <dt><i>ExponentIndicator:</i>
0N/A * <dd>{@code e}
0N/A * <dd>{@code E}
0N/A * <p>
3475N/A * <dt><i>SignedInteger:</i>
3475N/A * <dd><i>Sign<sub>opt</sub> Digits</i>
0N/A * <p>
3475N/A * <dt><i>Digits:</i>
3475N/A * <dd><i>Digit</i>
3475N/A * <dd><i>Digits Digit</i>
0N/A * <p>
0N/A * <dt><i>Digit:</i>
0N/A * <dd>any character for which {@link Character#isDigit}
0N/A * returns {@code true}, including 0, 1, 2 ...
0N/A * </dl>
0N/A * </blockquote>
0N/A *
0N/A * <p>The scale of the returned {@code BigDecimal} will be the
0N/A * number of digits in the fraction, or zero if the string
0N/A * contains no decimal point, subject to adjustment for any
0N/A * exponent; if the string contains an exponent, the exponent is
0N/A * subtracted from the scale. The value of the resulting scale
0N/A * must lie between {@code Integer.MIN_VALUE} and
0N/A * {@code Integer.MAX_VALUE}, inclusive.
0N/A *
0N/A * <p>The character-to-digit mapping is provided by {@link
0N/A * java.lang.Character#digit} set to convert to radix 10. The
0N/A * String may not contain any extraneous characters (whitespace,
0N/A * for example).
0N/A *
0N/A * <p><b>Examples:</b><br>
0N/A * The value of the returned {@code BigDecimal} is equal to
0N/A * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
0N/A * For each string on the left, the resulting representation
0N/A * [{@code BigInteger}, {@code scale}] is shown on the right.
0N/A * <pre>
0N/A * "0" [0,0]
0N/A * "0.00" [0,2]
0N/A * "123" [123,0]
0N/A * "-123" [-123,0]
0N/A * "1.23E3" [123,-1]
0N/A * "1.23E+3" [123,-1]
0N/A * "12.3E+7" [123,-6]
0N/A * "12.0" [120,1]
0N/A * "12.3" [123,1]
0N/A * "0.00123" [123,5]
0N/A * "-1.23E-12" [-123,14]
0N/A * "1234.5E-4" [12345,5]
0N/A * "0E+7" [0,-7]
0N/A * "-0" [0,0]
0N/A * </pre>
0N/A *
0N/A * <p>Note: For values other than {@code float} and
0N/A * {@code double} NaN and &plusmn;Infinity, this constructor is
0N/A * compatible with the values returned by {@link Float#toString}
0N/A * and {@link Double#toString}. This is generally the preferred
0N/A * way to convert a {@code float} or {@code double} into a
0N/A * BigDecimal, as it doesn't suffer from the unpredictability of
0N/A * the {@link #BigDecimal(double)} constructor.
0N/A *
0N/A * @param val String representation of {@code BigDecimal}.
0N/A *
0N/A * @throws NumberFormatException if {@code val} is not a valid
0N/A * representation of a {@code BigDecimal}.
0N/A */
0N/A public BigDecimal(String val) {
0N/A this(val.toCharArray(), 0, val.length());
0N/A }
0N/A
0N/A /**
0N/A * Translates the string representation of a {@code BigDecimal}
0N/A * into a {@code BigDecimal}, accepting the same strings as the
0N/A * {@link #BigDecimal(String)} constructor, with rounding
0N/A * according to the context settings.
0N/A *
0N/A * @param val string representation of a {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @throws NumberFormatException if {@code val} is not a valid
0N/A * representation of a BigDecimal.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(String val, MathContext mc) {
0N/A this(val.toCharArray(), 0, val.length());
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code double} into a {@code BigDecimal} which
0N/A * is the exact decimal representation of the {@code double}'s
0N/A * binary floating-point value. The scale of the returned
0N/A * {@code BigDecimal} is the smallest value such that
0N/A * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
0N/A * <p>
0N/A * <b>Notes:</b>
0N/A * <ol>
0N/A * <li>
0N/A * The results of this constructor can be somewhat unpredictable.
0N/A * One might assume that writing {@code new BigDecimal(0.1)} in
0N/A * Java creates a {@code BigDecimal} which is exactly equal to
0N/A * 0.1 (an unscaled value of 1, with a scale of 1), but it is
0N/A * actually equal to
0N/A * 0.1000000000000000055511151231257827021181583404541015625.
0N/A * This is because 0.1 cannot be represented exactly as a
0N/A * {@code double} (or, for that matter, as a binary fraction of
0N/A * any finite length). Thus, the value that is being passed
0N/A * <i>in</i> to the constructor is not exactly equal to 0.1,
0N/A * appearances notwithstanding.
0N/A *
0N/A * <li>
0N/A * The {@code String} constructor, on the other hand, is
0N/A * perfectly predictable: writing {@code new BigDecimal("0.1")}
0N/A * creates a {@code BigDecimal} which is <i>exactly</i> equal to
0N/A * 0.1, as one would expect. Therefore, it is generally
0N/A * recommended that the {@linkplain #BigDecimal(String)
0N/A * <tt>String</tt> constructor} be used in preference to this one.
0N/A *
0N/A * <li>
0N/A * When a {@code double} must be used as a source for a
0N/A * {@code BigDecimal}, note that this constructor provides an
0N/A * exact conversion; it does not give the same result as
0N/A * converting the {@code double} to a {@code String} using the
0N/A * {@link Double#toString(double)} method and then using the
0N/A * {@link #BigDecimal(String)} constructor. To get that result,
0N/A * use the {@code static} {@link #valueOf(double)} method.
0N/A * </ol>
0N/A *
0N/A * @param val {@code double} value to be converted to
0N/A * {@code BigDecimal}.
0N/A * @throws NumberFormatException if {@code val} is infinite or NaN.
0N/A */
0N/A public BigDecimal(double val) {
0N/A if (Double.isInfinite(val) || Double.isNaN(val))
0N/A throw new NumberFormatException("Infinite or NaN");
0N/A
0N/A // Translate the double into sign, exponent and significand, according
0N/A // to the formulae in JLS, Section 20.10.22.
0N/A long valBits = Double.doubleToLongBits(val);
0N/A int sign = ((valBits >> 63)==0 ? 1 : -1);
0N/A int exponent = (int) ((valBits >> 52) & 0x7ffL);
0N/A long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
0N/A : (valBits & ((1L<<52) - 1)) | (1L<<52));
0N/A exponent -= 1075;
0N/A // At this point, val == sign * significand * 2**exponent.
0N/A
0N/A /*
0N/A * Special case zero to supress nonterminating normalization
0N/A * and bogus scale calculation.
0N/A */
0N/A if (significand == 0) {
0N/A intVal = BigInteger.ZERO;
0N/A intCompact = 0;
0N/A precision = 1;
0N/A return;
0N/A }
0N/A
0N/A // Normalize
0N/A while((significand & 1) == 0) { // i.e., significand is even
0N/A significand >>= 1;
0N/A exponent++;
0N/A }
0N/A
0N/A // Calculate intVal and scale
1246N/A long s = sign * significand;
1246N/A BigInteger b;
0N/A if (exponent < 0) {
1246N/A b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
0N/A scale = -exponent;
0N/A } else if (exponent > 0) {
1246N/A b = BigInteger.valueOf(2).pow(exponent).multiply(s);
1246N/A } else {
1246N/A b = BigInteger.valueOf(s);
0N/A }
1246N/A intCompact = compactValFor(b);
1246N/A intVal = (intCompact != INFLATED) ? null : b;
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code double} into a {@code BigDecimal}, with
0N/A * rounding according to the context settings. The scale of the
0N/A * {@code BigDecimal} is the smallest value such that
0N/A * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
0N/A *
0N/A * <p>The results of this constructor can be somewhat unpredictable
0N/A * and its use is generally not recommended; see the notes under
0N/A * the {@link #BigDecimal(double)} constructor.
0N/A *
0N/A * @param val {@code double} value to be converted to
0N/A * {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * RoundingMode is UNNECESSARY.
0N/A * @throws NumberFormatException if {@code val} is infinite or NaN.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(double val, MathContext mc) {
0N/A this(val);
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code BigInteger} into a {@code BigDecimal}.
0N/A * The scale of the {@code BigDecimal} is zero.
0N/A *
0N/A * @param val {@code BigInteger} value to be converted to
0N/A * {@code BigDecimal}.
0N/A */
0N/A public BigDecimal(BigInteger val) {
1246N/A intCompact = compactValFor(val);
1246N/A intVal = (intCompact != INFLATED) ? null : val;
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code BigInteger} into a {@code BigDecimal}
0N/A * rounding according to the context settings. The scale of the
0N/A * {@code BigDecimal} is zero.
0N/A *
0N/A * @param val {@code BigInteger} value to be converted to
0N/A * {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(BigInteger val, MathContext mc) {
1246N/A this(val);
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code BigInteger} unscaled value and an
0N/A * {@code int} scale into a {@code BigDecimal}. The value of
0N/A * the {@code BigDecimal} is
0N/A * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
0N/A *
0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}.
0N/A * @param scale scale of the {@code BigDecimal}.
0N/A */
0N/A public BigDecimal(BigInteger unscaledVal, int scale) {
0N/A // Negative scales are now allowed
1246N/A this(unscaledVal);
0N/A this.scale = scale;
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code BigInteger} unscaled value and an
0N/A * {@code int} scale into a {@code BigDecimal}, with rounding
0N/A * according to the context settings. The value of the
0N/A * {@code BigDecimal} is <tt>(unscaledVal &times;
0N/A * 10<sup>-scale</sup>)</tt>, rounded according to the
0N/A * {@code precision} and rounding mode settings.
0N/A *
0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}.
0N/A * @param scale scale of the {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1246N/A this(unscaledVal);
0N/A this.scale = scale;
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates an {@code int} into a {@code BigDecimal}. The
0N/A * scale of the {@code BigDecimal} is zero.
0N/A *
0N/A * @param val {@code int} value to be converted to
0N/A * {@code BigDecimal}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(int val) {
0N/A intCompact = val;
0N/A }
0N/A
0N/A /**
0N/A * Translates an {@code int} into a {@code BigDecimal}, with
0N/A * rounding according to the context settings. The scale of the
0N/A * {@code BigDecimal}, before any rounding, is zero.
0N/A *
0N/A * @param val {@code int} value to be converted to {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(int val, MathContext mc) {
0N/A intCompact = val;
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code long} into a {@code BigDecimal}. The
0N/A * scale of the {@code BigDecimal} is zero.
0N/A *
0N/A * @param val {@code long} value to be converted to {@code BigDecimal}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(long val) {
1246N/A this.intCompact = val;
1246N/A this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code long} into a {@code BigDecimal}, with
0N/A * rounding according to the context settings. The scale of the
0N/A * {@code BigDecimal}, before any rounding, is zero.
0N/A *
0N/A * @param val {@code long} value to be converted to {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal(long val, MathContext mc) {
1246N/A this(val);
0N/A if (mc.precision > 0)
0N/A roundThis(mc);
0N/A }
0N/A
0N/A // Static Factory Methods
0N/A
0N/A /**
0N/A * Translates a {@code long} unscaled value and an
0N/A * {@code int} scale into a {@code BigDecimal}. This
0N/A * {@literal "static factory method"} is provided in preference to
0N/A * a ({@code long}, {@code int}) constructor because it
0N/A * allows for reuse of frequently used {@code BigDecimal} values..
0N/A *
0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}.
0N/A * @param scale scale of the {@code BigDecimal}.
0N/A * @return a {@code BigDecimal} whose value is
0N/A * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
0N/A */
0N/A public static BigDecimal valueOf(long unscaledVal, int scale) {
1246N/A if (scale == 0)
1246N/A return valueOf(unscaledVal);
1246N/A else if (unscaledVal == 0) {
1246N/A if (scale > 0 && scale < ZERO_SCALED_BY.length)
1246N/A return ZERO_SCALED_BY[scale];
1246N/A else
1246N/A return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
0N/A }
1246N/A return new BigDecimal(unscaledVal == INFLATED ?
1246N/A BigInteger.valueOf(unscaledVal) : null,
1246N/A unscaledVal, scale, 0);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code long} value into a {@code BigDecimal}
0N/A * with a scale of zero. This {@literal "static factory method"}
0N/A * is provided in preference to a ({@code long}) constructor
0N/A * because it allows for reuse of frequently used
0N/A * {@code BigDecimal} values.
0N/A *
0N/A * @param val value of the {@code BigDecimal}.
0N/A * @return a {@code BigDecimal} whose value is {@code val}.
0N/A */
0N/A public static BigDecimal valueOf(long val) {
1246N/A if (val >= 0 && val < zeroThroughTen.length)
1246N/A return zeroThroughTen[(int)val];
1246N/A else if (val != INFLATED)
1246N/A return new BigDecimal(null, val, 0, 0);
1246N/A return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
0N/A }
0N/A
0N/A /**
0N/A * Translates a {@code double} into a {@code BigDecimal}, using
0N/A * the {@code double}'s canonical string representation provided
0N/A * by the {@link Double#toString(double)} method.
0N/A *
0N/A * <p><b>Note:</b> This is generally the preferred way to convert
0N/A * a {@code double} (or {@code float}) into a
0N/A * {@code BigDecimal}, as the value returned is equal to that
0N/A * resulting from constructing a {@code BigDecimal} from the
0N/A * result of using {@link Double#toString(double)}.
0N/A *
0N/A * @param val {@code double} to convert to a {@code BigDecimal}.
0N/A * @return a {@code BigDecimal} whose value is equal to or approximately
0N/A * equal to the value of {@code val}.
0N/A * @throws NumberFormatException if {@code val} is infinite or NaN.
0N/A * @since 1.5
0N/A */
0N/A public static BigDecimal valueOf(double val) {
0N/A // Reminder: a zero double returns '0.0', so we cannot fastpath
0N/A // to use the constant ZERO. This might be important enough to
0N/A // justify a factory approach, a cache, or a few private
0N/A // constants, later.
0N/A return new BigDecimal(Double.toString(val));
0N/A }
0N/A
0N/A // Arithmetic Operations
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this +
0N/A * augend)}, and whose scale is {@code max(this.scale(),
0N/A * augend.scale())}.
0N/A *
0N/A * @param augend value to be added to this {@code BigDecimal}.
0N/A * @return {@code this + augend}
0N/A */
0N/A public BigDecimal add(BigDecimal augend) {
1246N/A long xs = this.intCompact;
1246N/A long ys = augend.intCompact;
1246N/A BigInteger fst = (xs != INFLATED) ? null : this.intVal;
1246N/A BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
1246N/A int rscale = this.scale;
0N/A
1246N/A long sdiff = (long)rscale - augend.scale;
1246N/A if (sdiff != 0) {
1246N/A if (sdiff < 0) {
1246N/A int raise = checkScale(-sdiff);
1246N/A rscale = augend.scale;
1246N/A if (xs == INFLATED ||
1246N/A (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
1246N/A fst = bigMultiplyPowerTen(raise);
1246N/A } else {
1246N/A int raise = augend.checkScale(sdiff);
1246N/A if (ys == INFLATED ||
1246N/A (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
1246N/A snd = augend.bigMultiplyPowerTen(raise);
1246N/A }
0N/A }
1246N/A if (xs != INFLATED && ys != INFLATED) {
1246N/A long sum = xs + ys;
1246N/A // See "Hacker's Delight" section 2-12 for explanation of
1246N/A // the overflow test.
1246N/A if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
1307N/A return BigDecimal.valueOf(sum, rscale);
1246N/A }
1246N/A if (fst == null)
1246N/A fst = BigInteger.valueOf(xs);
1246N/A if (snd == null)
1246N/A snd = BigInteger.valueOf(ys);
1246N/A BigInteger sum = fst.add(snd);
1246N/A return (fst.signum == snd.signum) ?
1246N/A new BigDecimal(sum, INFLATED, rscale, 0) :
1246N/A new BigDecimal(sum, rscale);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
0N/A * with rounding according to the context settings.
0N/A *
0N/A * If either number is zero and the precision setting is nonzero then
0N/A * the other number, rounded if necessary, is used as the result.
0N/A *
0N/A * @param augend value to be added to this {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @return {@code this + augend}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal add(BigDecimal augend, MathContext mc) {
0N/A if (mc.precision == 0)
0N/A return add(augend);
0N/A BigDecimal lhs = this;
0N/A
0N/A // Could optimize if values are compact
0N/A this.inflate();
0N/A augend.inflate();
0N/A
0N/A // If either number is zero then the other number, rounded and
0N/A // scaled if necessary, is used as the result.
0N/A {
0N/A boolean lhsIsZero = lhs.signum() == 0;
0N/A boolean augendIsZero = augend.signum() == 0;
0N/A
0N/A if (lhsIsZero || augendIsZero) {
0N/A int preferredScale = Math.max(lhs.scale(), augend.scale());
0N/A BigDecimal result;
0N/A
0N/A // Could use a factory for zero instead of a new object
0N/A if (lhsIsZero && augendIsZero)
1246N/A return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
0N/A
1246N/A result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
0N/A
0N/A if (result.scale() == preferredScale)
0N/A return result;
1246N/A else if (result.scale() > preferredScale) {
1246N/A BigDecimal scaledResult =
1246N/A new BigDecimal(result.intVal, result.intCompact,
1246N/A result.scale, 0);
1246N/A scaledResult.stripZerosToMatchScale(preferredScale);
1246N/A return scaledResult;
1246N/A } else { // result.scale < preferredScale
0N/A int precisionDiff = mc.precision - result.precision();
0N/A int scaleDiff = preferredScale - result.scale();
0N/A
0N/A if (precisionDiff >= scaleDiff)
0N/A return result.setScale(preferredScale); // can achieve target scale
0N/A else
0N/A return result.setScale(result.scale() + precisionDiff);
0N/A }
0N/A }
0N/A }
0N/A
0N/A long padding = (long)lhs.scale - augend.scale;
0N/A if (padding != 0) { // scales differ; alignment needed
0N/A BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
0N/A matchScale(arg);
0N/A lhs = arg[0];
0N/A augend = arg[1];
0N/A }
0N/A
1246N/A BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
1246N/A lhs.scale);
1246N/A return doRound(d, mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns an array of length two, the sum of whose entries is
0N/A * equal to the rounded sum of the {@code BigDecimal} arguments.
0N/A *
0N/A * <p>If the digit positions of the arguments have a sufficient
0N/A * gap between them, the value smaller in magnitude can be
0N/A * condensed into a {@literal "sticky bit"} and the end result will
0N/A * round the same way <em>if</em> the precision of the final
0N/A * result does not include the high order digit of the small
0N/A * magnitude operand.
0N/A *
0N/A * <p>Note that while strictly speaking this is an optimization,
0N/A * it makes a much wider range of additions practical.
0N/A *
0N/A * <p>This corresponds to a pre-shift operation in a fixed
0N/A * precision floating-point adder; this method is complicated by
0N/A * variable precision of the result as determined by the
0N/A * MathContext. A more nuanced operation could implement a
0N/A * {@literal "right shift"} on the smaller magnitude operand so
0N/A * that the number of digits of the smaller operand could be
0N/A * reduced even though the significands partially overlapped.
0N/A */
0N/A private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
0N/A long padding, MathContext mc) {
0N/A assert padding != 0;
0N/A BigDecimal big;
0N/A BigDecimal small;
0N/A
0N/A if (padding < 0) { // lhs is big; augend is small
0N/A big = lhs;
0N/A small = augend;
0N/A } else { // lhs is small; augend is big
0N/A big = augend;
0N/A small = lhs;
0N/A }
0N/A
0N/A /*
0N/A * This is the estimated scale of an ulp of the result; it
0N/A * assumes that the result doesn't have a carry-out on a true
0N/A * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
0N/A * on borrowing (e.g. 100 - 1.2 => 98.8)
0N/A */
0N/A long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
0N/A
0N/A /*
0N/A * The low-order digit position of big is big.scale(). This
0N/A * is true regardless of whether big has a positive or
0N/A * negative scale. The high-order digit position of small is
0N/A * small.scale - (small.precision() - 1). To do the full
0N/A * condensation, the digit positions of big and small must be
0N/A * disjoint *and* the digit positions of small should not be
0N/A * directly visible in the result.
0N/A */
0N/A long smallHighDigitPos = (long)small.scale - small.precision() + 1;
0N/A if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
0N/A smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
0N/A small = BigDecimal.valueOf(small.signum(),
0N/A this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
0N/A }
0N/A
0N/A // Since addition is symmetric, preserving input order in
0N/A // returned operands doesn't matter
0N/A BigDecimal[] result = {big, small};
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this -
0N/A * subtrahend)}, and whose scale is {@code max(this.scale(),
0N/A * subtrahend.scale())}.
0N/A *
0N/A * @param subtrahend value to be subtracted from this {@code BigDecimal}.
0N/A * @return {@code this - subtrahend}
0N/A */
0N/A public BigDecimal subtract(BigDecimal subtrahend) {
1246N/A return add(subtrahend.negate());
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
0N/A * with rounding according to the context settings.
0N/A *
0N/A * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
0N/A * result. If this is zero then the result is {@code subtrahend.negate(mc)}.
0N/A *
0N/A * @param subtrahend value to be subtracted from this {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @return {@code this - subtrahend}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1246N/A BigDecimal nsubtrahend = subtrahend.negate();
0N/A if (mc.precision == 0)
1246N/A return add(nsubtrahend);
0N/A // share the special rounding code in add()
1246N/A return add(nsubtrahend, mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is <tt>(this &times;
0N/A * multiplicand)</tt>, and whose scale is {@code (this.scale() +
0N/A * multiplicand.scale())}.
0N/A *
0N/A * @param multiplicand value to be multiplied by this {@code BigDecimal}.
0N/A * @return {@code this * multiplicand}
0N/A */
0N/A public BigDecimal multiply(BigDecimal multiplicand) {
0N/A long x = this.intCompact;
0N/A long y = multiplicand.intCompact;
1246N/A int productScale = checkScale((long)scale + multiplicand.scale);
0N/A
0N/A // Might be able to do a more clever check incorporating the
0N/A // inflated check into the overflow computation.
0N/A if (x != INFLATED && y != INFLATED) {
0N/A /*
0N/A * If the product is not an overflowed value, continue
0N/A * to use the compact representation. if either of x or y
0N/A * is INFLATED, the product should also be regarded as
1246N/A * an overflow. Before using the overflow test suggested in
1246N/A * "Hacker's Delight" section 2-12, we perform quick checks
1246N/A * using the precision information to see whether the overflow
1246N/A * would occur since division is expensive on most CPUs.
0N/A */
0N/A long product = x * y;
1307N/A long prec = this.precision() + multiplicand.precision();
1246N/A if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
1307N/A return BigDecimal.valueOf(product, productScale);
1246N/A return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
1246N/A productScale, 0);
0N/A }
1246N/A BigInteger rb;
1246N/A if (x == INFLATED && y == INFLATED)
1246N/A rb = this.intVal.multiply(multiplicand.intVal);
1246N/A else if (x != INFLATED)
1246N/A rb = multiplicand.intVal.multiply(x);
1246N/A else
1246N/A rb = this.intVal.multiply(y);
1246N/A return new BigDecimal(rb, INFLATED, productScale, 0);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is <tt>(this &times;
0N/A * multiplicand)</tt>, with rounding according to the context settings.
0N/A *
0N/A * @param multiplicand value to be multiplied by this {@code BigDecimal}.
0N/A * @param mc the context to use.
0N/A * @return {@code this * multiplicand}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
0N/A if (mc.precision == 0)
0N/A return multiply(multiplicand);
1246N/A return doRound(this.multiply(multiplicand), mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, and whose scale is as specified. If rounding must
0N/A * be performed to generate a result with the specified scale, the
0N/A * specified rounding mode is applied.
0N/A *
0N/A * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
0N/A * should be used in preference to this legacy method.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param scale scale of the {@code BigDecimal} quotient to be returned.
0N/A * @param roundingMode rounding mode to apply.
0N/A * @return {@code this / divisor}
0N/A * @throws ArithmeticException if {@code divisor} is zero,
0N/A * {@code roundingMode==ROUND_UNNECESSARY} and
0N/A * the specified scale is insufficient to represent the result
0N/A * of the division exactly.
0N/A * @throws IllegalArgumentException if {@code roundingMode} does not
0N/A * represent a valid rounding mode.
0N/A * @see #ROUND_UP
0N/A * @see #ROUND_DOWN
0N/A * @see #ROUND_CEILING
0N/A * @see #ROUND_FLOOR
0N/A * @see #ROUND_HALF_UP
0N/A * @see #ROUND_HALF_DOWN
0N/A * @see #ROUND_HALF_EVEN
0N/A * @see #ROUND_UNNECESSARY
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
0N/A /*
0N/A * IMPLEMENTATION NOTE: This method *must* return a new object
1246N/A * since divideAndRound uses divide to generate a value whose
0N/A * scale is then modified.
0N/A */
0N/A if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
0N/A throw new IllegalArgumentException("Invalid rounding mode");
0N/A /*
0N/A * Rescale dividend or divisor (whichever can be "upscaled" to
0N/A * produce correctly scaled quotient).
0N/A * Take care to detect out-of-range scales
0N/A */
1246N/A BigDecimal dividend = this;
1246N/A if (checkScale((long)scale + divisor.scale) > this.scale)
1246N/A dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
1246N/A else
1246N/A divisor = divisor.setScale(checkScale((long)this.scale - scale),
1246N/A ROUND_UNNECESSARY);
1246N/A return divideAndRound(dividend.intCompact, dividend.intVal,
1246N/A divisor.intCompact, divisor.intVal,
1246N/A scale, roundingMode, scale);
1246N/A }
0N/A
1246N/A /**
1246N/A * Internally used for division operation. The dividend and divisor are
1246N/A * passed both in {@code long} format and {@code BigInteger} format. The
1246N/A * returned {@code BigDecimal} object is the quotient whose scale is set to
1246N/A * the passed in scale. If the remainder is not zero, it will be rounded
1246N/A * based on the passed in roundingMode. Also, if the remainder is zero and
1246N/A * the last parameter, i.e. preferredScale is NOT equal to scale, the
1246N/A * trailing zeros of the result is stripped to match the preferredScale.
1246N/A */
1246N/A private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend,
1246N/A long ldivisor, BigInteger bdivisor,
1246N/A int scale, int roundingMode,
1246N/A int preferredScale) {
1246N/A boolean isRemainderZero; // record remainder is zero or not
1246N/A int qsign; // quotient sign
1246N/A long q = 0, r = 0; // store quotient & remainder in long
1246N/A MutableBigInteger mq = null; // store quotient
1246N/A MutableBigInteger mr = null; // store remainder
1246N/A MutableBigInteger mdivisor = null;
1246N/A boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
1246N/A if (isLongDivision) {
1246N/A q = ldividend / ldivisor;
1246N/A if (roundingMode == ROUND_DOWN && scale == preferredScale)
1246N/A return new BigDecimal(null, q, scale, 0);
1246N/A r = ldividend % ldivisor;
1246N/A isRemainderZero = (r == 0);
1246N/A qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
0N/A } else {
1246N/A if (bdividend == null)
1246N/A bdividend = BigInteger.valueOf(ldividend);
1246N/A // Descend into mutables for faster remainder checks
1246N/A MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
1246N/A mq = new MutableBigInteger();
1246N/A if (ldivisor != INFLATED) {
1246N/A r = mdividend.divide(ldivisor, mq);
1246N/A isRemainderZero = (r == 0);
1246N/A qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
1246N/A } else {
1246N/A mdivisor = new MutableBigInteger(bdivisor.mag);
1246N/A mr = mdividend.divide(mdivisor, mq);
1246N/A isRemainderZero = mr.isZero();
1246N/A qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
1246N/A }
0N/A }
1246N/A boolean increment = false;
1246N/A if (!isRemainderZero) {
0N/A int cmpFracHalf;
1246N/A /* Round as appropriate */
1246N/A if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited
1246N/A throw new ArithmeticException("Rounding necessary");
1246N/A } else if (roundingMode == ROUND_UP) { // Away from zero
1246N/A increment = true;
1246N/A } else if (roundingMode == ROUND_DOWN) { // Towards zero
1246N/A increment = false;
1246N/A } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1246N/A increment = (qsign > 0);
1246N/A } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
1246N/A increment = (qsign < 0);
0N/A } else {
1598N/A if (isLongDivision || ldivisor != INFLATED) {
1598N/A if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
1598N/A cmpFracHalf = 1; // 2 * r can't fit into long
1598N/A } else {
1598N/A cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
1598N/A }
1598N/A } else {
1246N/A cmpFracHalf = mr.compareHalf(mdivisor);
1598N/A }
1246N/A if (cmpFracHalf < 0)
1246N/A increment = false; // We're closer to higher digit
1246N/A else if (cmpFracHalf > 0) // We're closer to lower digit
1246N/A increment = true;
1246N/A else if (roundingMode == ROUND_HALF_UP)
0N/A increment = true;
0N/A else if (roundingMode == ROUND_HALF_DOWN)
0N/A increment = false;
1246N/A else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
1246N/A increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
0N/A }
0N/A }
1246N/A BigDecimal res;
1246N/A if (isLongDivision)
1246N/A res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
1246N/A else {
0N/A if (increment)
1246N/A mq.add(MutableBigInteger.ONE);
1246N/A res = mq.toBigDecimal(qsign, scale);
0N/A }
1246N/A if (isRemainderZero && preferredScale != scale)
1246N/A res.stripZerosToMatchScale(preferredScale);
1246N/A return res;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, and whose scale is as specified. If rounding must
0N/A * be performed to generate a result with the specified scale, the
0N/A * specified rounding mode is applied.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param scale scale of the {@code BigDecimal} quotient to be returned.
0N/A * @param roundingMode rounding mode to apply.
0N/A * @return {@code this / divisor}
0N/A * @throws ArithmeticException if {@code divisor} is zero,
0N/A * {@code roundingMode==RoundingMode.UNNECESSARY} and
0N/A * the specified scale is insufficient to represent the result
0N/A * of the division exactly.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
0N/A return divide(divisor, scale, roundingMode.oldMode);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, and whose scale is {@code this.scale()}. If
0N/A * rounding must be performed to generate a result with the given
0N/A * scale, the specified rounding mode is applied.
0N/A *
0N/A * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
0N/A * should be used in preference to this legacy method.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param roundingMode rounding mode to apply.
0N/A * @return {@code this / divisor}
0N/A * @throws ArithmeticException if {@code divisor==0}, or
0N/A * {@code roundingMode==ROUND_UNNECESSARY} and
0N/A * {@code this.scale()} is insufficient to represent the result
0N/A * of the division exactly.
0N/A * @throws IllegalArgumentException if {@code roundingMode} does not
0N/A * represent a valid rounding mode.
0N/A * @see #ROUND_UP
0N/A * @see #ROUND_DOWN
0N/A * @see #ROUND_CEILING
0N/A * @see #ROUND_FLOOR
0N/A * @see #ROUND_HALF_UP
0N/A * @see #ROUND_HALF_DOWN
0N/A * @see #ROUND_HALF_EVEN
0N/A * @see #ROUND_UNNECESSARY
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor, int roundingMode) {
0N/A return this.divide(divisor, scale, roundingMode);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, and whose scale is {@code this.scale()}. If
0N/A * rounding must be performed to generate a result with the given
0N/A * scale, the specified rounding mode is applied.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param roundingMode rounding mode to apply.
0N/A * @return {@code this / divisor}
0N/A * @throws ArithmeticException if {@code divisor==0}, or
0N/A * {@code roundingMode==RoundingMode.UNNECESSARY} and
0N/A * {@code this.scale()} is insufficient to represent the result
0N/A * of the division exactly.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
0N/A return this.divide(divisor, scale, roundingMode.oldMode);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, and whose preferred scale is {@code (this.scale() -
0N/A * divisor.scale())}; if the exact quotient cannot be
0N/A * represented (because it has a non-terminating decimal
0N/A * expansion) an {@code ArithmeticException} is thrown.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @throws ArithmeticException if the exact quotient does not have a
0N/A * terminating decimal expansion
0N/A * @return {@code this / divisor}
0N/A * @since 1.5
0N/A * @author Joseph D. Darcy
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor) {
0N/A /*
0N/A * Handle zero cases first.
0N/A */
0N/A if (divisor.signum() == 0) { // x/0
0N/A if (this.signum() == 0) // 0/0
0N/A throw new ArithmeticException("Division undefined"); // NaN
0N/A throw new ArithmeticException("Division by zero");
0N/A }
0N/A
0N/A // Calculate preferred scale
1246N/A int preferredScale = saturateLong((long)this.scale - divisor.scale);
0N/A if (this.signum() == 0) // 0/y
1246N/A return (preferredScale >= 0 &&
1246N/A preferredScale < ZERO_SCALED_BY.length) ?
1246N/A ZERO_SCALED_BY[preferredScale] :
1307N/A BigDecimal.valueOf(0, preferredScale);
0N/A else {
0N/A this.inflate();
0N/A divisor.inflate();
0N/A /*
0N/A * If the quotient this/divisor has a terminating decimal
0N/A * expansion, the expansion can have no more than
0N/A * (a.precision() + ceil(10*b.precision)/3) digits.
0N/A * Therefore, create a MathContext object with this
0N/A * precision and do a divide with the UNNECESSARY rounding
0N/A * mode.
0N/A */
0N/A MathContext mc = new MathContext( (int)Math.min(this.precision() +
0N/A (long)Math.ceil(10.0*divisor.precision()/3.0),
0N/A Integer.MAX_VALUE),
0N/A RoundingMode.UNNECESSARY);
0N/A BigDecimal quotient;
0N/A try {
0N/A quotient = this.divide(divisor, mc);
0N/A } catch (ArithmeticException e) {
0N/A throw new ArithmeticException("Non-terminating decimal expansion; " +
0N/A "no exact representable decimal result.");
0N/A }
0N/A
0N/A int quotientScale = quotient.scale();
0N/A
0N/A // divide(BigDecimal, mc) tries to adjust the quotient to
0N/A // the desired one by removing trailing zeros; since the
0N/A // exact divide method does not have an explicit digit
0N/A // limit, we can add zeros too.
0N/A
0N/A if (preferredScale > quotientScale)
1246N/A return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
0N/A
0N/A return quotient;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this /
0N/A * divisor)}, with rounding according to the context settings.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param mc the context to use.
0N/A * @return {@code this / divisor}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY} or
0N/A * {@code mc.precision == 0} and the quotient has a
0N/A * non-terminating decimal expansion.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1246N/A int mcp = mc.precision;
1246N/A if (mcp == 0)
0N/A return divide(divisor);
0N/A
1246N/A BigDecimal dividend = this;
1246N/A long preferredScale = (long)dividend.scale - divisor.scale;
0N/A // Now calculate the answer. We use the existing
0N/A // divide-and-round method, but as this rounds to scale we have
0N/A // to normalize the values here to achieve the desired result.
0N/A // For x/y we first handle y=0 and x=0, and then normalize x and
0N/A // y to give x' and y' with the following constraints:
0N/A // (a) 0.1 <= x' < 1
0N/A // (b) x' <= y' < 10*x'
0N/A // Dividing x'/y' with the required scale set to mc.precision then
0N/A // will give a result in the range 0.1 to 1 rounded to exactly
0N/A // the right number of digits (except in the case of a result of
0N/A // 1.000... which can arise when x=y, or when rounding overflows
0N/A // The 1.000... case will reduce properly to 1.
1246N/A if (divisor.signum() == 0) { // x/0
1246N/A if (dividend.signum() == 0) // 0/0
0N/A throw new ArithmeticException("Division undefined"); // NaN
0N/A throw new ArithmeticException("Division by zero");
0N/A }
1246N/A if (dividend.signum() == 0) // 0/y
1246N/A return new BigDecimal(BigInteger.ZERO, 0,
1246N/A saturateLong(preferredScale), 1);
1246N/A
1246N/A // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
1246N/A int xscale = dividend.precision();
1246N/A int yscale = divisor.precision();
1246N/A dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
1246N/A xscale, xscale);
1246N/A divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
1246N/A yscale, yscale);
1246N/A if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
1246N/A yscale = divisor.scale -= 1; // [that is, divisor *= 10]
0N/A
1246N/A // In order to find out whether the divide generates the exact result,
1246N/A // we avoid calling the above divide method. 'quotient' holds the
1246N/A // return BigDecimal object whose scale will be set to 'scl'.
1246N/A BigDecimal quotient;
1246N/A int scl = checkScale(preferredScale + yscale - xscale + mcp);
1246N/A if (checkScale((long)mcp + yscale) > xscale)
1246N/A dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
1246N/A else
1246N/A divisor = divisor.setScale(checkScale((long)xscale - mcp),
1246N/A ROUND_UNNECESSARY);
1246N/A quotient = divideAndRound(dividend.intCompact, dividend.intVal,
1246N/A divisor.intCompact, divisor.intVal,
1246N/A scl, mc.roundingMode.oldMode,
1246N/A checkScale(preferredScale));
1246N/A // doRound, here, only affects 1000000000 case.
1246N/A quotient = doRound(quotient, mc);
0N/A
1246N/A return quotient;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is the integer part
0N/A * of the quotient {@code (this / divisor)} rounded down. The
0N/A * preferred scale of the result is {@code (this.scale() -
0N/A * divisor.scale())}.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @return The integer part of {@code this / divisor}.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal divideToIntegralValue(BigDecimal divisor) {
0N/A // Calculate preferred scale
1246N/A int preferredScale = saturateLong((long)this.scale - divisor.scale);
1246N/A if (this.compareMagnitude(divisor) < 0) {
0N/A // much faster when this << divisor
0N/A return BigDecimal.valueOf(0, preferredScale);
0N/A }
0N/A
0N/A if(this.signum() == 0 && divisor.signum() != 0)
1246N/A return this.setScale(preferredScale, ROUND_UNNECESSARY);
0N/A
0N/A // Perform a divide with enough digits to round to a correct
0N/A // integer value; then remove any fractional digits
0N/A
0N/A int maxDigits = (int)Math.min(this.precision() +
0N/A (long)Math.ceil(10.0*divisor.precision()/3.0) +
0N/A Math.abs((long)this.scale() - divisor.scale()) + 2,
0N/A Integer.MAX_VALUE);
0N/A BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
0N/A RoundingMode.DOWN));
0N/A if (quotient.scale > 0) {
1246N/A quotient = quotient.setScale(0, RoundingMode.DOWN);
1246N/A quotient.stripZerosToMatchScale(preferredScale);
0N/A }
0N/A
0N/A if (quotient.scale < preferredScale) {
0N/A // pad with zeros if necessary
1246N/A quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
0N/A }
0N/A return quotient;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is the integer part
0N/A * of {@code (this / divisor)}. Since the integer part of the
0N/A * exact quotient does not depend on the rounding mode, the
0N/A * rounding mode does not affect the values returned by this
0N/A * method. The preferred scale of the result is
0N/A * {@code (this.scale() - divisor.scale())}. An
0N/A * {@code ArithmeticException} is thrown if the integer part of
0N/A * the exact quotient needs more than {@code mc.precision}
0N/A * digits.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param mc the context to use.
0N/A * @return The integer part of {@code this / divisor}.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
0N/A * requires a precision of more than {@code mc.precision} digits.
0N/A * @since 1.5
0N/A * @author Joseph D. Darcy
0N/A */
0N/A public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
0N/A if (mc.precision == 0 || // exact result
1246N/A (this.compareMagnitude(divisor) < 0) ) // zero result
0N/A return divideToIntegralValue(divisor);
0N/A
0N/A // Calculate preferred scale
1246N/A int preferredScale = saturateLong((long)this.scale - divisor.scale);
0N/A
0N/A /*
0N/A * Perform a normal divide to mc.precision digits. If the
0N/A * remainder has absolute value less than the divisor, the
0N/A * integer portion of the quotient fits into mc.precision
0N/A * digits. Next, remove any fractional digits from the
0N/A * quotient and adjust the scale to the preferred value.
0N/A */
1246N/A BigDecimal result = this.
1246N/A divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
0N/A
0N/A if (result.scale() < 0) {
0N/A /*
0N/A * Result is an integer. See if quotient represents the
0N/A * full integer portion of the exact quotient; if it does,
0N/A * the computed remainder will be less than the divisor.
0N/A */
0N/A BigDecimal product = result.multiply(divisor);
0N/A // If the quotient is the full integer value,
0N/A // |dividend-product| < |divisor|.
1246N/A if (this.subtract(product).compareMagnitude(divisor) >= 0) {
0N/A throw new ArithmeticException("Division impossible");
0N/A }
0N/A } else if (result.scale() > 0) {
0N/A /*
0N/A * Integer portion of quotient will fit into precision
0N/A * digits; recompute quotient to scale 0 to avoid double
0N/A * rounding and then try to adjust, if necessary.
0N/A */
0N/A result = result.setScale(0, RoundingMode.DOWN);
0N/A }
0N/A // else result.scale() == 0;
0N/A
0N/A int precisionDiff;
0N/A if ((preferredScale > result.scale()) &&
1246N/A (precisionDiff = mc.precision - result.precision()) > 0) {
0N/A return result.setScale(result.scale() +
0N/A Math.min(precisionDiff, preferredScale - result.scale) );
1246N/A } else {
1246N/A result.stripZerosToMatchScale(preferredScale);
1246N/A return result;
1246N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
0N/A *
0N/A * <p>The remainder is given by
0N/A * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
0N/A * Note that this is not the modulo operation (the result can be
0N/A * negative).
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @return {@code this % divisor}.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal remainder(BigDecimal divisor) {
0N/A BigDecimal divrem[] = this.divideAndRemainder(divisor);
0N/A return divrem[1];
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (this %
0N/A * divisor)}, with rounding according to the context settings.
0N/A * The {@code MathContext} settings affect the implicit divide
0N/A * used to compute the remainder. The remainder computation
0N/A * itself is by definition exact. Therefore, the remainder may
0N/A * contain more than {@code mc.getPrecision()} digits.
0N/A *
0N/A * <p>The remainder is given by
0N/A * {@code this.subtract(this.divideToIntegralValue(divisor,
0N/A * mc).multiply(divisor))}. Note that this is not the modulo
0N/A * operation (the result can be negative).
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided.
0N/A * @param mc the context to use.
0N/A * @return {@code this % divisor}, rounded as necessary.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
0N/A * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
0N/A * require a precision of more than {@code mc.precision} digits.
0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
0N/A BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
0N/A return divrem[1];
0N/A }
0N/A
0N/A /**
0N/A * Returns a two-element {@code BigDecimal} array containing the
0N/A * result of {@code divideToIntegralValue} followed by the result of
0N/A * {@code remainder} on the two operands.
0N/A *
0N/A * <p>Note that if both the integer quotient and remainder are
0N/A * needed, this method is faster than using the
0N/A * {@code divideToIntegralValue} and {@code remainder} methods
0N/A * separately because the division need only be carried out once.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided,
0N/A * and the remainder computed.
0N/A * @return a two element {@code BigDecimal} array: the quotient
0N/A * (the result of {@code divideToIntegralValue}) is the initial element
0N/A * and the remainder is the final element.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
0N/A * @see #remainder(java.math.BigDecimal, java.math.MathContext)
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
0N/A // we use the identity x = i * y + r to determine r
0N/A BigDecimal[] result = new BigDecimal[2];
0N/A
0N/A result[0] = this.divideToIntegralValue(divisor);
0N/A result[1] = this.subtract(result[0].multiply(divisor));
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns a two-element {@code BigDecimal} array containing the
0N/A * result of {@code divideToIntegralValue} followed by the result of
0N/A * {@code remainder} on the two operands calculated with rounding
0N/A * according to the context settings.
0N/A *
0N/A * <p>Note that if both the integer quotient and remainder are
0N/A * needed, this method is faster than using the
0N/A * {@code divideToIntegralValue} and {@code remainder} methods
0N/A * separately because the division need only be carried out once.
0N/A *
0N/A * @param divisor value by which this {@code BigDecimal} is to be divided,
0N/A * and the remainder computed.
0N/A * @param mc the context to use.
0N/A * @return a two element {@code BigDecimal} array: the quotient
0N/A * (the result of {@code divideToIntegralValue}) is the
0N/A * initial element and the remainder is the final element.
0N/A * @throws ArithmeticException if {@code divisor==0}
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
0N/A * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
0N/A * require a precision of more than {@code mc.precision} digits.
0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
0N/A * @see #remainder(java.math.BigDecimal, java.math.MathContext)
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
0N/A if (mc.precision == 0)
0N/A return divideAndRemainder(divisor);
0N/A
0N/A BigDecimal[] result = new BigDecimal[2];
0N/A BigDecimal lhs = this;
0N/A
0N/A result[0] = lhs.divideToIntegralValue(divisor, mc);
0N/A result[1] = lhs.subtract(result[0].multiply(divisor));
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is
0N/A * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
0N/A * unlimited precision.
0N/A *
0N/A * <p>The parameter {@code n} must be in the range 0 through
0N/A * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
0N/A * #ONE}.
0N/A *
0N/A * Note that future releases may expand the allowable exponent
0N/A * range of this method.
0N/A *
0N/A * @param n power to raise this {@code BigDecimal} to.
0N/A * @return <tt>this<sup>n</sup></tt>
0N/A * @throws ArithmeticException if {@code n} is out of range.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal pow(int n) {
0N/A if (n < 0 || n > 999999999)
0N/A throw new ArithmeticException("Invalid operation");
0N/A // No need to calculate pow(n) if result will over/underflow.
0N/A // Don't attempt to support "supernormal" numbers.
0N/A int newScale = checkScale((long)scale * n);
0N/A this.inflate();
0N/A return new BigDecimal(intVal.pow(n), newScale);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is
0N/A * <tt>(this<sup>n</sup>)</tt>. The current implementation uses
0N/A * the core algorithm defined in ANSI standard X3.274-1996 with
0N/A * rounding according to the context settings. In general, the
0N/A * returned numerical value is within two ulps of the exact
0N/A * numerical value for the chosen precision. Note that future
0N/A * releases may use a different algorithm with a decreased
0N/A * allowable error bound and increased allowable exponent range.
0N/A *
0N/A * <p>The X3.274-1996 algorithm is:
0N/A *
0N/A * <ul>
0N/A * <li> An {@code ArithmeticException} exception is thrown if
0N/A * <ul>
0N/A * <li>{@code abs(n) > 999999999}
0N/A * <li>{@code mc.precision == 0} and {@code n < 0}
0N/A * <li>{@code mc.precision > 0} and {@code n} has more than
0N/A * {@code mc.precision} decimal digits
0N/A * </ul>
0N/A *
0N/A * <li> if {@code n} is zero, {@link #ONE} is returned even if
0N/A * {@code this} is zero, otherwise
0N/A * <ul>
0N/A * <li> if {@code n} is positive, the result is calculated via
0N/A * the repeated squaring technique into a single accumulator.
0N/A * The individual multiplications with the accumulator use the
0N/A * same math context settings as in {@code mc} except for a
0N/A * precision increased to {@code mc.precision + elength + 1}
0N/A * where {@code elength} is the number of decimal digits in
0N/A * {@code n}.
0N/A *
0N/A * <li> if {@code n} is negative, the result is calculated as if
0N/A * {@code n} were positive; this value is then divided into one
0N/A * using the working precision specified above.
0N/A *
0N/A * <li> The final value from either the positive or negative case
0N/A * is then rounded to the destination precision.
0N/A * </ul>
0N/A * </ul>
0N/A *
0N/A * @param n power to raise this {@code BigDecimal} to.
0N/A * @param mc the context to use.
0N/A * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
0N/A * algorithm
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}, or {@code n} is out
0N/A * of range.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal pow(int n, MathContext mc) {
0N/A if (mc.precision == 0)
0N/A return pow(n);
0N/A if (n < -999999999 || n > 999999999)
0N/A throw new ArithmeticException("Invalid operation");
0N/A if (n == 0)
0N/A return ONE; // x**0 == 1 in X3.274
0N/A this.inflate();
0N/A BigDecimal lhs = this;
0N/A MathContext workmc = mc; // working settings
0N/A int mag = Math.abs(n); // magnitude of n
0N/A if (mc.precision > 0) {
0N/A
1246N/A int elength = longDigitLength(mag); // length of n in digits
0N/A if (elength > mc.precision) // X3.274 rule
0N/A throw new ArithmeticException("Invalid operation");
0N/A workmc = new MathContext(mc.precision + elength + 1,
0N/A mc.roundingMode);
0N/A }
0N/A // ready to carry out power calculation...
0N/A BigDecimal acc = ONE; // accumulator
0N/A boolean seenbit = false; // set once we've seen a 1-bit
0N/A for (int i=1;;i++) { // for each bit [top bit ignored]
0N/A mag += mag; // shift left 1 bit
0N/A if (mag < 0) { // top bit is set
0N/A seenbit = true; // OK, we're off
0N/A acc = acc.multiply(lhs, workmc); // acc=acc*x
0N/A }
0N/A if (i == 31)
0N/A break; // that was the last bit
0N/A if (seenbit)
0N/A acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
0N/A // else (!seenbit) no point in squaring ONE
0N/A }
0N/A // if negative n, calculate the reciprocal using working precision
0N/A if (n<0) // [hence mc.precision>0]
0N/A acc=ONE.divide(acc, workmc);
0N/A // round to final precision and strip zeros
1246N/A return doRound(acc, mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is the absolute value
0N/A * of this {@code BigDecimal}, and whose scale is
0N/A * {@code this.scale()}.
0N/A *
0N/A * @return {@code abs(this)}
0N/A */
0N/A public BigDecimal abs() {
0N/A return (signum() < 0 ? negate() : this);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is the absolute value
0N/A * of this {@code BigDecimal}, with rounding according to the
0N/A * context settings.
0N/A *
0N/A * @param mc the context to use.
0N/A * @return {@code abs(this)}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal abs(MathContext mc) {
0N/A return (signum() < 0 ? negate(mc) : plus(mc));
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (-this)},
0N/A * and whose scale is {@code this.scale()}.
0N/A *
0N/A * @return {@code -this}.
0N/A */
0N/A public BigDecimal negate() {
0N/A BigDecimal result;
0N/A if (intCompact != INFLATED)
0N/A result = BigDecimal.valueOf(-intCompact, scale);
0N/A else {
0N/A result = new BigDecimal(intVal.negate(), scale);
0N/A result.precision = precision;
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (-this)},
0N/A * with rounding according to the context settings.
0N/A *
0N/A * @param mc the context to use.
0N/A * @return {@code -this}, rounded as necessary.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal negate(MathContext mc) {
0N/A return negate().plus(mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
0N/A * scale is {@code this.scale()}.
0N/A *
0N/A * <p>This method, which simply returns this {@code BigDecimal}
0N/A * is included for symmetry with the unary minus method {@link
0N/A * #negate()}.
0N/A *
0N/A * @return {@code this}.
0N/A * @see #negate()
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal plus() {
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose value is {@code (+this)},
0N/A * with rounding according to the context settings.
0N/A *
0N/A * <p>The effect of this method is identical to that of the {@link
0N/A * #round(MathContext)} method.
0N/A *
0N/A * @param mc the context to use.
0N/A * @return {@code this}, rounded as necessary. A zero result will
0N/A * have a scale of 0.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A * @see #round(MathContext)
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal plus(MathContext mc) {
0N/A if (mc.precision == 0) // no rounding please
0N/A return this;
1246N/A return doRound(this, mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns the signum function of this {@code BigDecimal}.
0N/A *
0N/A * @return -1, 0, or 1 as the value of this {@code BigDecimal}
0N/A * is negative, zero, or positive.
0N/A */
0N/A public int signum() {
0N/A return (intCompact != INFLATED)?
0N/A Long.signum(intCompact):
0N/A intVal.signum();
0N/A }
0N/A
0N/A /**
0N/A * Returns the <i>scale</i> of this {@code BigDecimal}. If zero
0N/A * or positive, the scale is the number of digits to the right of
0N/A * the decimal point. If negative, the unscaled value of the
0N/A * number is multiplied by ten to the power of the negation of the
0N/A * scale. For example, a scale of {@code -3} means the unscaled
0N/A * value is multiplied by 1000.
0N/A *
0N/A * @return the scale of this {@code BigDecimal}.
0N/A */
0N/A public int scale() {
0N/A return scale;
0N/A }
0N/A
0N/A /**
0N/A * Returns the <i>precision</i> of this {@code BigDecimal}. (The
0N/A * precision is the number of digits in the unscaled value.)
0N/A *
0N/A * <p>The precision of a zero value is 1.
0N/A *
0N/A * @return the precision of this {@code BigDecimal}.
0N/A * @since 1.5
0N/A */
0N/A public int precision() {
0N/A int result = precision;
0N/A if (result == 0) {
1246N/A long s = intCompact;
1246N/A if (s != INFLATED)
1246N/A result = longDigitLength(s);
1246N/A else
1246N/A result = bigDigitLength(inflate());
0N/A precision = result;
0N/A }
0N/A return result;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Returns a {@code BigInteger} whose value is the <i>unscaled
0N/A * value</i> of this {@code BigDecimal}. (Computes <tt>(this *
0N/A * 10<sup>this.scale()</sup>)</tt>.)
0N/A *
0N/A * @return the unscaled value of this {@code BigDecimal}.
0N/A * @since 1.2
0N/A */
0N/A public BigInteger unscaledValue() {
1246N/A return this.inflate();
0N/A }
0N/A
0N/A // Rounding Modes
0N/A
0N/A /**
0N/A * Rounding mode to round away from zero. Always increments the
0N/A * digit prior to a nonzero discarded fraction. Note that this rounding
0N/A * mode never decreases the magnitude of the calculated value.
0N/A */
0N/A public final static int ROUND_UP = 0;
0N/A
0N/A /**
0N/A * Rounding mode to round towards zero. Never increments the digit
0N/A * prior to a discarded fraction (i.e., truncates). Note that this
0N/A * rounding mode never increases the magnitude of the calculated value.
0N/A */
0N/A public final static int ROUND_DOWN = 1;
0N/A
0N/A /**
0N/A * Rounding mode to round towards positive infinity. If the
0N/A * {@code BigDecimal} is positive, behaves as for
0N/A * {@code ROUND_UP}; if negative, behaves as for
0N/A * {@code ROUND_DOWN}. Note that this rounding mode never
0N/A * decreases the calculated value.
0N/A */
0N/A public final static int ROUND_CEILING = 2;
0N/A
0N/A /**
0N/A * Rounding mode to round towards negative infinity. If the
0N/A * {@code BigDecimal} is positive, behave as for
0N/A * {@code ROUND_DOWN}; if negative, behave as for
0N/A * {@code ROUND_UP}. Note that this rounding mode never
0N/A * increases the calculated value.
0N/A */
0N/A public final static int ROUND_FLOOR = 3;
0N/A
0N/A /**
0N/A * Rounding mode to round towards {@literal "nearest neighbor"}
0N/A * unless both neighbors are equidistant, in which case round up.
0N/A * Behaves as for {@code ROUND_UP} if the discarded fraction is
0N/A * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note
0N/A * that this is the rounding mode that most of us were taught in
0N/A * grade school.
0N/A */
0N/A public final static int ROUND_HALF_UP = 4;
0N/A
0N/A /**
0N/A * Rounding mode to round towards {@literal "nearest neighbor"}
0N/A * unless both neighbors are equidistant, in which case round
0N/A * down. Behaves as for {@code ROUND_UP} if the discarded
0N/A * fraction is {@literal >} 0.5; otherwise, behaves as for
0N/A * {@code ROUND_DOWN}.
0N/A */
0N/A public final static int ROUND_HALF_DOWN = 5;
0N/A
0N/A /**
0N/A * Rounding mode to round towards the {@literal "nearest neighbor"}
0N/A * unless both neighbors are equidistant, in which case, round
0N/A * towards the even neighbor. Behaves as for
0N/A * {@code ROUND_HALF_UP} if the digit to the left of the
0N/A * discarded fraction is odd; behaves as for
0N/A * {@code ROUND_HALF_DOWN} if it's even. Note that this is the
0N/A * rounding mode that minimizes cumulative error when applied
0N/A * repeatedly over a sequence of calculations.
0N/A */
0N/A public final static int ROUND_HALF_EVEN = 6;
0N/A
0N/A /**
0N/A * Rounding mode to assert that the requested operation has an exact
0N/A * result, hence no rounding is necessary. If this rounding mode is
0N/A * specified on an operation that yields an inexact result, an
0N/A * {@code ArithmeticException} is thrown.
0N/A */
0N/A public final static int ROUND_UNNECESSARY = 7;
0N/A
0N/A
0N/A // Scaling/Rounding Operations
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} rounded according to the
0N/A * {@code MathContext} settings. If the precision setting is 0 then
0N/A * no rounding takes place.
0N/A *
0N/A * <p>The effect of this method is identical to that of the
0N/A * {@link #plus(MathContext)} method.
0N/A *
0N/A * @param mc the context to use.
0N/A * @return a {@code BigDecimal} rounded according to the
0N/A * {@code MathContext} settings.
0N/A * @throws ArithmeticException if the rounding mode is
0N/A * {@code UNNECESSARY} and the
0N/A * {@code BigDecimal} operation would require rounding.
0N/A * @see #plus(MathContext)
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal round(MathContext mc) {
0N/A return plus(mc);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose scale is the specified
0N/A * value, and whose unscaled value is determined by multiplying or
0N/A * dividing this {@code BigDecimal}'s unscaled value by the
0N/A * appropriate power of ten to maintain its overall value. If the
0N/A * scale is reduced by the operation, the unscaled value must be
0N/A * divided (rather than multiplied), and the value may be changed;
0N/A * in this case, the specified rounding mode is applied to the
0N/A * division.
0N/A *
0N/A * <p>Note that since BigDecimal objects are immutable, calls of
0N/A * this method do <i>not</i> result in the original object being
0N/A * modified, contrary to the usual convention of having methods
0N/A * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
0N/A * Instead, {@code setScale} returns an object with the proper
0N/A * scale; the returned object may or may not be newly allocated.
0N/A *
0N/A * @param newScale scale of the {@code BigDecimal} value to be returned.
0N/A * @param roundingMode The rounding mode to apply.
0N/A * @return a {@code BigDecimal} whose scale is the specified value,
0N/A * and whose unscaled value is determined by multiplying or
0N/A * dividing this {@code BigDecimal}'s unscaled value by the
0N/A * appropriate power of ten to maintain its overall value.
0N/A * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
0N/A * and the specified scaling operation would require
0N/A * rounding.
0N/A * @see RoundingMode
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
0N/A return setScale(newScale, roundingMode.oldMode);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose scale is the specified
0N/A * value, and whose unscaled value is determined by multiplying or
0N/A * dividing this {@code BigDecimal}'s unscaled value by the
0N/A * appropriate power of ten to maintain its overall value. If the
0N/A * scale is reduced by the operation, the unscaled value must be
0N/A * divided (rather than multiplied), and the value may be changed;
0N/A * in this case, the specified rounding mode is applied to the
0N/A * division.
0N/A *
0N/A * <p>Note that since BigDecimal objects are immutable, calls of
0N/A * this method do <i>not</i> result in the original object being
0N/A * modified, contrary to the usual convention of having methods
0N/A * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
0N/A * Instead, {@code setScale} returns an object with the proper
0N/A * scale; the returned object may or may not be newly allocated.
0N/A *
0N/A * <p>The new {@link #setScale(int, RoundingMode)} method should
0N/A * be used in preference to this legacy method.
0N/A *
0N/A * @param newScale scale of the {@code BigDecimal} value to be returned.
0N/A * @param roundingMode The rounding mode to apply.
0N/A * @return a {@code BigDecimal} whose scale is the specified value,
0N/A * and whose unscaled value is determined by multiplying or
0N/A * dividing this {@code BigDecimal}'s unscaled value by the
0N/A * appropriate power of ten to maintain its overall value.
0N/A * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
0N/A * and the specified scaling operation would require
0N/A * rounding.
0N/A * @throws IllegalArgumentException if {@code roundingMode} does not
0N/A * represent a valid rounding mode.
0N/A * @see #ROUND_UP
0N/A * @see #ROUND_DOWN
0N/A * @see #ROUND_CEILING
0N/A * @see #ROUND_FLOOR
0N/A * @see #ROUND_HALF_UP
0N/A * @see #ROUND_HALF_DOWN
0N/A * @see #ROUND_HALF_EVEN
0N/A * @see #ROUND_UNNECESSARY
0N/A */
0N/A public BigDecimal setScale(int newScale, int roundingMode) {
0N/A if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
0N/A throw new IllegalArgumentException("Invalid rounding mode");
0N/A
1246N/A int oldScale = this.scale;
1246N/A if (newScale == oldScale) // easy case
0N/A return this;
0N/A if (this.signum() == 0) // zero can have any scale
0N/A return BigDecimal.valueOf(0, newScale);
0N/A
1246N/A long rs = this.intCompact;
1246N/A if (newScale > oldScale) {
1246N/A int raise = checkScale((long)newScale - oldScale);
1246N/A BigInteger rb = null;
1246N/A if (rs == INFLATED ||
1246N/A (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
1246N/A rb = bigMultiplyPowerTen(raise);
1246N/A return new BigDecimal(rb, rs, newScale,
1246N/A (precision > 0) ? precision + raise : 0);
1246N/A } else {
1246N/A // newScale < oldScale -- drop some digits
1246N/A // Can't predict the precision due to the effect of rounding.
1246N/A int drop = checkScale((long)oldScale - newScale);
1246N/A if (drop < LONG_TEN_POWERS_TABLE.length)
1246N/A return divideAndRound(rs, this.intVal,
1246N/A LONG_TEN_POWERS_TABLE[drop], null,
1246N/A newScale, roundingMode, newScale);
1246N/A else
1246N/A return divideAndRound(rs, this.intVal,
1246N/A INFLATED, bigTenToThe(drop),
1246N/A newScale, roundingMode, newScale);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} whose scale is the specified
0N/A * value, and whose value is numerically equal to this
0N/A * {@code BigDecimal}'s. Throws an {@code ArithmeticException}
0N/A * if this is not possible.
0N/A *
0N/A * <p>This call is typically used to increase the scale, in which
0N/A * case it is guaranteed that there exists a {@code BigDecimal}
0N/A * of the specified scale and the correct value. The call can
0N/A * also be used to reduce the scale if the caller knows that the
0N/A * {@code BigDecimal} has sufficiently many zeros at the end of
0N/A * its fractional part (i.e., factors of ten in its integer value)
0N/A * to allow for the rescaling without changing its value.
0N/A *
0N/A * <p>This method returns the same result as the two-argument
0N/A * versions of {@code setScale}, but saves the caller the trouble
0N/A * of specifying a rounding mode in cases where it is irrelevant.
0N/A *
0N/A * <p>Note that since {@code BigDecimal} objects are immutable,
0N/A * calls of this method do <i>not</i> result in the original
0N/A * object being modified, contrary to the usual convention of
0N/A * having methods named <tt>set<i>X</i></tt> mutate field
0N/A * <i>{@code X}</i>. Instead, {@code setScale} returns an
0N/A * object with the proper scale; the returned object may or may
0N/A * not be newly allocated.
0N/A *
0N/A * @param newScale scale of the {@code BigDecimal} value to be returned.
0N/A * @return a {@code BigDecimal} whose scale is the specified value, and
0N/A * whose unscaled value is determined by multiplying or dividing
0N/A * this {@code BigDecimal}'s unscaled value by the appropriate
0N/A * power of ten to maintain its overall value.
0N/A * @throws ArithmeticException if the specified scaling operation would
0N/A * require rounding.
0N/A * @see #setScale(int, int)
0N/A * @see #setScale(int, RoundingMode)
0N/A */
0N/A public BigDecimal setScale(int newScale) {
0N/A return setScale(newScale, ROUND_UNNECESSARY);
0N/A }
0N/A
0N/A // Decimal Point Motion Operations
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} which is equivalent to this one
0N/A * with the decimal point moved {@code n} places to the left. If
0N/A * {@code n} is non-negative, the call merely adds {@code n} to
0N/A * the scale. If {@code n} is negative, the call is equivalent
0N/A * to {@code movePointRight(-n)}. The {@code BigDecimal}
0N/A * returned by this call has value <tt>(this &times;
0N/A * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
0N/A * 0)}.
0N/A *
0N/A * @param n number of places to move the decimal point to the left.
0N/A * @return a {@code BigDecimal} which is equivalent to this one with the
0N/A * decimal point moved {@code n} places to the left.
0N/A * @throws ArithmeticException if scale overflows.
0N/A */
0N/A public BigDecimal movePointLeft(int n) {
0N/A // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
0N/A int newScale = checkScale((long)scale + n);
1246N/A BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
1246N/A return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} which is equivalent to this one
0N/A * with the decimal point moved {@code n} places to the right.
0N/A * If {@code n} is non-negative, the call merely subtracts
0N/A * {@code n} from the scale. If {@code n} is negative, the call
0N/A * is equivalent to {@code movePointLeft(-n)}. The
0N/A * {@code BigDecimal} returned by this call has value <tt>(this
0N/A * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
0N/A * 0)}.
0N/A *
0N/A * @param n number of places to move the decimal point to the right.
0N/A * @return a {@code BigDecimal} which is equivalent to this one
0N/A * with the decimal point moved {@code n} places to the right.
0N/A * @throws ArithmeticException if scale overflows.
0N/A */
0N/A public BigDecimal movePointRight(int n) {
0N/A // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
0N/A int newScale = checkScale((long)scale - n);
1246N/A BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
1246N/A return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
0N/A }
0N/A
0N/A /**
0N/A * Returns a BigDecimal whose numerical value is equal to
0N/A * ({@code this} * 10<sup>n</sup>). The scale of
0N/A * the result is {@code (this.scale() - n)}.
0N/A *
0N/A * @throws ArithmeticException if the scale would be
0N/A * outside the range of a 32-bit integer.
0N/A *
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal scaleByPowerOfTen(int n) {
1246N/A return new BigDecimal(intVal, intCompact,
1246N/A checkScale((long)scale - n), precision);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} which is numerically equal to
0N/A * this one but with any trailing zeros removed from the
0N/A * representation. For example, stripping the trailing zeros from
0N/A * the {@code BigDecimal} value {@code 600.0}, which has
0N/A * [{@code BigInteger}, {@code scale}] components equals to
0N/A * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
0N/A * {@code scale}] components equals to [6, -2]
0N/A *
0N/A * @return a numerically equal {@code BigDecimal} with any
0N/A * trailing zeros removed.
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal stripTrailingZeros() {
0N/A this.inflate();
1246N/A BigDecimal result = new BigDecimal(intVal, scale);
1246N/A result.stripZerosToMatchScale(Long.MIN_VALUE);
1246N/A return result;
0N/A }
0N/A
0N/A // Comparison Operations
0N/A
0N/A /**
0N/A * Compares this {@code BigDecimal} with the specified
0N/A * {@code BigDecimal}. Two {@code BigDecimal} objects that are
0N/A * equal in value but have a different scale (like 2.0 and 2.00)
0N/A * are considered equal by this method. This method is provided
0N/A * in preference to individual methods for each of the six boolean
0N/A * comparison operators ({@literal <}, ==,
0N/A * {@literal >}, {@literal >=}, !=, {@literal <=}). The
0N/A * suggested idiom for performing these comparisons is:
0N/A * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
0N/A * &lt;<i>op</i>&gt; is one of the six comparison operators.
0N/A *
0N/A * @param val {@code BigDecimal} to which this {@code BigDecimal} is
0N/A * to be compared.
0N/A * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
0N/A * less than, equal to, or greater than {@code val}.
0N/A */
0N/A public int compareTo(BigDecimal val) {
1246N/A // Quick path for equal scale and non-inflated case.
1246N/A if (scale == val.scale) {
1246N/A long xs = intCompact;
1246N/A long ys = val.intCompact;
1246N/A if (xs != INFLATED && ys != INFLATED)
1246N/A return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
1246N/A }
1246N/A int xsign = this.signum();
1246N/A int ysign = val.signum();
1246N/A if (xsign != ysign)
1246N/A return (xsign > ysign) ? 1 : -1;
1246N/A if (xsign == 0)
1246N/A return 0;
1246N/A int cmp = compareMagnitude(val);
1246N/A return (xsign > 0) ? cmp : -cmp;
1246N/A }
0N/A
1246N/A /**
1246N/A * Version of compareTo that ignores sign.
1246N/A */
1246N/A private int compareMagnitude(BigDecimal val) {
1246N/A // Match scales, avoid unnecessary inflation
1246N/A long ys = val.intCompact;
1246N/A long xs = this.intCompact;
1246N/A if (xs == 0)
1246N/A return (ys == 0) ? 0 : -1;
1246N/A if (ys == 0)
1246N/A return 1;
0N/A
1246N/A int sdiff = this.scale - val.scale;
1246N/A if (sdiff != 0) {
1246N/A // Avoid matching scales if the (adjusted) exponents differ
1246N/A int xae = this.precision() - this.scale; // [-1]
1246N/A int yae = val.precision() - val.scale; // [-1]
1246N/A if (xae < yae)
1246N/A return -1;
1246N/A if (xae > yae)
1246N/A return 1;
1246N/A BigInteger rb = null;
1246N/A if (sdiff < 0) {
1246N/A if ( (xs == INFLATED ||
1246N/A (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
1246N/A ys == INFLATED) {
1246N/A rb = bigMultiplyPowerTen(-sdiff);
1246N/A return rb.compareMagnitude(val.intVal);
1246N/A }
1246N/A } else { // sdiff > 0
1246N/A if ( (ys == INFLATED ||
1246N/A (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
1246N/A xs == INFLATED) {
1246N/A rb = val.bigMultiplyPowerTen(sdiff);
1246N/A return this.intVal.compareMagnitude(rb);
1246N/A }
1246N/A }
1246N/A }
1246N/A if (xs != INFLATED)
1246N/A return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
1246N/A else if (ys != INFLATED)
1246N/A return 1;
1246N/A else
1246N/A return this.intVal.compareMagnitude(val.intVal);
0N/A }
0N/A
0N/A /**
0N/A * Compares this {@code BigDecimal} with the specified
0N/A * {@code Object} for equality. Unlike {@link
0N/A * #compareTo(BigDecimal) compareTo}, this method considers two
0N/A * {@code BigDecimal} objects equal only if they are equal in
0N/A * value and scale (thus 2.0 is not equal to 2.00 when compared by
0N/A * this method).
0N/A *
0N/A * @param x {@code Object} to which this {@code BigDecimal} is
0N/A * to be compared.
0N/A * @return {@code true} if and only if the specified {@code Object} is a
0N/A * {@code BigDecimal} whose value and scale are equal to this
0N/A * {@code BigDecimal}'s.
0N/A * @see #compareTo(java.math.BigDecimal)
0N/A * @see #hashCode
0N/A */
1246N/A @Override
0N/A public boolean equals(Object x) {
0N/A if (!(x instanceof BigDecimal))
0N/A return false;
0N/A BigDecimal xDec = (BigDecimal) x;
1246N/A if (x == this)
1246N/A return true;
0N/A if (scale != xDec.scale)
0N/A return false;
1246N/A long s = this.intCompact;
1246N/A long xs = xDec.intCompact;
1246N/A if (s != INFLATED) {
1246N/A if (xs == INFLATED)
1246N/A xs = compactValFor(xDec.intVal);
1246N/A return xs == s;
1246N/A } else if (xs != INFLATED)
1246N/A return xs == compactValFor(this.intVal);
1246N/A
1246N/A return this.inflate().equals(xDec.inflate());
0N/A }
0N/A
0N/A /**
0N/A * Returns the minimum of this {@code BigDecimal} and
0N/A * {@code val}.
0N/A *
0N/A * @param val value with which the minimum is to be computed.
0N/A * @return the {@code BigDecimal} whose value is the lesser of this
0N/A * {@code BigDecimal} and {@code val}. If they are equal,
0N/A * as defined by the {@link #compareTo(BigDecimal) compareTo}
0N/A * method, {@code this} is returned.
0N/A * @see #compareTo(java.math.BigDecimal)
0N/A */
0N/A public BigDecimal min(BigDecimal val) {
0N/A return (compareTo(val) <= 0 ? this : val);
0N/A }
0N/A
0N/A /**
0N/A * Returns the maximum of this {@code BigDecimal} and {@code val}.
0N/A *
0N/A * @param val value with which the maximum is to be computed.
0N/A * @return the {@code BigDecimal} whose value is the greater of this
0N/A * {@code BigDecimal} and {@code val}. If they are equal,
0N/A * as defined by the {@link #compareTo(BigDecimal) compareTo}
0N/A * method, {@code this} is returned.
0N/A * @see #compareTo(java.math.BigDecimal)
0N/A */
0N/A public BigDecimal max(BigDecimal val) {
0N/A return (compareTo(val) >= 0 ? this : val);
0N/A }
0N/A
0N/A // Hash Function
0N/A
0N/A /**
0N/A * Returns the hash code for this {@code BigDecimal}. Note that
0N/A * two {@code BigDecimal} objects that are numerically equal but
0N/A * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
0N/A * have the same hash code.
0N/A *
0N/A * @return hash code for this {@code BigDecimal}.
0N/A * @see #equals(Object)
0N/A */
1246N/A @Override
0N/A public int hashCode() {
0N/A if (intCompact != INFLATED) {
1246N/A long val2 = (intCompact < 0)? -intCompact : intCompact;
0N/A int temp = (int)( ((int)(val2 >>> 32)) * 31 +
1246N/A (val2 & LONG_MASK));
0N/A return 31*((intCompact < 0) ?-temp:temp) + scale;
0N/A } else
0N/A return 31*intVal.hashCode() + scale;
0N/A }
0N/A
0N/A // Format Converters
0N/A
0N/A /**
0N/A * Returns the string representation of this {@code BigDecimal},
0N/A * using scientific notation if an exponent is needed.
0N/A *
0N/A * <p>A standard canonical string form of the {@code BigDecimal}
0N/A * is created as though by the following steps: first, the
0N/A * absolute value of the unscaled value of the {@code BigDecimal}
0N/A * is converted to a string in base ten using the characters
0N/A * {@code '0'} through {@code '9'} with no leading zeros (except
0N/A * if its value is zero, in which case a single {@code '0'}
0N/A * character is used).
0N/A *
0N/A * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
0N/A * negated scale, plus the number of characters in the converted
0N/A * unscaled value, less one. That is,
0N/A * {@code -scale+(ulength-1)}, where {@code ulength} is the
0N/A * length of the absolute value of the unscaled value in decimal
0N/A * digits (its <i>precision</i>).
0N/A *
0N/A * <p>If the scale is greater than or equal to zero and the
0N/A * adjusted exponent is greater than or equal to {@code -6}, the
0N/A * number will be converted to a character form without using
0N/A * exponential notation. In this case, if the scale is zero then
0N/A * no decimal point is added and if the scale is positive a
0N/A * decimal point will be inserted with the scale specifying the
0N/A * number of characters to the right of the decimal point.
0N/A * {@code '0'} characters are added to the left of the converted
0N/A * unscaled value as necessary. If no character precedes the
0N/A * decimal point after this insertion then a conventional
0N/A * {@code '0'} character is prefixed.
0N/A *
0N/A * <p>Otherwise (that is, if the scale is negative, or the
0N/A * adjusted exponent is less than {@code -6}), the number will be
0N/A * converted to a character form using exponential notation. In
0N/A * this case, if the converted {@code BigInteger} has more than
0N/A * one digit a decimal point is inserted after the first digit.
0N/A * An exponent in character form is then suffixed to the converted
0N/A * unscaled value (perhaps with inserted decimal point); this
0N/A * comprises the letter {@code 'E'} followed immediately by the
0N/A * adjusted exponent converted to a character form. The latter is
0N/A * in base ten, using the characters {@code '0'} through
0N/A * {@code '9'} with no leading zeros, and is always prefixed by a
0N/A * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the
0N/A * adjusted exponent is negative, {@code '+'}
0N/A * (<tt>'&#92;u002B'</tt>) otherwise).
0N/A *
0N/A * <p>Finally, the entire string is prefixed by a minus sign
0N/A * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled
0N/A * value is less than zero. No sign character is prefixed if the
0N/A * unscaled value is zero or positive.
0N/A *
0N/A * <p><b>Examples:</b>
0N/A * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
0N/A * on the left, the resulting string is shown on the right.
0N/A * <pre>
0N/A * [123,0] "123"
0N/A * [-123,0] "-123"
0N/A * [123,-1] "1.23E+3"
0N/A * [123,-3] "1.23E+5"
0N/A * [123,1] "12.3"
0N/A * [123,5] "0.00123"
0N/A * [123,10] "1.23E-8"
0N/A * [-123,12] "-1.23E-10"
0N/A * </pre>
0N/A *
0N/A * <b>Notes:</b>
0N/A * <ol>
0N/A *
0N/A * <li>There is a one-to-one mapping between the distinguishable
0N/A * {@code BigDecimal} values and the result of this conversion.
0N/A * That is, every distinguishable {@code BigDecimal} value
0N/A * (unscaled value and scale) has a unique string representation
0N/A * as a result of using {@code toString}. If that string
0N/A * representation is converted back to a {@code BigDecimal} using
0N/A * the {@link #BigDecimal(String)} constructor, then the original
0N/A * value will be recovered.
0N/A *
0N/A * <li>The string produced for a given number is always the same;
0N/A * it is not affected by locale. This means that it can be used
0N/A * as a canonical string representation for exchanging decimal
0N/A * data, or as a key for a Hashtable, etc. Locale-sensitive
0N/A * number formatting and parsing is handled by the {@link
0N/A * java.text.NumberFormat} class and its subclasses.
0N/A *
0N/A * <li>The {@link #toEngineeringString} method may be used for
0N/A * presenting numbers with exponents in engineering notation, and the
0N/A * {@link #setScale(int,RoundingMode) setScale} method may be used for
0N/A * rounding a {@code BigDecimal} so it has a known number of digits after
0N/A * the decimal point.
0N/A *
0N/A * <li>The digit-to-character mapping provided by
0N/A * {@code Character.forDigit} is used.
0N/A *
0N/A * </ol>
0N/A *
0N/A * @return string representation of this {@code BigDecimal}.
0N/A * @see Character#forDigit
0N/A * @see #BigDecimal(java.lang.String)
0N/A */
1246N/A @Override
0N/A public String toString() {
1246N/A String sc = stringCache;
1246N/A if (sc == null)
1246N/A stringCache = sc = layoutChars(true);
1246N/A return sc;
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this {@code BigDecimal},
0N/A * using engineering notation if an exponent is needed.
0N/A *
0N/A * <p>Returns a string that represents the {@code BigDecimal} as
0N/A * described in the {@link #toString()} method, except that if
0N/A * exponential notation is used, the power of ten is adjusted to
0N/A * be a multiple of three (engineering notation) such that the
0N/A * integer part of nonzero values will be in the range 1 through
0N/A * 999. If exponential notation is used for zero values, a
0N/A * decimal point and one or two fractional zero digits are used so
0N/A * that the scale of the zero value is preserved. Note that
0N/A * unlike the output of {@link #toString()}, the output of this
0N/A * method is <em>not</em> guaranteed to recover the same [integer,
0N/A * scale] pair of this {@code BigDecimal} if the output string is
0N/A * converting back to a {@code BigDecimal} using the {@linkplain
0N/A * #BigDecimal(String) string constructor}. The result of this method meets
0N/A * the weaker constraint of always producing a numerically equal
0N/A * result from applying the string constructor to the method's output.
0N/A *
0N/A * @return string representation of this {@code BigDecimal}, using
0N/A * engineering notation if an exponent is needed.
0N/A * @since 1.5
0N/A */
0N/A public String toEngineeringString() {
0N/A return layoutChars(false);
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this {@code BigDecimal}
0N/A * without an exponent field. For values with a positive scale,
0N/A * the number of digits to the right of the decimal point is used
0N/A * to indicate scale. For values with a zero or negative scale,
0N/A * the resulting string is generated as if the value were
0N/A * converted to a numerically equal value with zero scale and as
0N/A * if all the trailing zeros of the zero scale value were present
0N/A * in the result.
0N/A *
0N/A * The entire string is prefixed by a minus sign character '-'
0N/A * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
0N/A * zero. No sign character is prefixed if the unscaled value is
0N/A * zero or positive.
0N/A *
0N/A * Note that if the result of this method is passed to the
0N/A * {@linkplain #BigDecimal(String) string constructor}, only the
0N/A * numerical value of this {@code BigDecimal} will necessarily be
0N/A * recovered; the representation of the new {@code BigDecimal}
0N/A * may have a different scale. In particular, if this
0N/A * {@code BigDecimal} has a negative scale, the string resulting
0N/A * from this method will have a scale of zero when processed by
0N/A * the string constructor.
0N/A *
0N/A * (This method behaves analogously to the {@code toString}
0N/A * method in 1.4 and earlier releases.)
0N/A *
0N/A * @return a string representation of this {@code BigDecimal}
0N/A * without an exponent field.
0N/A * @since 1.5
0N/A * @see #toString()
0N/A * @see #toEngineeringString()
0N/A */
0N/A public String toPlainString() {
0N/A BigDecimal bd = this;
0N/A if (bd.scale < 0)
0N/A bd = bd.setScale(0);
0N/A bd.inflate();
0N/A if (bd.scale == 0) // No decimal point
0N/A return bd.intVal.toString();
0N/A return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
0N/A }
0N/A
0N/A /* Returns a digit.digit string */
0N/A private String getValueString(int signum, String intString, int scale) {
0N/A /* Insert decimal point */
0N/A StringBuilder buf;
0N/A int insertionPoint = intString.length() - scale;
0N/A if (insertionPoint == 0) { /* Point goes right before intVal */
0N/A return (signum<0 ? "-0." : "0.") + intString;
0N/A } else if (insertionPoint > 0) { /* Point goes inside intVal */
0N/A buf = new StringBuilder(intString);
0N/A buf.insert(insertionPoint, '.');
0N/A if (signum < 0)
0N/A buf.insert(0, '-');
0N/A } else { /* We must insert zeros between point and intVal */
0N/A buf = new StringBuilder(3-insertionPoint + intString.length());
0N/A buf.append(signum<0 ? "-0." : "0.");
0N/A for (int i=0; i<-insertionPoint; i++)
0N/A buf.append('0');
0N/A buf.append(intString);
0N/A }
0N/A return buf.toString();
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code BigInteger}.
4008N/A * This conversion is analogous to the
4008N/A * <i>narrowing primitive conversion</i> from {@code double} to
4008N/A * {@code long} as defined in section 5.1.3 of
4008N/A * <cite>The Java&trade; Language Specification</cite>:
4008N/A * any fractional part of this
0N/A * {@code BigDecimal} will be discarded. Note that this
0N/A * conversion can lose information about the precision of the
0N/A * {@code BigDecimal} value.
0N/A * <p>
0N/A * To have an exception thrown if the conversion is inexact (in
0N/A * other words if a nonzero fractional part is discarded), use the
0N/A * {@link #toBigIntegerExact()} method.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code BigInteger}.
0N/A */
0N/A public BigInteger toBigInteger() {
0N/A // force to an integer, quietly
1246N/A return this.setScale(0, ROUND_DOWN).inflate();
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code BigInteger},
0N/A * checking for lost information. An exception is thrown if this
0N/A * {@code BigDecimal} has a nonzero fractional part.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code BigInteger}.
0N/A * @throws ArithmeticException if {@code this} has a nonzero
0N/A * fractional part.
0N/A * @since 1.5
0N/A */
0N/A public BigInteger toBigIntegerExact() {
0N/A // round to an integer, with Exception if decimal part non-0
1246N/A return this.setScale(0, ROUND_UNNECESSARY).inflate();
0N/A }
0N/A
0N/A /**
4008N/A * Converts this {@code BigDecimal} to a {@code long}.
4008N/A * This conversion is analogous to the
4008N/A * <i>narrowing primitive conversion</i> from {@code double} to
4008N/A * {@code short} as defined in section 5.1.3 of
4008N/A * <cite>The Java&trade; Language Specification</cite>:
4008N/A * any fractional part of this
0N/A * {@code BigDecimal} will be discarded, and if the resulting
0N/A * "{@code BigInteger}" is too big to fit in a
0N/A * {@code long}, only the low-order 64 bits are returned.
0N/A * Note that this conversion can lose information about the
0N/A * overall magnitude and precision of this {@code BigDecimal} value as well
0N/A * as return a result with the opposite sign.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code long}.
0N/A */
0N/A public long longValue(){
0N/A return (intCompact != INFLATED && scale == 0) ?
0N/A intCompact:
0N/A toBigInteger().longValue();
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code long}, checking
0N/A * for lost information. If this {@code BigDecimal} has a
0N/A * nonzero fractional part or is out of the possible range for a
0N/A * {@code long} result then an {@code ArithmeticException} is
0N/A * thrown.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code long}.
0N/A * @throws ArithmeticException if {@code this} has a nonzero
0N/A * fractional part, or will not fit in a {@code long}.
0N/A * @since 1.5
0N/A */
0N/A public long longValueExact() {
0N/A if (intCompact != INFLATED && scale == 0)
0N/A return intCompact;
0N/A // If more than 19 digits in integer part it cannot possibly fit
0N/A if ((precision() - scale) > 19) // [OK for negative scale too]
0N/A throw new java.lang.ArithmeticException("Overflow");
0N/A // Fastpath zero and < 1.0 numbers (the latter can be very slow
0N/A // to round if very small)
0N/A if (this.signum() == 0)
0N/A return 0;
0N/A if ((this.precision() - this.scale) <= 0)
0N/A throw new ArithmeticException("Rounding necessary");
0N/A // round to an integer, with Exception if decimal part non-0
1246N/A BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
0N/A if (num.precision() >= 19) // need to check carefully
0N/A LongOverflow.check(num);
1246N/A return num.inflate().longValue();
0N/A }
0N/A
0N/A private static class LongOverflow {
0N/A /** BigInteger equal to Long.MIN_VALUE. */
0N/A private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
0N/A
0N/A /** BigInteger equal to Long.MAX_VALUE. */
0N/A private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
0N/A
0N/A public static void check(BigDecimal num) {
1246N/A num.inflate();
0N/A if ((num.intVal.compareTo(LONGMIN) < 0) ||
0N/A (num.intVal.compareTo(LONGMAX) > 0))
0N/A throw new java.lang.ArithmeticException("Overflow");
0N/A }
0N/A }
0N/A
0N/A /**
4008N/A * Converts this {@code BigDecimal} to an {@code int}.
4008N/A * This conversion is analogous to the
4008N/A * <i>narrowing primitive conversion</i> from {@code double} to
4008N/A * {@code short} as defined in section 5.1.3 of
4008N/A * <cite>The Java&trade; Language Specification</cite>:
4008N/A * any fractional part of this
0N/A * {@code BigDecimal} will be discarded, and if the resulting
0N/A * "{@code BigInteger}" is too big to fit in an
0N/A * {@code int}, only the low-order 32 bits are returned.
0N/A * Note that this conversion can lose information about the
0N/A * overall magnitude and precision of this {@code BigDecimal}
0N/A * value as well as return a result with the opposite sign.
0N/A *
0N/A * @return this {@code BigDecimal} converted to an {@code int}.
0N/A */
0N/A public int intValue() {
0N/A return (intCompact != INFLATED && scale == 0) ?
0N/A (int)intCompact :
0N/A toBigInteger().intValue();
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to an {@code int}, checking
0N/A * for lost information. If this {@code BigDecimal} has a
0N/A * nonzero fractional part or is out of the possible range for an
0N/A * {@code int} result then an {@code ArithmeticException} is
0N/A * thrown.
0N/A *
0N/A * @return this {@code BigDecimal} converted to an {@code int}.
0N/A * @throws ArithmeticException if {@code this} has a nonzero
0N/A * fractional part, or will not fit in an {@code int}.
0N/A * @since 1.5
0N/A */
0N/A public int intValueExact() {
0N/A long num;
0N/A num = this.longValueExact(); // will check decimal part
0N/A if ((int)num != num)
0N/A throw new java.lang.ArithmeticException("Overflow");
0N/A return (int)num;
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code short}, checking
0N/A * for lost information. If this {@code BigDecimal} has a
0N/A * nonzero fractional part or is out of the possible range for a
0N/A * {@code short} result then an {@code ArithmeticException} is
0N/A * thrown.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code short}.
0N/A * @throws ArithmeticException if {@code this} has a nonzero
0N/A * fractional part, or will not fit in a {@code short}.
0N/A * @since 1.5
0N/A */
0N/A public short shortValueExact() {
0N/A long num;
0N/A num = this.longValueExact(); // will check decimal part
0N/A if ((short)num != num)
0N/A throw new java.lang.ArithmeticException("Overflow");
0N/A return (short)num;
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code byte}, checking
0N/A * for lost information. If this {@code BigDecimal} has a
0N/A * nonzero fractional part or is out of the possible range for a
0N/A * {@code byte} result then an {@code ArithmeticException} is
0N/A * thrown.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code byte}.
0N/A * @throws ArithmeticException if {@code this} has a nonzero
0N/A * fractional part, or will not fit in a {@code byte}.
0N/A * @since 1.5
0N/A */
0N/A public byte byteValueExact() {
0N/A long num;
0N/A num = this.longValueExact(); // will check decimal part
0N/A if ((byte)num != num)
0N/A throw new java.lang.ArithmeticException("Overflow");
0N/A return (byte)num;
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code float}.
4008N/A * This conversion is similar to the
4008N/A * <i>narrowing primitive conversion</i> from {@code double} to
4008N/A * {@code float} as defined in section 5.1.3 of
4008N/A * <cite>The Java&trade; Language Specification</cite>:
4008N/A * if this {@code BigDecimal} has too great a
0N/A * magnitude to represent as a {@code float}, it will be
0N/A * converted to {@link Float#NEGATIVE_INFINITY} or {@link
0N/A * Float#POSITIVE_INFINITY} as appropriate. Note that even when
0N/A * the return value is finite, this conversion can lose
0N/A * information about the precision of the {@code BigDecimal}
0N/A * value.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code float}.
0N/A */
0N/A public float floatValue(){
0N/A if (scale == 0 && intCompact != INFLATED)
0N/A return (float)intCompact;
0N/A // Somewhat inefficient, but guaranteed to work.
0N/A return Float.parseFloat(this.toString());
0N/A }
0N/A
0N/A /**
0N/A * Converts this {@code BigDecimal} to a {@code double}.
4008N/A * This conversion is similar to the
4008N/A * <i>narrowing primitive conversion</i> from {@code double} to
4008N/A * {@code float} as defined in section 5.1.3 of
4008N/A * <cite>The Java&trade; Language Specification</cite>:
4008N/A * if this {@code BigDecimal} has too great a
0N/A * magnitude represent as a {@code double}, it will be
0N/A * converted to {@link Double#NEGATIVE_INFINITY} or {@link
0N/A * Double#POSITIVE_INFINITY} as appropriate. Note that even when
0N/A * the return value is finite, this conversion can lose
0N/A * information about the precision of the {@code BigDecimal}
0N/A * value.
0N/A *
0N/A * @return this {@code BigDecimal} converted to a {@code double}.
0N/A */
0N/A public double doubleValue(){
0N/A if (scale == 0 && intCompact != INFLATED)
0N/A return (double)intCompact;
0N/A // Somewhat inefficient, but guaranteed to work.
0N/A return Double.parseDouble(this.toString());
0N/A }
0N/A
0N/A /**
0N/A * Returns the size of an ulp, a unit in the last place, of this
0N/A * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
0N/A * value is the positive distance between this value and the
0N/A * {@code BigDecimal} value next larger in magnitude with the
0N/A * same number of digits. An ulp of a zero value is numerically
0N/A * equal to 1 with the scale of {@code this}. The result is
0N/A * stored with the same scale as {@code this} so the result
0N/A * for zero and nonzero values is equal to {@code [1,
0N/A * this.scale()]}.
0N/A *
0N/A * @return the size of an ulp of {@code this}
0N/A * @since 1.5
0N/A */
0N/A public BigDecimal ulp() {
0N/A return BigDecimal.valueOf(1, this.scale());
0N/A }
0N/A
1246N/A
1246N/A // Private class to build a string representation for BigDecimal object.
1246N/A // "StringBuilderHelper" is constructed as a thread local variable so it is
1246N/A // thread safe. The StringBuilder field acts as a buffer to hold the temporary
1246N/A // representation of BigDecimal. The cmpCharArray holds all the characters for
1246N/A // the compact representation of BigDecimal (except for '-' sign' if it is
1246N/A // negative) if its intCompact field is not INFLATED. It is shared by all
1246N/A // calls to toString() and its variants in that particular thread.
1246N/A static class StringBuilderHelper {
1246N/A final StringBuilder sb; // Placeholder for BigDecimal string
1246N/A final char[] cmpCharArray; // character array to place the intCompact
1246N/A
1246N/A StringBuilderHelper() {
1246N/A sb = new StringBuilder();
1246N/A // All non negative longs can be made to fit into 19 character array.
1246N/A cmpCharArray = new char[19];
1246N/A }
1246N/A
1246N/A // Accessors.
1246N/A StringBuilder getStringBuilder() {
1246N/A sb.setLength(0);
1246N/A return sb;
1246N/A }
1246N/A
1246N/A char[] getCompactCharArray() {
1246N/A return cmpCharArray;
1246N/A }
1246N/A
1246N/A /**
1246N/A * Places characters representing the intCompact in {@code long} into
1246N/A * cmpCharArray and returns the offset to the array where the
1246N/A * representation starts.
1246N/A *
1246N/A * @param intCompact the number to put into the cmpCharArray.
1246N/A * @return offset to the array where the representation starts.
1246N/A * Note: intCompact must be greater or equal to zero.
1246N/A */
1246N/A int putIntCompact(long intCompact) {
1246N/A assert intCompact >= 0;
1246N/A
1246N/A long q;
1246N/A int r;
1246N/A // since we start from the least significant digit, charPos points to
1246N/A // the last character in cmpCharArray.
1246N/A int charPos = cmpCharArray.length;
1246N/A
1246N/A // Get 2 digits/iteration using longs until quotient fits into an int
1246N/A while (intCompact > Integer.MAX_VALUE) {
1246N/A q = intCompact / 100;
1246N/A r = (int)(intCompact - q * 100);
1246N/A intCompact = q;
1246N/A cmpCharArray[--charPos] = DIGIT_ONES[r];
1246N/A cmpCharArray[--charPos] = DIGIT_TENS[r];
1246N/A }
1246N/A
1246N/A // Get 2 digits/iteration using ints when i2 >= 100
1246N/A int q2;
1246N/A int i2 = (int)intCompact;
1246N/A while (i2 >= 100) {
1246N/A q2 = i2 / 100;
1246N/A r = i2 - q2 * 100;
1246N/A i2 = q2;
1246N/A cmpCharArray[--charPos] = DIGIT_ONES[r];
1246N/A cmpCharArray[--charPos] = DIGIT_TENS[r];
1246N/A }
1246N/A
1246N/A cmpCharArray[--charPos] = DIGIT_ONES[i2];
1246N/A if (i2 >= 10)
1246N/A cmpCharArray[--charPos] = DIGIT_TENS[i2];
1246N/A
1246N/A return charPos;
1246N/A }
1246N/A
1246N/A final static char[] DIGIT_TENS = {
1246N/A '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
1246N/A '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
1246N/A '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
1246N/A '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
1246N/A '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
1246N/A '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
1246N/A '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
1246N/A '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
1246N/A '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
1246N/A '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
1246N/A };
1246N/A
1246N/A final static char[] DIGIT_ONES = {
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1246N/A };
1246N/A }
0N/A
0N/A /**
0N/A * Lay out this {@code BigDecimal} into a {@code char[]} array.
0N/A * The Java 1.2 equivalent to this was called {@code getValueString}.
0N/A *
0N/A * @param sci {@code true} for Scientific exponential notation;
0N/A * {@code false} for Engineering
0N/A * @return string with canonical string representation of this
0N/A * {@code BigDecimal}
0N/A */
0N/A private String layoutChars(boolean sci) {
0N/A if (scale == 0) // zero scale is trivial
0N/A return (intCompact != INFLATED) ?
0N/A Long.toString(intCompact):
0N/A intVal.toString();
0N/A
1246N/A StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
1246N/A char[] coeff;
1246N/A int offset; // offset is the starting index for coeff array
0N/A // Get the significand as an absolute value
1246N/A if (intCompact != INFLATED) {
1246N/A offset = sbHelper.putIntCompact(Math.abs(intCompact));
1246N/A coeff = sbHelper.getCompactCharArray();
1246N/A } else {
1246N/A offset = 0;
1246N/A coeff = intVal.abs().toString().toCharArray();
1246N/A }
0N/A
0N/A // Construct a buffer, with sufficient capacity for all cases.
0N/A // If E-notation is needed, length will be: +1 if negative, +1
0N/A // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
0N/A // Otherwise it could have +1 if negative, plus leading "0.00000"
1246N/A StringBuilder buf = sbHelper.getStringBuilder();
0N/A if (signum() < 0) // prefix '-' if negative
0N/A buf.append('-');
1246N/A int coeffLen = coeff.length - offset;
1246N/A long adjusted = -(long)scale + (coeffLen -1);
0N/A if ((scale >= 0) && (adjusted >= -6)) { // plain number
1246N/A int pad = scale - coeffLen; // count of padding zeros
1246N/A if (pad >= 0) { // 0.xxx form
0N/A buf.append('0');
0N/A buf.append('.');
0N/A for (; pad>0; pad--) {
0N/A buf.append('0');
0N/A }
1246N/A buf.append(coeff, offset, coeffLen);
0N/A } else { // xx.xx form
1246N/A buf.append(coeff, offset, -pad);
0N/A buf.append('.');
1246N/A buf.append(coeff, -pad + offset, scale);
0N/A }
0N/A } else { // E-notation is needed
0N/A if (sci) { // Scientific notation
1246N/A buf.append(coeff[offset]); // first character
1246N/A if (coeffLen > 1) { // more to come
0N/A buf.append('.');
1246N/A buf.append(coeff, offset + 1, coeffLen - 1);
0N/A }
0N/A } else { // Engineering notation
0N/A int sig = (int)(adjusted % 3);
0N/A if (sig < 0)
0N/A sig += 3; // [adjusted was negative]
0N/A adjusted -= sig; // now a multiple of 3
0N/A sig++;
0N/A if (signum() == 0) {
0N/A switch (sig) {
0N/A case 1:
0N/A buf.append('0'); // exponent is a multiple of three
0N/A break;
0N/A case 2:
0N/A buf.append("0.00");
0N/A adjusted += 3;
0N/A break;
0N/A case 3:
0N/A buf.append("0.0");
0N/A adjusted += 3;
0N/A break;
0N/A default:
0N/A throw new AssertionError("Unexpected sig value " + sig);
0N/A }
1246N/A } else if (sig >= coeffLen) { // significand all in integer
1246N/A buf.append(coeff, offset, coeffLen);
0N/A // may need some zeros, too
1246N/A for (int i = sig - coeffLen; i > 0; i--)
0N/A buf.append('0');
0N/A } else { // xx.xxE form
1246N/A buf.append(coeff, offset, sig);
0N/A buf.append('.');
1246N/A buf.append(coeff, offset + sig, coeffLen - sig);
0N/A }
0N/A }
0N/A if (adjusted != 0) { // [!sci could have made 0]
0N/A buf.append('E');
0N/A if (adjusted > 0) // force sign for positive
0N/A buf.append('+');
0N/A buf.append(adjusted);
0N/A }
0N/A }
0N/A return buf.toString();
0N/A }
0N/A
0N/A /**
0N/A * Return 10 to the power n, as a {@code BigInteger}.
0N/A *
0N/A * @param n the power of ten to be returned (>=0)
0N/A * @return a {@code BigInteger} with the value (10<sup>n</sup>)
0N/A */
1246N/A private static BigInteger bigTenToThe(int n) {
1246N/A if (n < 0)
1246N/A return BigInteger.ZERO;
1246N/A
1246N/A if (n < BIG_TEN_POWERS_TABLE_MAX) {
1246N/A BigInteger[] pows = BIG_TEN_POWERS_TABLE;
1246N/A if (n < pows.length)
1246N/A return pows[n];
1246N/A else
1246N/A return expandBigIntegerTenPowers(n);
1246N/A }
0N/A // BigInteger.pow is slow, so make 10**n by constructing a
0N/A // BigInteger from a character string (still not very fast)
0N/A char tenpow[] = new char[n + 1];
0N/A tenpow[0] = '1';
0N/A for (int i = 1; i <= n; i++)
0N/A tenpow[i] = '0';
0N/A return new BigInteger(tenpow);
0N/A }
1246N/A
1246N/A /**
1246N/A * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
1246N/A *
1246N/A * @param n the power of ten to be returned (>=0)
1246N/A * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
1246N/A * in the meantime, the BIG_TEN_POWERS_TABLE array gets
1246N/A * expanded to the size greater than n.
1246N/A */
1246N/A private static BigInteger expandBigIntegerTenPowers(int n) {
1246N/A synchronized(BigDecimal.class) {
1246N/A BigInteger[] pows = BIG_TEN_POWERS_TABLE;
1246N/A int curLen = pows.length;
1246N/A // The following comparison and the above synchronized statement is
1246N/A // to prevent multiple threads from expanding the same array.
1246N/A if (curLen <= n) {
1246N/A int newLen = curLen << 1;
1246N/A while (newLen <= n)
1246N/A newLen <<= 1;
1246N/A pows = Arrays.copyOf(pows, newLen);
1246N/A for (int i = curLen; i < newLen; i++)
1246N/A pows[i] = pows[i - 1].multiply(BigInteger.TEN);
1246N/A // Based on the following facts:
1246N/A // 1. pows is a private local varible;
1246N/A // 2. the following store is a volatile store.
1246N/A // the newly created array elements can be safely published.
1246N/A BIG_TEN_POWERS_TABLE = pows;
1246N/A }
1246N/A return pows[n];
1246N/A }
1246N/A }
1246N/A
1246N/A private static final long[] LONG_TEN_POWERS_TABLE = {
1246N/A 1, // 0 / 10^0
1246N/A 10, // 1 / 10^1
1246N/A 100, // 2 / 10^2
1246N/A 1000, // 3 / 10^3
1246N/A 10000, // 4 / 10^4
1246N/A 100000, // 5 / 10^5
1246N/A 1000000, // 6 / 10^6
1246N/A 10000000, // 7 / 10^7
1246N/A 100000000, // 8 / 10^8
1246N/A 1000000000, // 9 / 10^9
1246N/A 10000000000L, // 10 / 10^10
1246N/A 100000000000L, // 11 / 10^11
1246N/A 1000000000000L, // 12 / 10^12
1246N/A 10000000000000L, // 13 / 10^13
1246N/A 100000000000000L, // 14 / 10^14
1246N/A 1000000000000000L, // 15 / 10^15
1246N/A 10000000000000000L, // 16 / 10^16
1246N/A 100000000000000000L, // 17 / 10^17
1246N/A 1000000000000000000L // 18 / 10^18
1246N/A };
1246N/A
1246N/A private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
0N/A BigInteger.valueOf(10), BigInteger.valueOf(100),
0N/A BigInteger.valueOf(1000), BigInteger.valueOf(10000),
0N/A BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
0N/A BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
1246N/A BigInteger.valueOf(1000000000),
1246N/A BigInteger.valueOf(10000000000L),
1246N/A BigInteger.valueOf(100000000000L),
1246N/A BigInteger.valueOf(1000000000000L),
1246N/A BigInteger.valueOf(10000000000000L),
1246N/A BigInteger.valueOf(100000000000000L),
1246N/A BigInteger.valueOf(1000000000000000L),
1246N/A BigInteger.valueOf(10000000000000000L),
1246N/A BigInteger.valueOf(100000000000000000L),
1246N/A BigInteger.valueOf(1000000000000000000L)
1246N/A };
1246N/A
1246N/A private static final int BIG_TEN_POWERS_TABLE_INITLEN =
1246N/A BIG_TEN_POWERS_TABLE.length;
1246N/A private static final int BIG_TEN_POWERS_TABLE_MAX =
1246N/A 16 * BIG_TEN_POWERS_TABLE_INITLEN;
1246N/A
1246N/A private static final long THRESHOLDS_TABLE[] = {
1246N/A Long.MAX_VALUE, // 0
1246N/A Long.MAX_VALUE/10L, // 1
1246N/A Long.MAX_VALUE/100L, // 2
1246N/A Long.MAX_VALUE/1000L, // 3
1246N/A Long.MAX_VALUE/10000L, // 4
1246N/A Long.MAX_VALUE/100000L, // 5
1246N/A Long.MAX_VALUE/1000000L, // 6
1246N/A Long.MAX_VALUE/10000000L, // 7
1246N/A Long.MAX_VALUE/100000000L, // 8
1246N/A Long.MAX_VALUE/1000000000L, // 9
1246N/A Long.MAX_VALUE/10000000000L, // 10
1246N/A Long.MAX_VALUE/100000000000L, // 11
1246N/A Long.MAX_VALUE/1000000000000L, // 12
1246N/A Long.MAX_VALUE/10000000000000L, // 13
1246N/A Long.MAX_VALUE/100000000000000L, // 14
1246N/A Long.MAX_VALUE/1000000000000000L, // 15
1246N/A Long.MAX_VALUE/10000000000000000L, // 16
1246N/A Long.MAX_VALUE/100000000000000000L, // 17
1246N/A Long.MAX_VALUE/1000000000000000000L // 18
1246N/A };
0N/A
0N/A /**
0N/A * Compute val * 10 ^ n; return this product if it is
0N/A * representable as a long, INFLATED otherwise.
0N/A */
1246N/A private static long longMultiplyPowerTen(long val, int n) {
1246N/A if (val == 0 || n <= 0)
1246N/A return val;
1246N/A long[] tab = LONG_TEN_POWERS_TABLE;
1246N/A long[] bounds = THRESHOLDS_TABLE;
1246N/A if (n < tab.length && n < bounds.length) {
1246N/A long tenpower = tab[n];
1246N/A if (val == 1)
1246N/A return tenpower;
1246N/A if (Math.abs(val) <= bounds[n])
1246N/A return val * tenpower;
0N/A }
0N/A return INFLATED;
0N/A }
0N/A
1246N/A /**
1246N/A * Compute this * 10 ^ n.
1246N/A * Needed mainly to allow special casing to trap zero value
1246N/A */
1246N/A private BigInteger bigMultiplyPowerTen(int n) {
1246N/A if (n <= 0)
1246N/A return this.inflate();
0N/A
1246N/A if (intCompact != INFLATED)
1246N/A return bigTenToThe(n).multiply(intCompact);
1246N/A else
1246N/A return intVal.multiply(bigTenToThe(n));
0N/A }
0N/A
0N/A /**
0N/A * Assign appropriate BigInteger to intVal field if intVal is
0N/A * null, i.e. the compact representation is in use.
0N/A */
1246N/A private BigInteger inflate() {
0N/A if (intVal == null)
0N/A intVal = BigInteger.valueOf(intCompact);
1246N/A return intVal;
0N/A }
0N/A
0N/A /**
0N/A * Match the scales of two {@code BigDecimal}s to align their
0N/A * least significant digits.
0N/A *
0N/A * <p>If the scales of val[0] and val[1] differ, rescale
0N/A * (non-destructively) the lower-scaled {@code BigDecimal} so
0N/A * they match. That is, the lower-scaled reference will be
0N/A * replaced by a reference to a new object with the same scale as
0N/A * the other {@code BigDecimal}.
0N/A *
0N/A * @param val array of two elements referring to the two
0N/A * {@code BigDecimal}s to be aligned.
0N/A */
0N/A private static void matchScale(BigDecimal[] val) {
1246N/A if (val[0].scale == val[1].scale) {
1246N/A return;
1246N/A } else if (val[0].scale < val[1].scale) {
1246N/A val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
1246N/A } else if (val[1].scale < val[0].scale) {
1246N/A val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
1246N/A }
0N/A }
0N/A
0N/A /**
0N/A * Reconstitute the {@code BigDecimal} instance from a stream (that is,
0N/A * deserialize it).
0N/A *
0N/A * @param s the stream being read.
0N/A */
0N/A private void readObject(java.io.ObjectInputStream s)
0N/A throws java.io.IOException, ClassNotFoundException {
0N/A // Read in all fields
0N/A s.defaultReadObject();
0N/A // validate possibly bad fields
0N/A if (intVal == null) {
0N/A String message = "BigDecimal: null intVal in stream";
0N/A throw new java.io.StreamCorruptedException(message);
0N/A // [all values of scale are now allowed]
0N/A }
1246N/A intCompact = compactValFor(intVal);
0N/A }
0N/A
0N/A /**
0N/A * Serialize this {@code BigDecimal} to the stream in question
0N/A *
0N/A * @param s the stream to serialize to.
0N/A */
0N/A private void writeObject(java.io.ObjectOutputStream s)
0N/A throws java.io.IOException {
0N/A // Must inflate to maintain compatible serial form.
0N/A this.inflate();
0N/A
0N/A // Write proper fields
0N/A s.defaultWriteObject();
0N/A }
0N/A
1246N/A
0N/A /**
1246N/A * Returns the length of the absolute value of a {@code long}, in decimal
1246N/A * digits.
0N/A *
1246N/A * @param x the {@code long}
1246N/A * @return the length of the unscaled value, in deciaml digits.
1246N/A */
1246N/A private static int longDigitLength(long x) {
1246N/A /*
1246N/A * As described in "Bit Twiddling Hacks" by Sean Anderson,
1246N/A * (http://graphics.stanford.edu/~seander/bithacks.html)
1246N/A * integer log 10 of x is within 1 of
1246N/A * (1233/4096)* (1 + integer log 2 of x).
1246N/A * The fraction 1233/4096 approximates log10(2). So we first
1246N/A * do a version of log2 (a variant of Long class with
1246N/A * pre-checks and opposite directionality) and then scale and
1246N/A * check against powers table. This is a little simpler in
1246N/A * present context than the version in Hacker's Delight sec
1246N/A * 11-4. Adding one to bit length allows comparing downward
1246N/A * from the LONG_TEN_POWERS_TABLE that we need anyway.
1246N/A */
1246N/A assert x != INFLATED;
1246N/A if (x < 0)
1246N/A x = -x;
1246N/A if (x < 10) // must screen for 0, might as well 10
1246N/A return 1;
1246N/A int n = 64; // not 63, to avoid needing to add 1 later
1246N/A int y = (int)(x >>> 32);
1246N/A if (y == 0) { n -= 32; y = (int)x; }
1246N/A if (y >>> 16 == 0) { n -= 16; y <<= 16; }
1246N/A if (y >>> 24 == 0) { n -= 8; y <<= 8; }
1246N/A if (y >>> 28 == 0) { n -= 4; y <<= 4; }
1246N/A if (y >>> 30 == 0) { n -= 2; y <<= 2; }
1246N/A int r = (((y >>> 31) + n) * 1233) >>> 12;
1246N/A long[] tab = LONG_TEN_POWERS_TABLE;
1246N/A // if r >= length, must have max possible digits for long
1246N/A return (r >= tab.length || x < tab[r])? r : r+1;
1246N/A }
1246N/A
1246N/A /**
1246N/A * Returns the length of the absolute value of a BigInteger, in
1246N/A * decimal digits.
0N/A *
1246N/A * @param b the BigInteger
0N/A * @return the length of the unscaled value, in decimal digits
0N/A */
1246N/A private static int bigDigitLength(BigInteger b) {
1246N/A /*
1246N/A * Same idea as the long version, but we need a better
1246N/A * approximation of log10(2). Using 646456993/2^31
1246N/A * is accurate up to max possible reported bitLength.
1246N/A */
1246N/A if (b.signum == 0)
0N/A return 1;
1246N/A int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
1246N/A return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Remove insignificant trailing zeros from this
0N/A * {@code BigDecimal} until the preferred scale is reached or no
0N/A * more zeros can be removed. If the preferred scale is less than
0N/A * Integer.MIN_VALUE, all the trailing zeros will be removed.
0N/A *
0N/A * {@code BigInteger} assistance could help, here?
0N/A *
0N/A * <p>WARNING: This method should only be called on new objects as
0N/A * it mutates the value fields.
0N/A *
0N/A * @return this {@code BigDecimal} with a scale possibly reduced
0N/A * to be closed to the preferred scale.
0N/A */
0N/A private BigDecimal stripZerosToMatchScale(long preferredScale) {
0N/A this.inflate();
0N/A BigInteger qr[]; // quotient-remainder pair
1246N/A while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
0N/A scale > preferredScale) {
0N/A if (intVal.testBit(0))
0N/A break; // odd number cannot end in 0
0N/A qr = intVal.divideAndRemainder(BigInteger.TEN);
0N/A if (qr[1].signum() != 0)
0N/A break; // non-0 remainder
0N/A intVal=qr[0];
0N/A scale = checkScale((long)scale-1); // could Overflow
0N/A if (precision > 0) // adjust precision if known
0N/A precision--;
0N/A }
1246N/A if (intVal != null)
1246N/A intCompact = compactValFor(intVal);
0N/A return this;
0N/A }
0N/A
0N/A /**
0N/A * Check a scale for Underflow or Overflow. If this BigDecimal is
1246N/A * nonzero, throw an exception if the scale is outof range. If this
1246N/A * is zero, saturate the scale to the extreme value of the right
1246N/A * sign if the scale is out of range.
0N/A *
0N/A * @param val The new scale.
0N/A * @throws ArithmeticException (overflow or underflow) if the new
0N/A * scale is out of range.
0N/A * @return validated scale as an int.
0N/A */
0N/A private int checkScale(long val) {
1246N/A int asInt = (int)val;
1246N/A if (asInt != val) {
1246N/A asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
1246N/A BigInteger b;
1246N/A if (intCompact != 0 &&
1246N/A ((b = intVal) == null || b.signum() != 0))
1246N/A throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
0N/A }
1246N/A return asInt;
0N/A }
0N/A
0N/A /**
0N/A * Round an operand; used only if digits &gt; 0. Does not change
0N/A * {@code this}; if rounding is needed a new {@code BigDecimal}
0N/A * is created and returned.
0N/A *
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the result is inexact but the
0N/A * rounding mode is {@code UNNECESSARY}.
0N/A */
0N/A private BigDecimal roundOp(MathContext mc) {
1246N/A BigDecimal rounded = doRound(this, mc);
0N/A return rounded;
0N/A }
0N/A
0N/A /** Round this BigDecimal according to the MathContext settings;
0N/A * used only if precision {@literal >} 0.
0N/A *
0N/A * <p>WARNING: This method should only be called on new objects as
0N/A * it mutates the value fields.
0N/A *
0N/A * @param mc the context to use.
0N/A * @throws ArithmeticException if the rounding mode is
0N/A * {@code RoundingMode.UNNECESSARY} and the
0N/A * {@code BigDecimal} operation would require rounding.
0N/A */
0N/A private void roundThis(MathContext mc) {
1246N/A BigDecimal rounded = doRound(this, mc);
0N/A if (rounded == this) // wasn't rounded
0N/A return;
0N/A this.intVal = rounded.intVal;
0N/A this.intCompact = rounded.intCompact;
0N/A this.scale = rounded.scale;
0N/A this.precision = rounded.precision;
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@code BigDecimal} rounded according to the
0N/A * MathContext settings; used only if {@code mc.precision > 0}.
0N/A * Does not change {@code this}; if rounding is needed a new
0N/A * {@code BigDecimal} is created and returned.
0N/A *
0N/A * @param mc the context to use.
0N/A * @return a {@code BigDecimal} rounded according to the MathContext
0N/A * settings. May return this, if no rounding needed.
0N/A * @throws ArithmeticException if the rounding mode is
0N/A * {@code RoundingMode.UNNECESSARY} and the
0N/A * result is inexact.
0N/A */
1246N/A private static BigDecimal doRound(BigDecimal d, MathContext mc) {
1246N/A int mcp = mc.precision;
1246N/A int drop;
1246N/A // This might (rarely) iterate to cover the 999=>1000 case
1246N/A while ((drop = d.precision() - mcp) > 0) {
1246N/A int newScale = d.checkScale((long)d.scale - drop);
1246N/A int mode = mc.roundingMode.oldMode;
1246N/A if (drop < LONG_TEN_POWERS_TABLE.length)
1246N/A d = divideAndRound(d.intCompact, d.intVal,
1246N/A LONG_TEN_POWERS_TABLE[drop], null,
1246N/A newScale, mode, newScale);
1246N/A else
1246N/A d = divideAndRound(d.intCompact, d.intVal,
1246N/A INFLATED, bigTenToThe(drop),
1246N/A newScale, mode, newScale);
0N/A }
1246N/A return d;
0N/A }
0N/A
0N/A /**
1246N/A * Returns the compact value for given {@code BigInteger}, or
1246N/A * INFLATED if too big. Relies on internal representation of
1246N/A * {@code BigInteger}.
0N/A */
1246N/A private static long compactValFor(BigInteger b) {
1246N/A int[] m = b.mag;
1246N/A int len = m.length;
1246N/A if (len == 0)
1246N/A return 0;
1246N/A int d = m[0];
1246N/A if (len > 2 || (len == 2 && d < 0))
1246N/A return INFLATED;
0N/A
1246N/A long u = (len == 2)?
1246N/A (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
1246N/A (((long)d) & LONG_MASK);
1246N/A return (b.signum < 0)? -u : u;
0N/A }
0N/A
1246N/A private static int longCompareMagnitude(long x, long y) {
1246N/A if (x < 0)
1246N/A x = -x;
1246N/A if (y < 0)
1246N/A y = -y;
1246N/A return (x < y) ? -1 : ((x == y) ? 0 : 1);
1246N/A }
1246N/A
1246N/A private static int saturateLong(long s) {
1246N/A int i = (int)s;
1246N/A return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
0N/A }
0N/A
0N/A /*
0N/A * Internal printing routine
0N/A */
0N/A private static void print(String name, BigDecimal bd) {
0N/A System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
0N/A name,
0N/A bd.intCompact,
0N/A bd.intVal,
0N/A bd.scale,
0N/A bd.precision);
0N/A }
0N/A
0N/A /**
0N/A * Check internal invariants of this BigDecimal. These invariants
0N/A * include:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>The object must be initialized; either intCompact must not be
0N/A * INFLATED or intVal is non-null. Both of these conditions may
0N/A * be true.
0N/A *
0N/A * <li>If both intCompact and intVal and set, their values must be
0N/A * consistent.
0N/A *
0N/A * <li>If precision is nonzero, it must have the right value.
0N/A * </ul>
1246N/A *
1246N/A * Note: Since this is an audit method, we are not supposed to change the
1246N/A * state of this BigDecimal object.
0N/A */
0N/A private BigDecimal audit() {
0N/A if (intCompact == INFLATED) {
0N/A if (intVal == null) {
0N/A print("audit", this);
0N/A throw new AssertionError("null intVal");
0N/A }
1246N/A // Check precision
1246N/A if (precision > 0 && precision != bigDigitLength(intVal)) {
1246N/A print("audit", this);
1246N/A throw new AssertionError("precision mismatch");
1246N/A }
0N/A } else {
0N/A if (intVal != null) {
0N/A long val = intVal.longValue();
0N/A if (val != intCompact) {
0N/A print("audit", this);
0N/A throw new AssertionError("Inconsistent state, intCompact=" +
0N/A intCompact + "\t intVal=" + val);
0N/A }
0N/A }
1246N/A // Check precision
1246N/A if (precision > 0 && precision != longDigitLength(intCompact)) {
1246N/A print("audit", this);
1246N/A throw new AssertionError("precision mismatch");
1246N/A }
0N/A }
0N/A return this;
0N/A }
0N/A}