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