1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/emul/compact/src/main/java/java/math/BigDecimal.java Sat Sep 07 13:51:24 2013 +0200
1.3 @@ -0,0 +1,3855 @@
1.4 +/*
1.5 + * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +/*
1.30 + * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
1.31 + */
1.32 +
1.33 +package java.math;
1.34 +
1.35 +import java.util.Arrays;
1.36 +import static java.math.BigInteger.LONG_MASK;
1.37 +
1.38 +/**
1.39 + * Immutable, arbitrary-precision signed decimal numbers. A
1.40 + * {@code BigDecimal} consists of an arbitrary precision integer
1.41 + * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
1.42 + * or positive, the scale is the number of digits to the right of the
1.43 + * decimal point. If negative, the unscaled value of the number is
1.44 + * multiplied by ten to the power of the negation of the scale. The
1.45 + * value of the number represented by the {@code BigDecimal} is
1.46 + * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
1.47 + *
1.48 + * <p>The {@code BigDecimal} class provides operations for
1.49 + * arithmetic, scale manipulation, rounding, comparison, hashing, and
1.50 + * format conversion. The {@link #toString} method provides a
1.51 + * canonical representation of a {@code BigDecimal}.
1.52 + *
1.53 + * <p>The {@code BigDecimal} class gives its user complete control
1.54 + * over rounding behavior. If no rounding mode is specified and the
1.55 + * exact result cannot be represented, an exception is thrown;
1.56 + * otherwise, calculations can be carried out to a chosen precision
1.57 + * and rounding mode by supplying an appropriate {@link MathContext}
1.58 + * object to the operation. In either case, eight <em>rounding
1.59 + * modes</em> are provided for the control of rounding. Using the
1.60 + * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
1.61 + * represent rounding mode is largely obsolete; the enumeration values
1.62 + * of the {@code RoundingMode} {@code enum}, (such as {@link
1.63 + * RoundingMode#HALF_UP}) should be used instead.
1.64 + *
1.65 + * <p>When a {@code MathContext} object is supplied with a precision
1.66 + * setting of 0 (for example, {@link MathContext#UNLIMITED}),
1.67 + * arithmetic operations are exact, as are the arithmetic methods
1.68 + * which take no {@code MathContext} object. (This is the only
1.69 + * behavior that was supported in releases prior to 5.) As a
1.70 + * corollary of computing the exact result, the rounding mode setting
1.71 + * of a {@code MathContext} object with a precision setting of 0 is
1.72 + * not used and thus irrelevant. In the case of divide, the exact
1.73 + * quotient could have an infinitely long decimal expansion; for
1.74 + * example, 1 divided by 3. If the quotient has a nonterminating
1.75 + * decimal expansion and the operation is specified to return an exact
1.76 + * result, an {@code ArithmeticException} is thrown. Otherwise, the
1.77 + * exact result of the division is returned, as done for other
1.78 + * operations.
1.79 + *
1.80 + * <p>When the precision setting is not 0, the rules of
1.81 + * {@code BigDecimal} arithmetic are broadly compatible with selected
1.82 + * modes of operation of the arithmetic defined in ANSI X3.274-1996
1.83 + * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
1.84 + * standards, {@code BigDecimal} includes many rounding modes, which
1.85 + * were mandatory for division in {@code BigDecimal} releases prior
1.86 + * to 5. Any conflicts between these ANSI standards and the
1.87 + * {@code BigDecimal} specification are resolved in favor of
1.88 + * {@code BigDecimal}.
1.89 + *
1.90 + * <p>Since the same numerical value can have different
1.91 + * representations (with different scales), the rules of arithmetic
1.92 + * and rounding must specify both the numerical result and the scale
1.93 + * used in the result's representation.
1.94 + *
1.95 + *
1.96 + * <p>In general the rounding modes and precision setting determine
1.97 + * how operations return results with a limited number of digits when
1.98 + * the exact result has more digits (perhaps infinitely many in the
1.99 + * case of division) than the number of digits returned.
1.100 + *
1.101 + * First, the
1.102 + * total number of digits to return is specified by the
1.103 + * {@code MathContext}'s {@code precision} setting; this determines
1.104 + * the result's <i>precision</i>. The digit count starts from the
1.105 + * leftmost nonzero digit of the exact result. The rounding mode
1.106 + * determines how any discarded trailing digits affect the returned
1.107 + * result.
1.108 + *
1.109 + * <p>For all arithmetic operators , the operation is carried out as
1.110 + * though an exact intermediate result were first calculated and then
1.111 + * rounded to the number of digits specified by the precision setting
1.112 + * (if necessary), using the selected rounding mode. If the exact
1.113 + * result is not returned, some digit positions of the exact result
1.114 + * are discarded. When rounding increases the magnitude of the
1.115 + * returned result, it is possible for a new digit position to be
1.116 + * created by a carry propagating to a leading {@literal "9"} digit.
1.117 + * For example, rounding the value 999.9 to three digits rounding up
1.118 + * would be numerically equal to one thousand, represented as
1.119 + * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
1.120 + * the leading digit position of the returned result.
1.121 + *
1.122 + * <p>Besides a logical exact result, each arithmetic operation has a
1.123 + * preferred scale for representing a result. The preferred
1.124 + * scale for each operation is listed in the table below.
1.125 + *
1.126 + * <table border>
1.127 + * <caption><b>Preferred Scales for Results of Arithmetic Operations
1.128 + * </b></caption>
1.129 + * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
1.130 + * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
1.131 + * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
1.132 + * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
1.133 + * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
1.134 + * </table>
1.135 + *
1.136 + * These scales are the ones used by the methods which return exact
1.137 + * arithmetic results; except that an exact divide may have to use a
1.138 + * larger scale since the exact result may have more digits. For
1.139 + * example, {@code 1/32} is {@code 0.03125}.
1.140 + *
1.141 + * <p>Before rounding, the scale of the logical exact intermediate
1.142 + * result is the preferred scale for that operation. If the exact
1.143 + * numerical result cannot be represented in {@code precision}
1.144 + * digits, rounding selects the set of digits to return and the scale
1.145 + * of the result is reduced from the scale of the intermediate result
1.146 + * to the least scale which can represent the {@code precision}
1.147 + * digits actually returned. If the exact result can be represented
1.148 + * with at most {@code precision} digits, the representation
1.149 + * of the result with the scale closest to the preferred scale is
1.150 + * returned. In particular, an exactly representable quotient may be
1.151 + * represented in fewer than {@code precision} digits by removing
1.152 + * trailing zeros and decreasing the scale. For example, rounding to
1.153 + * three digits using the {@linkplain RoundingMode#FLOOR floor}
1.154 + * rounding mode, <br>
1.155 + *
1.156 + * {@code 19/100 = 0.19 // integer=19, scale=2} <br>
1.157 + *
1.158 + * but<br>
1.159 + *
1.160 + * {@code 21/110 = 0.190 // integer=190, scale=3} <br>
1.161 + *
1.162 + * <p>Note that for add, subtract, and multiply, the reduction in
1.163 + * scale will equal the number of digit positions of the exact result
1.164 + * which are discarded. If the rounding causes a carry propagation to
1.165 + * create a new high-order digit position, an additional digit of the
1.166 + * result is discarded than when no new digit position is created.
1.167 + *
1.168 + * <p>Other methods may have slightly different rounding semantics.
1.169 + * For example, the result of the {@code pow} method using the
1.170 + * {@linkplain #pow(int, MathContext) specified algorithm} can
1.171 + * occasionally differ from the rounded mathematical result by more
1.172 + * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
1.173 + *
1.174 + * <p>Two types of operations are provided for manipulating the scale
1.175 + * of a {@code BigDecimal}: scaling/rounding operations and decimal
1.176 + * point motion operations. Scaling/rounding operations ({@link
1.177 + * #setScale setScale} and {@link #round round}) return a
1.178 + * {@code BigDecimal} whose value is approximately (or exactly) equal
1.179 + * to that of the operand, but whose scale or precision is the
1.180 + * specified value; that is, they increase or decrease the precision
1.181 + * of the stored number with minimal effect on its value. Decimal
1.182 + * point motion operations ({@link #movePointLeft movePointLeft} and
1.183 + * {@link #movePointRight movePointRight}) return a
1.184 + * {@code BigDecimal} created from the operand by moving the decimal
1.185 + * point a specified distance in the specified direction.
1.186 + *
1.187 + * <p>For the sake of brevity and clarity, pseudo-code is used
1.188 + * throughout the descriptions of {@code BigDecimal} methods. The
1.189 + * pseudo-code expression {@code (i + j)} is shorthand for "a
1.190 + * {@code BigDecimal} whose value is that of the {@code BigDecimal}
1.191 + * {@code i} added to that of the {@code BigDecimal}
1.192 + * {@code j}." The pseudo-code expression {@code (i == j)} is
1.193 + * shorthand for "{@code true} if and only if the
1.194 + * {@code BigDecimal} {@code i} represents the same value as the
1.195 + * {@code BigDecimal} {@code j}." Other pseudo-code expressions
1.196 + * are interpreted similarly. Square brackets are used to represent
1.197 + * the particular {@code BigInteger} and scale pair defining a
1.198 + * {@code BigDecimal} value; for example [19, 2] is the
1.199 + * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
1.200 + *
1.201 + * <p>Note: care should be exercised if {@code BigDecimal} objects
1.202 + * are used as keys in a {@link java.util.SortedMap SortedMap} or
1.203 + * elements in a {@link java.util.SortedSet SortedSet} since
1.204 + * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
1.205 + * with equals</i>. See {@link Comparable}, {@link
1.206 + * java.util.SortedMap} or {@link java.util.SortedSet} for more
1.207 + * information.
1.208 + *
1.209 + * <p>All methods and constructors for this class throw
1.210 + * {@code NullPointerException} when passed a {@code null} object
1.211 + * reference for any input parameter.
1.212 + *
1.213 + * @see BigInteger
1.214 + * @see MathContext
1.215 + * @see RoundingMode
1.216 + * @see java.util.SortedMap
1.217 + * @see java.util.SortedSet
1.218 + * @author Josh Bloch
1.219 + * @author Mike Cowlishaw
1.220 + * @author Joseph D. Darcy
1.221 + */
1.222 +public class BigDecimal extends Number implements Comparable<BigDecimal> {
1.223 + /**
1.224 + * The unscaled value of this BigDecimal, as returned by {@link
1.225 + * #unscaledValue}.
1.226 + *
1.227 + * @serial
1.228 + * @see #unscaledValue
1.229 + */
1.230 + private volatile BigInteger intVal;
1.231 +
1.232 + /**
1.233 + * The scale of this BigDecimal, as returned by {@link #scale}.
1.234 + *
1.235 + * @serial
1.236 + * @see #scale
1.237 + */
1.238 + private int scale; // Note: this may have any value, so
1.239 + // calculations must be done in longs
1.240 + /**
1.241 + * The number of decimal digits in this BigDecimal, or 0 if the
1.242 + * number of digits are not known (lookaside information). If
1.243 + * nonzero, the value is guaranteed correct. Use the precision()
1.244 + * method to obtain and set the value if it might be 0. This
1.245 + * field is mutable until set nonzero.
1.246 + *
1.247 + * @since 1.5
1.248 + */
1.249 + private transient int precision;
1.250 +
1.251 + /**
1.252 + * Used to store the canonical string representation, if computed.
1.253 + */
1.254 + private transient String stringCache;
1.255 +
1.256 + /**
1.257 + * Sentinel value for {@link #intCompact} indicating the
1.258 + * significand information is only available from {@code intVal}.
1.259 + */
1.260 + static final long INFLATED = Long.MIN_VALUE;
1.261 +
1.262 + /**
1.263 + * If the absolute value of the significand of this BigDecimal is
1.264 + * less than or equal to {@code Long.MAX_VALUE}, the value can be
1.265 + * compactly stored in this field and used in computations.
1.266 + */
1.267 + private transient long intCompact;
1.268 +
1.269 + // All 18-digit base ten strings fit into a long; not all 19-digit
1.270 + // strings will
1.271 + private static final int MAX_COMPACT_DIGITS = 18;
1.272 +
1.273 + private static final int MAX_BIGINT_BITS = 62;
1.274 +
1.275 + /* Appease the serialization gods */
1.276 + private static final long serialVersionUID = 6108874887143696463L;
1.277 +
1.278 + private static final ThreadLocal<StringBuilderHelper>
1.279 + threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
1.280 + @Override
1.281 + protected StringBuilderHelper initialValue() {
1.282 + return new StringBuilderHelper();
1.283 + }
1.284 + };
1.285 +
1.286 + // Cache of common small BigDecimal values.
1.287 + private static final BigDecimal zeroThroughTen[] = {
1.288 + new BigDecimal(BigInteger.ZERO, 0, 0, 1),
1.289 + new BigDecimal(BigInteger.ONE, 1, 0, 1),
1.290 + new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),
1.291 + new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
1.292 + new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
1.293 + new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
1.294 + new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
1.295 + new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
1.296 + new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
1.297 + new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
1.298 + new BigDecimal(BigInteger.TEN, 10, 0, 2),
1.299 + };
1.300 +
1.301 + // Cache of zero scaled by 0 - 15
1.302 + private static final BigDecimal[] ZERO_SCALED_BY = {
1.303 + zeroThroughTen[0],
1.304 + new BigDecimal(BigInteger.ZERO, 0, 1, 1),
1.305 + new BigDecimal(BigInteger.ZERO, 0, 2, 1),
1.306 + new BigDecimal(BigInteger.ZERO, 0, 3, 1),
1.307 + new BigDecimal(BigInteger.ZERO, 0, 4, 1),
1.308 + new BigDecimal(BigInteger.ZERO, 0, 5, 1),
1.309 + new BigDecimal(BigInteger.ZERO, 0, 6, 1),
1.310 + new BigDecimal(BigInteger.ZERO, 0, 7, 1),
1.311 + new BigDecimal(BigInteger.ZERO, 0, 8, 1),
1.312 + new BigDecimal(BigInteger.ZERO, 0, 9, 1),
1.313 + new BigDecimal(BigInteger.ZERO, 0, 10, 1),
1.314 + new BigDecimal(BigInteger.ZERO, 0, 11, 1),
1.315 + new BigDecimal(BigInteger.ZERO, 0, 12, 1),
1.316 + new BigDecimal(BigInteger.ZERO, 0, 13, 1),
1.317 + new BigDecimal(BigInteger.ZERO, 0, 14, 1),
1.318 + new BigDecimal(BigInteger.ZERO, 0, 15, 1),
1.319 + };
1.320 +
1.321 + // Half of Long.MIN_VALUE & Long.MAX_VALUE.
1.322 + private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
1.323 + private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
1.324 +
1.325 + // Constants
1.326 + /**
1.327 + * The value 0, with a scale of 0.
1.328 + *
1.329 + * @since 1.5
1.330 + */
1.331 + public static final BigDecimal ZERO =
1.332 + zeroThroughTen[0];
1.333 +
1.334 + /**
1.335 + * The value 1, with a scale of 0.
1.336 + *
1.337 + * @since 1.5
1.338 + */
1.339 + public static final BigDecimal ONE =
1.340 + zeroThroughTen[1];
1.341 +
1.342 + /**
1.343 + * The value 10, with a scale of 0.
1.344 + *
1.345 + * @since 1.5
1.346 + */
1.347 + public static final BigDecimal TEN =
1.348 + zeroThroughTen[10];
1.349 +
1.350 + // Constructors
1.351 +
1.352 + /**
1.353 + * Trusted package private constructor.
1.354 + * Trusted simply means if val is INFLATED, intVal could not be null and
1.355 + * if intVal is null, val could not be INFLATED.
1.356 + */
1.357 + BigDecimal(BigInteger intVal, long val, int scale, int prec) {
1.358 + this.scale = scale;
1.359 + this.precision = prec;
1.360 + this.intCompact = val;
1.361 + this.intVal = intVal;
1.362 + }
1.363 +
1.364 + /**
1.365 + * Translates a character array representation of a
1.366 + * {@code BigDecimal} into a {@code BigDecimal}, accepting the
1.367 + * same sequence of characters as the {@link #BigDecimal(String)}
1.368 + * constructor, while allowing a sub-array to be specified.
1.369 + *
1.370 + * <p>Note that if the sequence of characters is already available
1.371 + * within a character array, using this constructor is faster than
1.372 + * converting the {@code char} array to string and using the
1.373 + * {@code BigDecimal(String)} constructor .
1.374 + *
1.375 + * @param in {@code char} array that is the source of characters.
1.376 + * @param offset first character in the array to inspect.
1.377 + * @param len number of characters to consider.
1.378 + * @throws NumberFormatException if {@code in} is not a valid
1.379 + * representation of a {@code BigDecimal} or the defined subarray
1.380 + * is not wholly within {@code in}.
1.381 + * @since 1.5
1.382 + */
1.383 + public BigDecimal(char[] in, int offset, int len) {
1.384 + // protect against huge length.
1.385 + if (offset+len > in.length || offset < 0)
1.386 + throw new NumberFormatException();
1.387 + // This is the primary string to BigDecimal constructor; all
1.388 + // incoming strings end up here; it uses explicit (inline)
1.389 + // parsing for speed and generates at most one intermediate
1.390 + // (temporary) object (a char[] array) for non-compact case.
1.391 +
1.392 + // Use locals for all fields values until completion
1.393 + int prec = 0; // record precision value
1.394 + int scl = 0; // record scale value
1.395 + long rs = 0; // the compact value in long
1.396 + BigInteger rb = null; // the inflated value in BigInteger
1.397 +
1.398 + // use array bounds checking to handle too-long, len == 0,
1.399 + // bad offset, etc.
1.400 + try {
1.401 + // handle the sign
1.402 + boolean isneg = false; // assume positive
1.403 + if (in[offset] == '-') {
1.404 + isneg = true; // leading minus means negative
1.405 + offset++;
1.406 + len--;
1.407 + } else if (in[offset] == '+') { // leading + allowed
1.408 + offset++;
1.409 + len--;
1.410 + }
1.411 +
1.412 + // should now be at numeric part of the significand
1.413 + boolean dot = false; // true when there is a '.'
1.414 + int cfirst = offset; // record start of integer
1.415 + long exp = 0; // exponent
1.416 + char c; // current character
1.417 +
1.418 + boolean isCompact = (len <= MAX_COMPACT_DIGITS);
1.419 + // integer significand array & idx is the index to it. The array
1.420 + // is ONLY used when we can't use a compact representation.
1.421 + char coeff[] = isCompact ? null : new char[len];
1.422 + int idx = 0;
1.423 +
1.424 + for (; len > 0; offset++, len--) {
1.425 + c = in[offset];
1.426 + // have digit
1.427 + if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
1.428 + // First compact case, we need not to preserve the character
1.429 + // and we can just compute the value in place.
1.430 + if (isCompact) {
1.431 + int digit = Character.digit(c, 10);
1.432 + if (digit == 0) {
1.433 + if (prec == 0)
1.434 + prec = 1;
1.435 + else if (rs != 0) {
1.436 + rs *= 10;
1.437 + ++prec;
1.438 + } // else digit is a redundant leading zero
1.439 + } else {
1.440 + if (prec != 1 || rs != 0)
1.441 + ++prec; // prec unchanged if preceded by 0s
1.442 + rs = rs * 10 + digit;
1.443 + }
1.444 + } else { // the unscaled value is likely a BigInteger object.
1.445 + if (c == '0' || Character.digit(c, 10) == 0) {
1.446 + if (prec == 0) {
1.447 + coeff[idx] = c;
1.448 + prec = 1;
1.449 + } else if (idx != 0) {
1.450 + coeff[idx++] = c;
1.451 + ++prec;
1.452 + } // else c must be a redundant leading zero
1.453 + } else {
1.454 + if (prec != 1 || idx != 0)
1.455 + ++prec; // prec unchanged if preceded by 0s
1.456 + coeff[idx++] = c;
1.457 + }
1.458 + }
1.459 + if (dot)
1.460 + ++scl;
1.461 + continue;
1.462 + }
1.463 + // have dot
1.464 + if (c == '.') {
1.465 + // have dot
1.466 + if (dot) // two dots
1.467 + throw new NumberFormatException();
1.468 + dot = true;
1.469 + continue;
1.470 + }
1.471 + // exponent expected
1.472 + if ((c != 'e') && (c != 'E'))
1.473 + throw new NumberFormatException();
1.474 + offset++;
1.475 + c = in[offset];
1.476 + len--;
1.477 + boolean negexp = (c == '-');
1.478 + // optional sign
1.479 + if (negexp || c == '+') {
1.480 + offset++;
1.481 + c = in[offset];
1.482 + len--;
1.483 + }
1.484 + if (len <= 0) // no exponent digits
1.485 + throw new NumberFormatException();
1.486 + // skip leading zeros in the exponent
1.487 + while (len > 10 && Character.digit(c, 10) == 0) {
1.488 + offset++;
1.489 + c = in[offset];
1.490 + len--;
1.491 + }
1.492 + if (len > 10) // too many nonzero exponent digits
1.493 + throw new NumberFormatException();
1.494 + // c now holds first digit of exponent
1.495 + for (;; len--) {
1.496 + int v;
1.497 + if (c >= '0' && c <= '9') {
1.498 + v = c - '0';
1.499 + } else {
1.500 + v = Character.digit(c, 10);
1.501 + if (v < 0) // not a digit
1.502 + throw new NumberFormatException();
1.503 + }
1.504 + exp = exp * 10 + v;
1.505 + if (len == 1)
1.506 + break; // that was final character
1.507 + offset++;
1.508 + c = in[offset];
1.509 + }
1.510 + if (negexp) // apply sign
1.511 + exp = -exp;
1.512 + // Next test is required for backwards compatibility
1.513 + if ((int)exp != exp) // overflow
1.514 + throw new NumberFormatException();
1.515 + break; // [saves a test]
1.516 + }
1.517 + // here when no characters left
1.518 + if (prec == 0) // no digits found
1.519 + throw new NumberFormatException();
1.520 +
1.521 + // Adjust scale if exp is not zero.
1.522 + if (exp != 0) { // had significant exponent
1.523 + // Can't call checkScale which relies on proper fields value
1.524 + long adjustedScale = scl - exp;
1.525 + if (adjustedScale > Integer.MAX_VALUE ||
1.526 + adjustedScale < Integer.MIN_VALUE)
1.527 + throw new NumberFormatException("Scale out of range.");
1.528 + scl = (int)adjustedScale;
1.529 + }
1.530 +
1.531 + // Remove leading zeros from precision (digits count)
1.532 + if (isCompact) {
1.533 + rs = isneg ? -rs : rs;
1.534 + } else {
1.535 + char quick[];
1.536 + if (!isneg) {
1.537 + quick = (coeff.length != prec) ?
1.538 + Arrays.copyOf(coeff, prec) : coeff;
1.539 + } else {
1.540 + quick = new char[prec + 1];
1.541 + quick[0] = '-';
1.542 + System.arraycopy(coeff, 0, quick, 1, prec);
1.543 + }
1.544 + rb = new BigInteger(quick);
1.545 + rs = compactValFor(rb);
1.546 + }
1.547 + } catch (ArrayIndexOutOfBoundsException e) {
1.548 + throw new NumberFormatException();
1.549 + } catch (NegativeArraySizeException e) {
1.550 + throw new NumberFormatException();
1.551 + }
1.552 + this.scale = scl;
1.553 + this.precision = prec;
1.554 + this.intCompact = rs;
1.555 + this.intVal = (rs != INFLATED) ? null : rb;
1.556 + }
1.557 +
1.558 + /**
1.559 + * Translates a character array representation of a
1.560 + * {@code BigDecimal} into a {@code BigDecimal}, accepting the
1.561 + * same sequence of characters as the {@link #BigDecimal(String)}
1.562 + * constructor, while allowing a sub-array to be specified and
1.563 + * with rounding according to the context settings.
1.564 + *
1.565 + * <p>Note that if the sequence of characters is already available
1.566 + * within a character array, using this constructor is faster than
1.567 + * converting the {@code char} array to string and using the
1.568 + * {@code BigDecimal(String)} constructor .
1.569 + *
1.570 + * @param in {@code char} array that is the source of characters.
1.571 + * @param offset first character in the array to inspect.
1.572 + * @param len number of characters to consider..
1.573 + * @param mc the context to use.
1.574 + * @throws ArithmeticException if the result is inexact but the
1.575 + * rounding mode is {@code UNNECESSARY}.
1.576 + * @throws NumberFormatException if {@code in} is not a valid
1.577 + * representation of a {@code BigDecimal} or the defined subarray
1.578 + * is not wholly within {@code in}.
1.579 + * @since 1.5
1.580 + */
1.581 + public BigDecimal(char[] in, int offset, int len, MathContext mc) {
1.582 + this(in, offset, len);
1.583 + if (mc.precision > 0)
1.584 + roundThis(mc);
1.585 + }
1.586 +
1.587 + /**
1.588 + * Translates a character array representation of a
1.589 + * {@code BigDecimal} into a {@code BigDecimal}, accepting the
1.590 + * same sequence of characters as the {@link #BigDecimal(String)}
1.591 + * constructor.
1.592 + *
1.593 + * <p>Note that if the sequence of characters is already available
1.594 + * as a character array, using this constructor is faster than
1.595 + * converting the {@code char} array to string and using the
1.596 + * {@code BigDecimal(String)} constructor .
1.597 + *
1.598 + * @param in {@code char} array that is the source of characters.
1.599 + * @throws NumberFormatException if {@code in} is not a valid
1.600 + * representation of a {@code BigDecimal}.
1.601 + * @since 1.5
1.602 + */
1.603 + public BigDecimal(char[] in) {
1.604 + this(in, 0, in.length);
1.605 + }
1.606 +
1.607 + /**
1.608 + * Translates a character array representation of a
1.609 + * {@code BigDecimal} into a {@code BigDecimal}, accepting the
1.610 + * same sequence of characters as the {@link #BigDecimal(String)}
1.611 + * constructor and with rounding according to the context
1.612 + * settings.
1.613 + *
1.614 + * <p>Note that if the sequence of characters is already available
1.615 + * as a character array, using this constructor is faster than
1.616 + * converting the {@code char} array to string and using the
1.617 + * {@code BigDecimal(String)} constructor .
1.618 + *
1.619 + * @param in {@code char} array that is the source of characters.
1.620 + * @param mc the context to use.
1.621 + * @throws ArithmeticException if the result is inexact but the
1.622 + * rounding mode is {@code UNNECESSARY}.
1.623 + * @throws NumberFormatException if {@code in} is not a valid
1.624 + * representation of a {@code BigDecimal}.
1.625 + * @since 1.5
1.626 + */
1.627 + public BigDecimal(char[] in, MathContext mc) {
1.628 + this(in, 0, in.length, mc);
1.629 + }
1.630 +
1.631 + /**
1.632 + * Translates the string representation of a {@code BigDecimal}
1.633 + * into a {@code BigDecimal}. The string representation consists
1.634 + * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or
1.635 + * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of
1.636 + * zero or more decimal digits ("the integer"), optionally
1.637 + * followed by a fraction, optionally followed by an exponent.
1.638 + *
1.639 + * <p>The fraction consists of a decimal point followed by zero
1.640 + * or more decimal digits. The string must contain at least one
1.641 + * digit in either the integer or the fraction. The number formed
1.642 + * by the sign, the integer and the fraction is referred to as the
1.643 + * <i>significand</i>.
1.644 + *
1.645 + * <p>The exponent consists of the character {@code 'e'}
1.646 + * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>)
1.647 + * followed by one or more decimal digits. The value of the
1.648 + * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
1.649 + * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
1.650 + *
1.651 + * <p>More formally, the strings this constructor accepts are
1.652 + * described by the following grammar:
1.653 + * <blockquote>
1.654 + * <dl>
1.655 + * <dt><i>BigDecimalString:</i>
1.656 + * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
1.657 + * <p>
1.658 + * <dt><i>Sign:</i>
1.659 + * <dd>{@code +}
1.660 + * <dd>{@code -}
1.661 + * <p>
1.662 + * <dt><i>Significand:</i>
1.663 + * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
1.664 + * <dd>{@code .} <i>FractionPart</i>
1.665 + * <dd><i>IntegerPart</i>
1.666 + * <p>
1.667 + * <dt><i>IntegerPart:</i>
1.668 + * <dd><i>Digits</i>
1.669 + * <p>
1.670 + * <dt><i>FractionPart:</i>
1.671 + * <dd><i>Digits</i>
1.672 + * <p>
1.673 + * <dt><i>Exponent:</i>
1.674 + * <dd><i>ExponentIndicator SignedInteger</i>
1.675 + * <p>
1.676 + * <dt><i>ExponentIndicator:</i>
1.677 + * <dd>{@code e}
1.678 + * <dd>{@code E}
1.679 + * <p>
1.680 + * <dt><i>SignedInteger:</i>
1.681 + * <dd><i>Sign<sub>opt</sub> Digits</i>
1.682 + * <p>
1.683 + * <dt><i>Digits:</i>
1.684 + * <dd><i>Digit</i>
1.685 + * <dd><i>Digits Digit</i>
1.686 + * <p>
1.687 + * <dt><i>Digit:</i>
1.688 + * <dd>any character for which {@link Character#isDigit}
1.689 + * returns {@code true}, including 0, 1, 2 ...
1.690 + * </dl>
1.691 + * </blockquote>
1.692 + *
1.693 + * <p>The scale of the returned {@code BigDecimal} will be the
1.694 + * number of digits in the fraction, or zero if the string
1.695 + * contains no decimal point, subject to adjustment for any
1.696 + * exponent; if the string contains an exponent, the exponent is
1.697 + * subtracted from the scale. The value of the resulting scale
1.698 + * must lie between {@code Integer.MIN_VALUE} and
1.699 + * {@code Integer.MAX_VALUE}, inclusive.
1.700 + *
1.701 + * <p>The character-to-digit mapping is provided by {@link
1.702 + * java.lang.Character#digit} set to convert to radix 10. The
1.703 + * String may not contain any extraneous characters (whitespace,
1.704 + * for example).
1.705 + *
1.706 + * <p><b>Examples:</b><br>
1.707 + * The value of the returned {@code BigDecimal} is equal to
1.708 + * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
1.709 + * For each string on the left, the resulting representation
1.710 + * [{@code BigInteger}, {@code scale}] is shown on the right.
1.711 + * <pre>
1.712 + * "0" [0,0]
1.713 + * "0.00" [0,2]
1.714 + * "123" [123,0]
1.715 + * "-123" [-123,0]
1.716 + * "1.23E3" [123,-1]
1.717 + * "1.23E+3" [123,-1]
1.718 + * "12.3E+7" [123,-6]
1.719 + * "12.0" [120,1]
1.720 + * "12.3" [123,1]
1.721 + * "0.00123" [123,5]
1.722 + * "-1.23E-12" [-123,14]
1.723 + * "1234.5E-4" [12345,5]
1.724 + * "0E+7" [0,-7]
1.725 + * "-0" [0,0]
1.726 + * </pre>
1.727 + *
1.728 + * <p>Note: For values other than {@code float} and
1.729 + * {@code double} NaN and ±Infinity, this constructor is
1.730 + * compatible with the values returned by {@link Float#toString}
1.731 + * and {@link Double#toString}. This is generally the preferred
1.732 + * way to convert a {@code float} or {@code double} into a
1.733 + * BigDecimal, as it doesn't suffer from the unpredictability of
1.734 + * the {@link #BigDecimal(double)} constructor.
1.735 + *
1.736 + * @param val String representation of {@code BigDecimal}.
1.737 + *
1.738 + * @throws NumberFormatException if {@code val} is not a valid
1.739 + * representation of a {@code BigDecimal}.
1.740 + */
1.741 + public BigDecimal(String val) {
1.742 + this(val.toCharArray(), 0, val.length());
1.743 + }
1.744 +
1.745 + /**
1.746 + * Translates the string representation of a {@code BigDecimal}
1.747 + * into a {@code BigDecimal}, accepting the same strings as the
1.748 + * {@link #BigDecimal(String)} constructor, with rounding
1.749 + * according to the context settings.
1.750 + *
1.751 + * @param val string representation of a {@code BigDecimal}.
1.752 + * @param mc the context to use.
1.753 + * @throws ArithmeticException if the result is inexact but the
1.754 + * rounding mode is {@code UNNECESSARY}.
1.755 + * @throws NumberFormatException if {@code val} is not a valid
1.756 + * representation of a BigDecimal.
1.757 + * @since 1.5
1.758 + */
1.759 + public BigDecimal(String val, MathContext mc) {
1.760 + this(val.toCharArray(), 0, val.length());
1.761 + if (mc.precision > 0)
1.762 + roundThis(mc);
1.763 + }
1.764 +
1.765 + /**
1.766 + * Translates a {@code double} into a {@code BigDecimal} which
1.767 + * is the exact decimal representation of the {@code double}'s
1.768 + * binary floating-point value. The scale of the returned
1.769 + * {@code BigDecimal} is the smallest value such that
1.770 + * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
1.771 + * <p>
1.772 + * <b>Notes:</b>
1.773 + * <ol>
1.774 + * <li>
1.775 + * The results of this constructor can be somewhat unpredictable.
1.776 + * One might assume that writing {@code new BigDecimal(0.1)} in
1.777 + * Java creates a {@code BigDecimal} which is exactly equal to
1.778 + * 0.1 (an unscaled value of 1, with a scale of 1), but it is
1.779 + * actually equal to
1.780 + * 0.1000000000000000055511151231257827021181583404541015625.
1.781 + * This is because 0.1 cannot be represented exactly as a
1.782 + * {@code double} (or, for that matter, as a binary fraction of
1.783 + * any finite length). Thus, the value that is being passed
1.784 + * <i>in</i> to the constructor is not exactly equal to 0.1,
1.785 + * appearances notwithstanding.
1.786 + *
1.787 + * <li>
1.788 + * The {@code String} constructor, on the other hand, is
1.789 + * perfectly predictable: writing {@code new BigDecimal("0.1")}
1.790 + * creates a {@code BigDecimal} which is <i>exactly</i> equal to
1.791 + * 0.1, as one would expect. Therefore, it is generally
1.792 + * recommended that the {@linkplain #BigDecimal(String)
1.793 + * <tt>String</tt> constructor} be used in preference to this one.
1.794 + *
1.795 + * <li>
1.796 + * When a {@code double} must be used as a source for a
1.797 + * {@code BigDecimal}, note that this constructor provides an
1.798 + * exact conversion; it does not give the same result as
1.799 + * converting the {@code double} to a {@code String} using the
1.800 + * {@link Double#toString(double)} method and then using the
1.801 + * {@link #BigDecimal(String)} constructor. To get that result,
1.802 + * use the {@code static} {@link #valueOf(double)} method.
1.803 + * </ol>
1.804 + *
1.805 + * @param val {@code double} value to be converted to
1.806 + * {@code BigDecimal}.
1.807 + * @throws NumberFormatException if {@code val} is infinite or NaN.
1.808 + */
1.809 + public BigDecimal(double val) {
1.810 + if (Double.isInfinite(val) || Double.isNaN(val))
1.811 + throw new NumberFormatException("Infinite or NaN");
1.812 +
1.813 + // Translate the double into sign, exponent and significand, according
1.814 + // to the formulae in JLS, Section 20.10.22.
1.815 + long valBits = Double.doubleToLongBits(val);
1.816 + int sign = ((valBits >> 63)==0 ? 1 : -1);
1.817 + int exponent = (int) ((valBits >> 52) & 0x7ffL);
1.818 + long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
1.819 + : (valBits & ((1L<<52) - 1)) | (1L<<52));
1.820 + exponent -= 1075;
1.821 + // At this point, val == sign * significand * 2**exponent.
1.822 +
1.823 + /*
1.824 + * Special case zero to supress nonterminating normalization
1.825 + * and bogus scale calculation.
1.826 + */
1.827 + if (significand == 0) {
1.828 + intVal = BigInteger.ZERO;
1.829 + intCompact = 0;
1.830 + precision = 1;
1.831 + return;
1.832 + }
1.833 +
1.834 + // Normalize
1.835 + while((significand & 1) == 0) { // i.e., significand is even
1.836 + significand >>= 1;
1.837 + exponent++;
1.838 + }
1.839 +
1.840 + // Calculate intVal and scale
1.841 + long s = sign * significand;
1.842 + BigInteger b;
1.843 + if (exponent < 0) {
1.844 + b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
1.845 + scale = -exponent;
1.846 + } else if (exponent > 0) {
1.847 + b = BigInteger.valueOf(2).pow(exponent).multiply(s);
1.848 + } else {
1.849 + b = BigInteger.valueOf(s);
1.850 + }
1.851 + intCompact = compactValFor(b);
1.852 + intVal = (intCompact != INFLATED) ? null : b;
1.853 + }
1.854 +
1.855 + /**
1.856 + * Translates a {@code double} into a {@code BigDecimal}, with
1.857 + * rounding according to the context settings. The scale of the
1.858 + * {@code BigDecimal} is the smallest value such that
1.859 + * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
1.860 + *
1.861 + * <p>The results of this constructor can be somewhat unpredictable
1.862 + * and its use is generally not recommended; see the notes under
1.863 + * the {@link #BigDecimal(double)} constructor.
1.864 + *
1.865 + * @param val {@code double} value to be converted to
1.866 + * {@code BigDecimal}.
1.867 + * @param mc the context to use.
1.868 + * @throws ArithmeticException if the result is inexact but the
1.869 + * RoundingMode is UNNECESSARY.
1.870 + * @throws NumberFormatException if {@code val} is infinite or NaN.
1.871 + * @since 1.5
1.872 + */
1.873 + public BigDecimal(double val, MathContext mc) {
1.874 + this(val);
1.875 + if (mc.precision > 0)
1.876 + roundThis(mc);
1.877 + }
1.878 +
1.879 + /**
1.880 + * Translates a {@code BigInteger} into a {@code BigDecimal}.
1.881 + * The scale of the {@code BigDecimal} is zero.
1.882 + *
1.883 + * @param val {@code BigInteger} value to be converted to
1.884 + * {@code BigDecimal}.
1.885 + */
1.886 + public BigDecimal(BigInteger val) {
1.887 + intCompact = compactValFor(val);
1.888 + intVal = (intCompact != INFLATED) ? null : val;
1.889 + }
1.890 +
1.891 + /**
1.892 + * Translates a {@code BigInteger} into a {@code BigDecimal}
1.893 + * rounding according to the context settings. The scale of the
1.894 + * {@code BigDecimal} is zero.
1.895 + *
1.896 + * @param val {@code BigInteger} value to be converted to
1.897 + * {@code BigDecimal}.
1.898 + * @param mc the context to use.
1.899 + * @throws ArithmeticException if the result is inexact but the
1.900 + * rounding mode is {@code UNNECESSARY}.
1.901 + * @since 1.5
1.902 + */
1.903 + public BigDecimal(BigInteger val, MathContext mc) {
1.904 + this(val);
1.905 + if (mc.precision > 0)
1.906 + roundThis(mc);
1.907 + }
1.908 +
1.909 + /**
1.910 + * Translates a {@code BigInteger} unscaled value and an
1.911 + * {@code int} scale into a {@code BigDecimal}. The value of
1.912 + * the {@code BigDecimal} is
1.913 + * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
1.914 + *
1.915 + * @param unscaledVal unscaled value of the {@code BigDecimal}.
1.916 + * @param scale scale of the {@code BigDecimal}.
1.917 + */
1.918 + public BigDecimal(BigInteger unscaledVal, int scale) {
1.919 + // Negative scales are now allowed
1.920 + this(unscaledVal);
1.921 + this.scale = scale;
1.922 + }
1.923 +
1.924 + /**
1.925 + * Translates a {@code BigInteger} unscaled value and an
1.926 + * {@code int} scale into a {@code BigDecimal}, with rounding
1.927 + * according to the context settings. The value of the
1.928 + * {@code BigDecimal} is <tt>(unscaledVal ×
1.929 + * 10<sup>-scale</sup>)</tt>, rounded according to the
1.930 + * {@code precision} and rounding mode settings.
1.931 + *
1.932 + * @param unscaledVal unscaled value of the {@code BigDecimal}.
1.933 + * @param scale scale of the {@code BigDecimal}.
1.934 + * @param mc the context to use.
1.935 + * @throws ArithmeticException if the result is inexact but the
1.936 + * rounding mode is {@code UNNECESSARY}.
1.937 + * @since 1.5
1.938 + */
1.939 + public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
1.940 + this(unscaledVal);
1.941 + this.scale = scale;
1.942 + if (mc.precision > 0)
1.943 + roundThis(mc);
1.944 + }
1.945 +
1.946 + /**
1.947 + * Translates an {@code int} into a {@code BigDecimal}. The
1.948 + * scale of the {@code BigDecimal} is zero.
1.949 + *
1.950 + * @param val {@code int} value to be converted to
1.951 + * {@code BigDecimal}.
1.952 + * @since 1.5
1.953 + */
1.954 + public BigDecimal(int val) {
1.955 + intCompact = val;
1.956 + }
1.957 +
1.958 + /**
1.959 + * Translates an {@code int} into a {@code BigDecimal}, with
1.960 + * rounding according to the context settings. The scale of the
1.961 + * {@code BigDecimal}, before any rounding, is zero.
1.962 + *
1.963 + * @param val {@code int} value to be converted to {@code BigDecimal}.
1.964 + * @param mc the context to use.
1.965 + * @throws ArithmeticException if the result is inexact but the
1.966 + * rounding mode is {@code UNNECESSARY}.
1.967 + * @since 1.5
1.968 + */
1.969 + public BigDecimal(int val, MathContext mc) {
1.970 + intCompact = val;
1.971 + if (mc.precision > 0)
1.972 + roundThis(mc);
1.973 + }
1.974 +
1.975 + /**
1.976 + * Translates a {@code long} into a {@code BigDecimal}. The
1.977 + * scale of the {@code BigDecimal} is zero.
1.978 + *
1.979 + * @param val {@code long} value to be converted to {@code BigDecimal}.
1.980 + * @since 1.5
1.981 + */
1.982 + public BigDecimal(long val) {
1.983 + this.intCompact = val;
1.984 + this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
1.985 + }
1.986 +
1.987 + /**
1.988 + * Translates a {@code long} into a {@code BigDecimal}, with
1.989 + * rounding according to the context settings. The scale of the
1.990 + * {@code BigDecimal}, before any rounding, is zero.
1.991 + *
1.992 + * @param val {@code long} value to be converted to {@code BigDecimal}.
1.993 + * @param mc the context to use.
1.994 + * @throws ArithmeticException if the result is inexact but the
1.995 + * rounding mode is {@code UNNECESSARY}.
1.996 + * @since 1.5
1.997 + */
1.998 + public BigDecimal(long val, MathContext mc) {
1.999 + this(val);
1.1000 + if (mc.precision > 0)
1.1001 + roundThis(mc);
1.1002 + }
1.1003 +
1.1004 + // Static Factory Methods
1.1005 +
1.1006 + /**
1.1007 + * Translates a {@code long} unscaled value and an
1.1008 + * {@code int} scale into a {@code BigDecimal}. This
1.1009 + * {@literal "static factory method"} is provided in preference to
1.1010 + * a ({@code long}, {@code int}) constructor because it
1.1011 + * allows for reuse of frequently used {@code BigDecimal} values..
1.1012 + *
1.1013 + * @param unscaledVal unscaled value of the {@code BigDecimal}.
1.1014 + * @param scale scale of the {@code BigDecimal}.
1.1015 + * @return a {@code BigDecimal} whose value is
1.1016 + * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
1.1017 + */
1.1018 + public static BigDecimal valueOf(long unscaledVal, int scale) {
1.1019 + if (scale == 0)
1.1020 + return valueOf(unscaledVal);
1.1021 + else if (unscaledVal == 0) {
1.1022 + if (scale > 0 && scale < ZERO_SCALED_BY.length)
1.1023 + return ZERO_SCALED_BY[scale];
1.1024 + else
1.1025 + return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1.1026 + }
1.1027 + return new BigDecimal(unscaledVal == INFLATED ?
1.1028 + BigInteger.valueOf(unscaledVal) : null,
1.1029 + unscaledVal, scale, 0);
1.1030 + }
1.1031 +
1.1032 + /**
1.1033 + * Translates a {@code long} value into a {@code BigDecimal}
1.1034 + * with a scale of zero. This {@literal "static factory method"}
1.1035 + * is provided in preference to a ({@code long}) constructor
1.1036 + * because it allows for reuse of frequently used
1.1037 + * {@code BigDecimal} values.
1.1038 + *
1.1039 + * @param val value of the {@code BigDecimal}.
1.1040 + * @return a {@code BigDecimal} whose value is {@code val}.
1.1041 + */
1.1042 + public static BigDecimal valueOf(long val) {
1.1043 + if (val >= 0 && val < zeroThroughTen.length)
1.1044 + return zeroThroughTen[(int)val];
1.1045 + else if (val != INFLATED)
1.1046 + return new BigDecimal(null, val, 0, 0);
1.1047 + return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
1.1048 + }
1.1049 +
1.1050 + /**
1.1051 + * Translates a {@code double} into a {@code BigDecimal}, using
1.1052 + * the {@code double}'s canonical string representation provided
1.1053 + * by the {@link Double#toString(double)} method.
1.1054 + *
1.1055 + * <p><b>Note:</b> This is generally the preferred way to convert
1.1056 + * a {@code double} (or {@code float}) into a
1.1057 + * {@code BigDecimal}, as the value returned is equal to that
1.1058 + * resulting from constructing a {@code BigDecimal} from the
1.1059 + * result of using {@link Double#toString(double)}.
1.1060 + *
1.1061 + * @param val {@code double} to convert to a {@code BigDecimal}.
1.1062 + * @return a {@code BigDecimal} whose value is equal to or approximately
1.1063 + * equal to the value of {@code val}.
1.1064 + * @throws NumberFormatException if {@code val} is infinite or NaN.
1.1065 + * @since 1.5
1.1066 + */
1.1067 + public static BigDecimal valueOf(double val) {
1.1068 + // Reminder: a zero double returns '0.0', so we cannot fastpath
1.1069 + // to use the constant ZERO. This might be important enough to
1.1070 + // justify a factory approach, a cache, or a few private
1.1071 + // constants, later.
1.1072 + return new BigDecimal(Double.toString(val));
1.1073 + }
1.1074 +
1.1075 + // Arithmetic Operations
1.1076 + /**
1.1077 + * Returns a {@code BigDecimal} whose value is {@code (this +
1.1078 + * augend)}, and whose scale is {@code max(this.scale(),
1.1079 + * augend.scale())}.
1.1080 + *
1.1081 + * @param augend value to be added to this {@code BigDecimal}.
1.1082 + * @return {@code this + augend}
1.1083 + */
1.1084 + public BigDecimal add(BigDecimal augend) {
1.1085 + long xs = this.intCompact;
1.1086 + long ys = augend.intCompact;
1.1087 + BigInteger fst = (xs != INFLATED) ? null : this.intVal;
1.1088 + BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
1.1089 + int rscale = this.scale;
1.1090 +
1.1091 + long sdiff = (long)rscale - augend.scale;
1.1092 + if (sdiff != 0) {
1.1093 + if (sdiff < 0) {
1.1094 + int raise = checkScale(-sdiff);
1.1095 + rscale = augend.scale;
1.1096 + if (xs == INFLATED ||
1.1097 + (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
1.1098 + fst = bigMultiplyPowerTen(raise);
1.1099 + } else {
1.1100 + int raise = augend.checkScale(sdiff);
1.1101 + if (ys == INFLATED ||
1.1102 + (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
1.1103 + snd = augend.bigMultiplyPowerTen(raise);
1.1104 + }
1.1105 + }
1.1106 + if (xs != INFLATED && ys != INFLATED) {
1.1107 + long sum = xs + ys;
1.1108 + // See "Hacker's Delight" section 2-12 for explanation of
1.1109 + // the overflow test.
1.1110 + if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
1.1111 + return BigDecimal.valueOf(sum, rscale);
1.1112 + }
1.1113 + if (fst == null)
1.1114 + fst = BigInteger.valueOf(xs);
1.1115 + if (snd == null)
1.1116 + snd = BigInteger.valueOf(ys);
1.1117 + BigInteger sum = fst.add(snd);
1.1118 + return (fst.signum == snd.signum) ?
1.1119 + new BigDecimal(sum, INFLATED, rscale, 0) :
1.1120 + new BigDecimal(sum, rscale);
1.1121 + }
1.1122 +
1.1123 + /**
1.1124 + * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1.1125 + * with rounding according to the context settings.
1.1126 + *
1.1127 + * If either number is zero and the precision setting is nonzero then
1.1128 + * the other number, rounded if necessary, is used as the result.
1.1129 + *
1.1130 + * @param augend value to be added to this {@code BigDecimal}.
1.1131 + * @param mc the context to use.
1.1132 + * @return {@code this + augend}, rounded as necessary.
1.1133 + * @throws ArithmeticException if the result is inexact but the
1.1134 + * rounding mode is {@code UNNECESSARY}.
1.1135 + * @since 1.5
1.1136 + */
1.1137 + public BigDecimal add(BigDecimal augend, MathContext mc) {
1.1138 + if (mc.precision == 0)
1.1139 + return add(augend);
1.1140 + BigDecimal lhs = this;
1.1141 +
1.1142 + // Could optimize if values are compact
1.1143 + this.inflate();
1.1144 + augend.inflate();
1.1145 +
1.1146 + // If either number is zero then the other number, rounded and
1.1147 + // scaled if necessary, is used as the result.
1.1148 + {
1.1149 + boolean lhsIsZero = lhs.signum() == 0;
1.1150 + boolean augendIsZero = augend.signum() == 0;
1.1151 +
1.1152 + if (lhsIsZero || augendIsZero) {
1.1153 + int preferredScale = Math.max(lhs.scale(), augend.scale());
1.1154 + BigDecimal result;
1.1155 +
1.1156 + // Could use a factory for zero instead of a new object
1.1157 + if (lhsIsZero && augendIsZero)
1.1158 + return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
1.1159 +
1.1160 + result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1.1161 +
1.1162 + if (result.scale() == preferredScale)
1.1163 + return result;
1.1164 + else if (result.scale() > preferredScale) {
1.1165 + BigDecimal scaledResult =
1.1166 + new BigDecimal(result.intVal, result.intCompact,
1.1167 + result.scale, 0);
1.1168 + scaledResult.stripZerosToMatchScale(preferredScale);
1.1169 + return scaledResult;
1.1170 + } else { // result.scale < preferredScale
1.1171 + int precisionDiff = mc.precision - result.precision();
1.1172 + int scaleDiff = preferredScale - result.scale();
1.1173 +
1.1174 + if (precisionDiff >= scaleDiff)
1.1175 + return result.setScale(preferredScale); // can achieve target scale
1.1176 + else
1.1177 + return result.setScale(result.scale() + precisionDiff);
1.1178 + }
1.1179 + }
1.1180 + }
1.1181 +
1.1182 + long padding = (long)lhs.scale - augend.scale;
1.1183 + if (padding != 0) { // scales differ; alignment needed
1.1184 + BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1.1185 + matchScale(arg);
1.1186 + lhs = arg[0];
1.1187 + augend = arg[1];
1.1188 + }
1.1189 +
1.1190 + BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
1.1191 + lhs.scale);
1.1192 + return doRound(d, mc);
1.1193 + }
1.1194 +
1.1195 + /**
1.1196 + * Returns an array of length two, the sum of whose entries is
1.1197 + * equal to the rounded sum of the {@code BigDecimal} arguments.
1.1198 + *
1.1199 + * <p>If the digit positions of the arguments have a sufficient
1.1200 + * gap between them, the value smaller in magnitude can be
1.1201 + * condensed into a {@literal "sticky bit"} and the end result will
1.1202 + * round the same way <em>if</em> the precision of the final
1.1203 + * result does not include the high order digit of the small
1.1204 + * magnitude operand.
1.1205 + *
1.1206 + * <p>Note that while strictly speaking this is an optimization,
1.1207 + * it makes a much wider range of additions practical.
1.1208 + *
1.1209 + * <p>This corresponds to a pre-shift operation in a fixed
1.1210 + * precision floating-point adder; this method is complicated by
1.1211 + * variable precision of the result as determined by the
1.1212 + * MathContext. A more nuanced operation could implement a
1.1213 + * {@literal "right shift"} on the smaller magnitude operand so
1.1214 + * that the number of digits of the smaller operand could be
1.1215 + * reduced even though the significands partially overlapped.
1.1216 + */
1.1217 + private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
1.1218 + long padding, MathContext mc) {
1.1219 + assert padding != 0;
1.1220 + BigDecimal big;
1.1221 + BigDecimal small;
1.1222 +
1.1223 + if (padding < 0) { // lhs is big; augend is small
1.1224 + big = lhs;
1.1225 + small = augend;
1.1226 + } else { // lhs is small; augend is big
1.1227 + big = augend;
1.1228 + small = lhs;
1.1229 + }
1.1230 +
1.1231 + /*
1.1232 + * This is the estimated scale of an ulp of the result; it
1.1233 + * assumes that the result doesn't have a carry-out on a true
1.1234 + * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1.1235 + * on borrowing (e.g. 100 - 1.2 => 98.8)
1.1236 + */
1.1237 + long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
1.1238 +
1.1239 + /*
1.1240 + * The low-order digit position of big is big.scale(). This
1.1241 + * is true regardless of whether big has a positive or
1.1242 + * negative scale. The high-order digit position of small is
1.1243 + * small.scale - (small.precision() - 1). To do the full
1.1244 + * condensation, the digit positions of big and small must be
1.1245 + * disjoint *and* the digit positions of small should not be
1.1246 + * directly visible in the result.
1.1247 + */
1.1248 + long smallHighDigitPos = (long)small.scale - small.precision() + 1;
1.1249 + if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1.1250 + smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1.1251 + small = BigDecimal.valueOf(small.signum(),
1.1252 + this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1.1253 + }
1.1254 +
1.1255 + // Since addition is symmetric, preserving input order in
1.1256 + // returned operands doesn't matter
1.1257 + BigDecimal[] result = {big, small};
1.1258 + return result;
1.1259 + }
1.1260 +
1.1261 + /**
1.1262 + * Returns a {@code BigDecimal} whose value is {@code (this -
1.1263 + * subtrahend)}, and whose scale is {@code max(this.scale(),
1.1264 + * subtrahend.scale())}.
1.1265 + *
1.1266 + * @param subtrahend value to be subtracted from this {@code BigDecimal}.
1.1267 + * @return {@code this - subtrahend}
1.1268 + */
1.1269 + public BigDecimal subtract(BigDecimal subtrahend) {
1.1270 + return add(subtrahend.negate());
1.1271 + }
1.1272 +
1.1273 + /**
1.1274 + * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1.1275 + * with rounding according to the context settings.
1.1276 + *
1.1277 + * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1.1278 + * result. If this is zero then the result is {@code subtrahend.negate(mc)}.
1.1279 + *
1.1280 + * @param subtrahend value to be subtracted from this {@code BigDecimal}.
1.1281 + * @param mc the context to use.
1.1282 + * @return {@code this - subtrahend}, rounded as necessary.
1.1283 + * @throws ArithmeticException if the result is inexact but the
1.1284 + * rounding mode is {@code UNNECESSARY}.
1.1285 + * @since 1.5
1.1286 + */
1.1287 + public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1.1288 + BigDecimal nsubtrahend = subtrahend.negate();
1.1289 + if (mc.precision == 0)
1.1290 + return add(nsubtrahend);
1.1291 + // share the special rounding code in add()
1.1292 + return add(nsubtrahend, mc);
1.1293 + }
1.1294 +
1.1295 + /**
1.1296 + * Returns a {@code BigDecimal} whose value is <tt>(this ×
1.1297 + * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1.1298 + * multiplicand.scale())}.
1.1299 + *
1.1300 + * @param multiplicand value to be multiplied by this {@code BigDecimal}.
1.1301 + * @return {@code this * multiplicand}
1.1302 + */
1.1303 + public BigDecimal multiply(BigDecimal multiplicand) {
1.1304 + long x = this.intCompact;
1.1305 + long y = multiplicand.intCompact;
1.1306 + int productScale = checkScale((long)scale + multiplicand.scale);
1.1307 +
1.1308 + // Might be able to do a more clever check incorporating the
1.1309 + // inflated check into the overflow computation.
1.1310 + if (x != INFLATED && y != INFLATED) {
1.1311 + /*
1.1312 + * If the product is not an overflowed value, continue
1.1313 + * to use the compact representation. if either of x or y
1.1314 + * is INFLATED, the product should also be regarded as
1.1315 + * an overflow. Before using the overflow test suggested in
1.1316 + * "Hacker's Delight" section 2-12, we perform quick checks
1.1317 + * using the precision information to see whether the overflow
1.1318 + * would occur since division is expensive on most CPUs.
1.1319 + */
1.1320 + long product = x * y;
1.1321 + long prec = this.precision() + multiplicand.precision();
1.1322 + if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
1.1323 + return BigDecimal.valueOf(product, productScale);
1.1324 + return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
1.1325 + productScale, 0);
1.1326 + }
1.1327 + BigInteger rb;
1.1328 + if (x == INFLATED && y == INFLATED)
1.1329 + rb = this.intVal.multiply(multiplicand.intVal);
1.1330 + else if (x != INFLATED)
1.1331 + rb = multiplicand.intVal.multiply(x);
1.1332 + else
1.1333 + rb = this.intVal.multiply(y);
1.1334 + return new BigDecimal(rb, INFLATED, productScale, 0);
1.1335 + }
1.1336 +
1.1337 + /**
1.1338 + * Returns a {@code BigDecimal} whose value is <tt>(this ×
1.1339 + * multiplicand)</tt>, with rounding according to the context settings.
1.1340 + *
1.1341 + * @param multiplicand value to be multiplied by this {@code BigDecimal}.
1.1342 + * @param mc the context to use.
1.1343 + * @return {@code this * multiplicand}, rounded as necessary.
1.1344 + * @throws ArithmeticException if the result is inexact but the
1.1345 + * rounding mode is {@code UNNECESSARY}.
1.1346 + * @since 1.5
1.1347 + */
1.1348 + public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1.1349 + if (mc.precision == 0)
1.1350 + return multiply(multiplicand);
1.1351 + return doRound(this.multiply(multiplicand), mc);
1.1352 + }
1.1353 +
1.1354 + /**
1.1355 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1356 + * divisor)}, and whose scale is as specified. If rounding must
1.1357 + * be performed to generate a result with the specified scale, the
1.1358 + * specified rounding mode is applied.
1.1359 + *
1.1360 + * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1.1361 + * should be used in preference to this legacy method.
1.1362 + *
1.1363 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1364 + * @param scale scale of the {@code BigDecimal} quotient to be returned.
1.1365 + * @param roundingMode rounding mode to apply.
1.1366 + * @return {@code this / divisor}
1.1367 + * @throws ArithmeticException if {@code divisor} is zero,
1.1368 + * {@code roundingMode==ROUND_UNNECESSARY} and
1.1369 + * the specified scale is insufficient to represent the result
1.1370 + * of the division exactly.
1.1371 + * @throws IllegalArgumentException if {@code roundingMode} does not
1.1372 + * represent a valid rounding mode.
1.1373 + * @see #ROUND_UP
1.1374 + * @see #ROUND_DOWN
1.1375 + * @see #ROUND_CEILING
1.1376 + * @see #ROUND_FLOOR
1.1377 + * @see #ROUND_HALF_UP
1.1378 + * @see #ROUND_HALF_DOWN
1.1379 + * @see #ROUND_HALF_EVEN
1.1380 + * @see #ROUND_UNNECESSARY
1.1381 + */
1.1382 + public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1.1383 + /*
1.1384 + * IMPLEMENTATION NOTE: This method *must* return a new object
1.1385 + * since divideAndRound uses divide to generate a value whose
1.1386 + * scale is then modified.
1.1387 + */
1.1388 + if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1.1389 + throw new IllegalArgumentException("Invalid rounding mode");
1.1390 + /*
1.1391 + * Rescale dividend or divisor (whichever can be "upscaled" to
1.1392 + * produce correctly scaled quotient).
1.1393 + * Take care to detect out-of-range scales
1.1394 + */
1.1395 + BigDecimal dividend = this;
1.1396 + if (checkScale((long)scale + divisor.scale) > this.scale)
1.1397 + dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
1.1398 + else
1.1399 + divisor = divisor.setScale(checkScale((long)this.scale - scale),
1.1400 + ROUND_UNNECESSARY);
1.1401 + return divideAndRound(dividend.intCompact, dividend.intVal,
1.1402 + divisor.intCompact, divisor.intVal,
1.1403 + scale, roundingMode, scale);
1.1404 + }
1.1405 +
1.1406 + /**
1.1407 + * Internally used for division operation. The dividend and divisor are
1.1408 + * passed both in {@code long} format and {@code BigInteger} format. The
1.1409 + * returned {@code BigDecimal} object is the quotient whose scale is set to
1.1410 + * the passed in scale. If the remainder is not zero, it will be rounded
1.1411 + * based on the passed in roundingMode. Also, if the remainder is zero and
1.1412 + * the last parameter, i.e. preferredScale is NOT equal to scale, the
1.1413 + * trailing zeros of the result is stripped to match the preferredScale.
1.1414 + */
1.1415 + private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend,
1.1416 + long ldivisor, BigInteger bdivisor,
1.1417 + int scale, int roundingMode,
1.1418 + int preferredScale) {
1.1419 + boolean isRemainderZero; // record remainder is zero or not
1.1420 + int qsign; // quotient sign
1.1421 + long q = 0, r = 0; // store quotient & remainder in long
1.1422 + MutableBigInteger mq = null; // store quotient
1.1423 + MutableBigInteger mr = null; // store remainder
1.1424 + MutableBigInteger mdivisor = null;
1.1425 + boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
1.1426 + if (isLongDivision) {
1.1427 + q = ldividend / ldivisor;
1.1428 + if (roundingMode == ROUND_DOWN && scale == preferredScale)
1.1429 + return new BigDecimal(null, q, scale, 0);
1.1430 + r = ldividend % ldivisor;
1.1431 + isRemainderZero = (r == 0);
1.1432 + qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
1.1433 + } else {
1.1434 + if (bdividend == null)
1.1435 + bdividend = BigInteger.valueOf(ldividend);
1.1436 + // Descend into mutables for faster remainder checks
1.1437 + MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
1.1438 + mq = new MutableBigInteger();
1.1439 + if (ldivisor != INFLATED) {
1.1440 + r = mdividend.divide(ldivisor, mq);
1.1441 + isRemainderZero = (r == 0);
1.1442 + qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
1.1443 + } else {
1.1444 + mdivisor = new MutableBigInteger(bdivisor.mag);
1.1445 + mr = mdividend.divide(mdivisor, mq);
1.1446 + isRemainderZero = mr.isZero();
1.1447 + qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
1.1448 + }
1.1449 + }
1.1450 + boolean increment = false;
1.1451 + if (!isRemainderZero) {
1.1452 + int cmpFracHalf;
1.1453 + /* Round as appropriate */
1.1454 + if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited
1.1455 + throw new ArithmeticException("Rounding necessary");
1.1456 + } else if (roundingMode == ROUND_UP) { // Away from zero
1.1457 + increment = true;
1.1458 + } else if (roundingMode == ROUND_DOWN) { // Towards zero
1.1459 + increment = false;
1.1460 + } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1.1461 + increment = (qsign > 0);
1.1462 + } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
1.1463 + increment = (qsign < 0);
1.1464 + } else {
1.1465 + if (isLongDivision || ldivisor != INFLATED) {
1.1466 + if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
1.1467 + cmpFracHalf = 1; // 2 * r can't fit into long
1.1468 + } else {
1.1469 + cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
1.1470 + }
1.1471 + } else {
1.1472 + cmpFracHalf = mr.compareHalf(mdivisor);
1.1473 + }
1.1474 + if (cmpFracHalf < 0)
1.1475 + increment = false; // We're closer to higher digit
1.1476 + else if (cmpFracHalf > 0) // We're closer to lower digit
1.1477 + increment = true;
1.1478 + else if (roundingMode == ROUND_HALF_UP)
1.1479 + increment = true;
1.1480 + else if (roundingMode == ROUND_HALF_DOWN)
1.1481 + increment = false;
1.1482 + else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
1.1483 + increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
1.1484 + }
1.1485 + }
1.1486 + BigDecimal res;
1.1487 + if (isLongDivision)
1.1488 + res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
1.1489 + else {
1.1490 + if (increment)
1.1491 + mq.add(MutableBigInteger.ONE);
1.1492 + res = mq.toBigDecimal(qsign, scale);
1.1493 + }
1.1494 + if (isRemainderZero && preferredScale != scale)
1.1495 + res.stripZerosToMatchScale(preferredScale);
1.1496 + return res;
1.1497 + }
1.1498 +
1.1499 + /**
1.1500 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1501 + * divisor)}, and whose scale is as specified. If rounding must
1.1502 + * be performed to generate a result with the specified scale, the
1.1503 + * specified rounding mode is applied.
1.1504 + *
1.1505 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1506 + * @param scale scale of the {@code BigDecimal} quotient to be returned.
1.1507 + * @param roundingMode rounding mode to apply.
1.1508 + * @return {@code this / divisor}
1.1509 + * @throws ArithmeticException if {@code divisor} is zero,
1.1510 + * {@code roundingMode==RoundingMode.UNNECESSARY} and
1.1511 + * the specified scale is insufficient to represent the result
1.1512 + * of the division exactly.
1.1513 + * @since 1.5
1.1514 + */
1.1515 + public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1.1516 + return divide(divisor, scale, roundingMode.oldMode);
1.1517 + }
1.1518 +
1.1519 + /**
1.1520 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1521 + * divisor)}, and whose scale is {@code this.scale()}. If
1.1522 + * rounding must be performed to generate a result with the given
1.1523 + * scale, the specified rounding mode is applied.
1.1524 + *
1.1525 + * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1.1526 + * should be used in preference to this legacy method.
1.1527 + *
1.1528 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1529 + * @param roundingMode rounding mode to apply.
1.1530 + * @return {@code this / divisor}
1.1531 + * @throws ArithmeticException if {@code divisor==0}, or
1.1532 + * {@code roundingMode==ROUND_UNNECESSARY} and
1.1533 + * {@code this.scale()} is insufficient to represent the result
1.1534 + * of the division exactly.
1.1535 + * @throws IllegalArgumentException if {@code roundingMode} does not
1.1536 + * represent a valid rounding mode.
1.1537 + * @see #ROUND_UP
1.1538 + * @see #ROUND_DOWN
1.1539 + * @see #ROUND_CEILING
1.1540 + * @see #ROUND_FLOOR
1.1541 + * @see #ROUND_HALF_UP
1.1542 + * @see #ROUND_HALF_DOWN
1.1543 + * @see #ROUND_HALF_EVEN
1.1544 + * @see #ROUND_UNNECESSARY
1.1545 + */
1.1546 + public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1.1547 + return this.divide(divisor, scale, roundingMode);
1.1548 + }
1.1549 +
1.1550 + /**
1.1551 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1552 + * divisor)}, and whose scale is {@code this.scale()}. If
1.1553 + * rounding must be performed to generate a result with the given
1.1554 + * scale, the specified rounding mode is applied.
1.1555 + *
1.1556 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1557 + * @param roundingMode rounding mode to apply.
1.1558 + * @return {@code this / divisor}
1.1559 + * @throws ArithmeticException if {@code divisor==0}, or
1.1560 + * {@code roundingMode==RoundingMode.UNNECESSARY} and
1.1561 + * {@code this.scale()} is insufficient to represent the result
1.1562 + * of the division exactly.
1.1563 + * @since 1.5
1.1564 + */
1.1565 + public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1.1566 + return this.divide(divisor, scale, roundingMode.oldMode);
1.1567 + }
1.1568 +
1.1569 + /**
1.1570 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1571 + * divisor)}, and whose preferred scale is {@code (this.scale() -
1.1572 + * divisor.scale())}; if the exact quotient cannot be
1.1573 + * represented (because it has a non-terminating decimal
1.1574 + * expansion) an {@code ArithmeticException} is thrown.
1.1575 + *
1.1576 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1577 + * @throws ArithmeticException if the exact quotient does not have a
1.1578 + * terminating decimal expansion
1.1579 + * @return {@code this / divisor}
1.1580 + * @since 1.5
1.1581 + * @author Joseph D. Darcy
1.1582 + */
1.1583 + public BigDecimal divide(BigDecimal divisor) {
1.1584 + /*
1.1585 + * Handle zero cases first.
1.1586 + */
1.1587 + if (divisor.signum() == 0) { // x/0
1.1588 + if (this.signum() == 0) // 0/0
1.1589 + throw new ArithmeticException("Division undefined"); // NaN
1.1590 + throw new ArithmeticException("Division by zero");
1.1591 + }
1.1592 +
1.1593 + // Calculate preferred scale
1.1594 + int preferredScale = saturateLong((long)this.scale - divisor.scale);
1.1595 + if (this.signum() == 0) // 0/y
1.1596 + return (preferredScale >= 0 &&
1.1597 + preferredScale < ZERO_SCALED_BY.length) ?
1.1598 + ZERO_SCALED_BY[preferredScale] :
1.1599 + BigDecimal.valueOf(0, preferredScale);
1.1600 + else {
1.1601 + this.inflate();
1.1602 + divisor.inflate();
1.1603 + /*
1.1604 + * If the quotient this/divisor has a terminating decimal
1.1605 + * expansion, the expansion can have no more than
1.1606 + * (a.precision() + ceil(10*b.precision)/3) digits.
1.1607 + * Therefore, create a MathContext object with this
1.1608 + * precision and do a divide with the UNNECESSARY rounding
1.1609 + * mode.
1.1610 + */
1.1611 + MathContext mc = new MathContext( (int)Math.min(this.precision() +
1.1612 + (long)Math.ceil(10.0*divisor.precision()/3.0),
1.1613 + Integer.MAX_VALUE),
1.1614 + RoundingMode.UNNECESSARY);
1.1615 + BigDecimal quotient;
1.1616 + try {
1.1617 + quotient = this.divide(divisor, mc);
1.1618 + } catch (ArithmeticException e) {
1.1619 + throw new ArithmeticException("Non-terminating decimal expansion; " +
1.1620 + "no exact representable decimal result.");
1.1621 + }
1.1622 +
1.1623 + int quotientScale = quotient.scale();
1.1624 +
1.1625 + // divide(BigDecimal, mc) tries to adjust the quotient to
1.1626 + // the desired one by removing trailing zeros; since the
1.1627 + // exact divide method does not have an explicit digit
1.1628 + // limit, we can add zeros too.
1.1629 +
1.1630 + if (preferredScale > quotientScale)
1.1631 + return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1.1632 +
1.1633 + return quotient;
1.1634 + }
1.1635 + }
1.1636 +
1.1637 + /**
1.1638 + * Returns a {@code BigDecimal} whose value is {@code (this /
1.1639 + * divisor)}, with rounding according to the context settings.
1.1640 + *
1.1641 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1642 + * @param mc the context to use.
1.1643 + * @return {@code this / divisor}, rounded as necessary.
1.1644 + * @throws ArithmeticException if the result is inexact but the
1.1645 + * rounding mode is {@code UNNECESSARY} or
1.1646 + * {@code mc.precision == 0} and the quotient has a
1.1647 + * non-terminating decimal expansion.
1.1648 + * @since 1.5
1.1649 + */
1.1650 + public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1.1651 + int mcp = mc.precision;
1.1652 + if (mcp == 0)
1.1653 + return divide(divisor);
1.1654 +
1.1655 + BigDecimal dividend = this;
1.1656 + long preferredScale = (long)dividend.scale - divisor.scale;
1.1657 + // Now calculate the answer. We use the existing
1.1658 + // divide-and-round method, but as this rounds to scale we have
1.1659 + // to normalize the values here to achieve the desired result.
1.1660 + // For x/y we first handle y=0 and x=0, and then normalize x and
1.1661 + // y to give x' and y' with the following constraints:
1.1662 + // (a) 0.1 <= x' < 1
1.1663 + // (b) x' <= y' < 10*x'
1.1664 + // Dividing x'/y' with the required scale set to mc.precision then
1.1665 + // will give a result in the range 0.1 to 1 rounded to exactly
1.1666 + // the right number of digits (except in the case of a result of
1.1667 + // 1.000... which can arise when x=y, or when rounding overflows
1.1668 + // The 1.000... case will reduce properly to 1.
1.1669 + if (divisor.signum() == 0) { // x/0
1.1670 + if (dividend.signum() == 0) // 0/0
1.1671 + throw new ArithmeticException("Division undefined"); // NaN
1.1672 + throw new ArithmeticException("Division by zero");
1.1673 + }
1.1674 + if (dividend.signum() == 0) // 0/y
1.1675 + return new BigDecimal(BigInteger.ZERO, 0,
1.1676 + saturateLong(preferredScale), 1);
1.1677 +
1.1678 + // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
1.1679 + int xscale = dividend.precision();
1.1680 + int yscale = divisor.precision();
1.1681 + dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
1.1682 + xscale, xscale);
1.1683 + divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
1.1684 + yscale, yscale);
1.1685 + if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
1.1686 + yscale = divisor.scale -= 1; // [that is, divisor *= 10]
1.1687 +
1.1688 + // In order to find out whether the divide generates the exact result,
1.1689 + // we avoid calling the above divide method. 'quotient' holds the
1.1690 + // return BigDecimal object whose scale will be set to 'scl'.
1.1691 + BigDecimal quotient;
1.1692 + int scl = checkScale(preferredScale + yscale - xscale + mcp);
1.1693 + if (checkScale((long)mcp + yscale) > xscale)
1.1694 + dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
1.1695 + else
1.1696 + divisor = divisor.setScale(checkScale((long)xscale - mcp),
1.1697 + ROUND_UNNECESSARY);
1.1698 + quotient = divideAndRound(dividend.intCompact, dividend.intVal,
1.1699 + divisor.intCompact, divisor.intVal,
1.1700 + scl, mc.roundingMode.oldMode,
1.1701 + checkScale(preferredScale));
1.1702 + // doRound, here, only affects 1000000000 case.
1.1703 + quotient = doRound(quotient, mc);
1.1704 +
1.1705 + return quotient;
1.1706 + }
1.1707 +
1.1708 + /**
1.1709 + * Returns a {@code BigDecimal} whose value is the integer part
1.1710 + * of the quotient {@code (this / divisor)} rounded down. The
1.1711 + * preferred scale of the result is {@code (this.scale() -
1.1712 + * divisor.scale())}.
1.1713 + *
1.1714 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1715 + * @return The integer part of {@code this / divisor}.
1.1716 + * @throws ArithmeticException if {@code divisor==0}
1.1717 + * @since 1.5
1.1718 + */
1.1719 + public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1.1720 + // Calculate preferred scale
1.1721 + int preferredScale = saturateLong((long)this.scale - divisor.scale);
1.1722 + if (this.compareMagnitude(divisor) < 0) {
1.1723 + // much faster when this << divisor
1.1724 + return BigDecimal.valueOf(0, preferredScale);
1.1725 + }
1.1726 +
1.1727 + if(this.signum() == 0 && divisor.signum() != 0)
1.1728 + return this.setScale(preferredScale, ROUND_UNNECESSARY);
1.1729 +
1.1730 + // Perform a divide with enough digits to round to a correct
1.1731 + // integer value; then remove any fractional digits
1.1732 +
1.1733 + int maxDigits = (int)Math.min(this.precision() +
1.1734 + (long)Math.ceil(10.0*divisor.precision()/3.0) +
1.1735 + Math.abs((long)this.scale() - divisor.scale()) + 2,
1.1736 + Integer.MAX_VALUE);
1.1737 + BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1.1738 + RoundingMode.DOWN));
1.1739 + if (quotient.scale > 0) {
1.1740 + quotient = quotient.setScale(0, RoundingMode.DOWN);
1.1741 + quotient.stripZerosToMatchScale(preferredScale);
1.1742 + }
1.1743 +
1.1744 + if (quotient.scale < preferredScale) {
1.1745 + // pad with zeros if necessary
1.1746 + quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1.1747 + }
1.1748 + return quotient;
1.1749 + }
1.1750 +
1.1751 + /**
1.1752 + * Returns a {@code BigDecimal} whose value is the integer part
1.1753 + * of {@code (this / divisor)}. Since the integer part of the
1.1754 + * exact quotient does not depend on the rounding mode, the
1.1755 + * rounding mode does not affect the values returned by this
1.1756 + * method. The preferred scale of the result is
1.1757 + * {@code (this.scale() - divisor.scale())}. An
1.1758 + * {@code ArithmeticException} is thrown if the integer part of
1.1759 + * the exact quotient needs more than {@code mc.precision}
1.1760 + * digits.
1.1761 + *
1.1762 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1763 + * @param mc the context to use.
1.1764 + * @return The integer part of {@code this / divisor}.
1.1765 + * @throws ArithmeticException if {@code divisor==0}
1.1766 + * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1.1767 + * requires a precision of more than {@code mc.precision} digits.
1.1768 + * @since 1.5
1.1769 + * @author Joseph D. Darcy
1.1770 + */
1.1771 + public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1.1772 + if (mc.precision == 0 || // exact result
1.1773 + (this.compareMagnitude(divisor) < 0) ) // zero result
1.1774 + return divideToIntegralValue(divisor);
1.1775 +
1.1776 + // Calculate preferred scale
1.1777 + int preferredScale = saturateLong((long)this.scale - divisor.scale);
1.1778 +
1.1779 + /*
1.1780 + * Perform a normal divide to mc.precision digits. If the
1.1781 + * remainder has absolute value less than the divisor, the
1.1782 + * integer portion of the quotient fits into mc.precision
1.1783 + * digits. Next, remove any fractional digits from the
1.1784 + * quotient and adjust the scale to the preferred value.
1.1785 + */
1.1786 + BigDecimal result = this.
1.1787 + divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1.1788 +
1.1789 + if (result.scale() < 0) {
1.1790 + /*
1.1791 + * Result is an integer. See if quotient represents the
1.1792 + * full integer portion of the exact quotient; if it does,
1.1793 + * the computed remainder will be less than the divisor.
1.1794 + */
1.1795 + BigDecimal product = result.multiply(divisor);
1.1796 + // If the quotient is the full integer value,
1.1797 + // |dividend-product| < |divisor|.
1.1798 + if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1.1799 + throw new ArithmeticException("Division impossible");
1.1800 + }
1.1801 + } else if (result.scale() > 0) {
1.1802 + /*
1.1803 + * Integer portion of quotient will fit into precision
1.1804 + * digits; recompute quotient to scale 0 to avoid double
1.1805 + * rounding and then try to adjust, if necessary.
1.1806 + */
1.1807 + result = result.setScale(0, RoundingMode.DOWN);
1.1808 + }
1.1809 + // else result.scale() == 0;
1.1810 +
1.1811 + int precisionDiff;
1.1812 + if ((preferredScale > result.scale()) &&
1.1813 + (precisionDiff = mc.precision - result.precision()) > 0) {
1.1814 + return result.setScale(result.scale() +
1.1815 + Math.min(precisionDiff, preferredScale - result.scale) );
1.1816 + } else {
1.1817 + result.stripZerosToMatchScale(preferredScale);
1.1818 + return result;
1.1819 + }
1.1820 + }
1.1821 +
1.1822 + /**
1.1823 + * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1.1824 + *
1.1825 + * <p>The remainder is given by
1.1826 + * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1.1827 + * Note that this is not the modulo operation (the result can be
1.1828 + * negative).
1.1829 + *
1.1830 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1831 + * @return {@code this % divisor}.
1.1832 + * @throws ArithmeticException if {@code divisor==0}
1.1833 + * @since 1.5
1.1834 + */
1.1835 + public BigDecimal remainder(BigDecimal divisor) {
1.1836 + BigDecimal divrem[] = this.divideAndRemainder(divisor);
1.1837 + return divrem[1];
1.1838 + }
1.1839 +
1.1840 +
1.1841 + /**
1.1842 + * Returns a {@code BigDecimal} whose value is {@code (this %
1.1843 + * divisor)}, with rounding according to the context settings.
1.1844 + * The {@code MathContext} settings affect the implicit divide
1.1845 + * used to compute the remainder. The remainder computation
1.1846 + * itself is by definition exact. Therefore, the remainder may
1.1847 + * contain more than {@code mc.getPrecision()} digits.
1.1848 + *
1.1849 + * <p>The remainder is given by
1.1850 + * {@code this.subtract(this.divideToIntegralValue(divisor,
1.1851 + * mc).multiply(divisor))}. Note that this is not the modulo
1.1852 + * operation (the result can be negative).
1.1853 + *
1.1854 + * @param divisor value by which this {@code BigDecimal} is to be divided.
1.1855 + * @param mc the context to use.
1.1856 + * @return {@code this % divisor}, rounded as necessary.
1.1857 + * @throws ArithmeticException if {@code divisor==0}
1.1858 + * @throws ArithmeticException if the result is inexact but the
1.1859 + * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1.1860 + * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1.1861 + * require a precision of more than {@code mc.precision} digits.
1.1862 + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1.1863 + * @since 1.5
1.1864 + */
1.1865 + public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1.1866 + BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1.1867 + return divrem[1];
1.1868 + }
1.1869 +
1.1870 + /**
1.1871 + * Returns a two-element {@code BigDecimal} array containing the
1.1872 + * result of {@code divideToIntegralValue} followed by the result of
1.1873 + * {@code remainder} on the two operands.
1.1874 + *
1.1875 + * <p>Note that if both the integer quotient and remainder are
1.1876 + * needed, this method is faster than using the
1.1877 + * {@code divideToIntegralValue} and {@code remainder} methods
1.1878 + * separately because the division need only be carried out once.
1.1879 + *
1.1880 + * @param divisor value by which this {@code BigDecimal} is to be divided,
1.1881 + * and the remainder computed.
1.1882 + * @return a two element {@code BigDecimal} array: the quotient
1.1883 + * (the result of {@code divideToIntegralValue}) is the initial element
1.1884 + * and the remainder is the final element.
1.1885 + * @throws ArithmeticException if {@code divisor==0}
1.1886 + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1.1887 + * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1.1888 + * @since 1.5
1.1889 + */
1.1890 + public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1.1891 + // we use the identity x = i * y + r to determine r
1.1892 + BigDecimal[] result = new BigDecimal[2];
1.1893 +
1.1894 + result[0] = this.divideToIntegralValue(divisor);
1.1895 + result[1] = this.subtract(result[0].multiply(divisor));
1.1896 + return result;
1.1897 + }
1.1898 +
1.1899 + /**
1.1900 + * Returns a two-element {@code BigDecimal} array containing the
1.1901 + * result of {@code divideToIntegralValue} followed by the result of
1.1902 + * {@code remainder} on the two operands calculated with rounding
1.1903 + * according to the context settings.
1.1904 + *
1.1905 + * <p>Note that if both the integer quotient and remainder are
1.1906 + * needed, this method is faster than using the
1.1907 + * {@code divideToIntegralValue} and {@code remainder} methods
1.1908 + * separately because the division need only be carried out once.
1.1909 + *
1.1910 + * @param divisor value by which this {@code BigDecimal} is to be divided,
1.1911 + * and the remainder computed.
1.1912 + * @param mc the context to use.
1.1913 + * @return a two element {@code BigDecimal} array: the quotient
1.1914 + * (the result of {@code divideToIntegralValue}) is the
1.1915 + * initial element and the remainder is the final element.
1.1916 + * @throws ArithmeticException if {@code divisor==0}
1.1917 + * @throws ArithmeticException if the result is inexact but the
1.1918 + * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1.1919 + * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1.1920 + * require a precision of more than {@code mc.precision} digits.
1.1921 + * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1.1922 + * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1.1923 + * @since 1.5
1.1924 + */
1.1925 + public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1.1926 + if (mc.precision == 0)
1.1927 + return divideAndRemainder(divisor);
1.1928 +
1.1929 + BigDecimal[] result = new BigDecimal[2];
1.1930 + BigDecimal lhs = this;
1.1931 +
1.1932 + result[0] = lhs.divideToIntegralValue(divisor, mc);
1.1933 + result[1] = lhs.subtract(result[0].multiply(divisor));
1.1934 + return result;
1.1935 + }
1.1936 +
1.1937 + /**
1.1938 + * Returns a {@code BigDecimal} whose value is
1.1939 + * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
1.1940 + * unlimited precision.
1.1941 + *
1.1942 + * <p>The parameter {@code n} must be in the range 0 through
1.1943 + * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
1.1944 + * #ONE}.
1.1945 + *
1.1946 + * Note that future releases may expand the allowable exponent
1.1947 + * range of this method.
1.1948 + *
1.1949 + * @param n power to raise this {@code BigDecimal} to.
1.1950 + * @return <tt>this<sup>n</sup></tt>
1.1951 + * @throws ArithmeticException if {@code n} is out of range.
1.1952 + * @since 1.5
1.1953 + */
1.1954 + public BigDecimal pow(int n) {
1.1955 + if (n < 0 || n > 999999999)
1.1956 + throw new ArithmeticException("Invalid operation");
1.1957 + // No need to calculate pow(n) if result will over/underflow.
1.1958 + // Don't attempt to support "supernormal" numbers.
1.1959 + int newScale = checkScale((long)scale * n);
1.1960 + this.inflate();
1.1961 + return new BigDecimal(intVal.pow(n), newScale);
1.1962 + }
1.1963 +
1.1964 +
1.1965 + /**
1.1966 + * Returns a {@code BigDecimal} whose value is
1.1967 + * <tt>(this<sup>n</sup>)</tt>. The current implementation uses
1.1968 + * the core algorithm defined in ANSI standard X3.274-1996 with
1.1969 + * rounding according to the context settings. In general, the
1.1970 + * returned numerical value is within two ulps of the exact
1.1971 + * numerical value for the chosen precision. Note that future
1.1972 + * releases may use a different algorithm with a decreased
1.1973 + * allowable error bound and increased allowable exponent range.
1.1974 + *
1.1975 + * <p>The X3.274-1996 algorithm is:
1.1976 + *
1.1977 + * <ul>
1.1978 + * <li> An {@code ArithmeticException} exception is thrown if
1.1979 + * <ul>
1.1980 + * <li>{@code abs(n) > 999999999}
1.1981 + * <li>{@code mc.precision == 0} and {@code n < 0}
1.1982 + * <li>{@code mc.precision > 0} and {@code n} has more than
1.1983 + * {@code mc.precision} decimal digits
1.1984 + * </ul>
1.1985 + *
1.1986 + * <li> if {@code n} is zero, {@link #ONE} is returned even if
1.1987 + * {@code this} is zero, otherwise
1.1988 + * <ul>
1.1989 + * <li> if {@code n} is positive, the result is calculated via
1.1990 + * the repeated squaring technique into a single accumulator.
1.1991 + * The individual multiplications with the accumulator use the
1.1992 + * same math context settings as in {@code mc} except for a
1.1993 + * precision increased to {@code mc.precision + elength + 1}
1.1994 + * where {@code elength} is the number of decimal digits in
1.1995 + * {@code n}.
1.1996 + *
1.1997 + * <li> if {@code n} is negative, the result is calculated as if
1.1998 + * {@code n} were positive; this value is then divided into one
1.1999 + * using the working precision specified above.
1.2000 + *
1.2001 + * <li> The final value from either the positive or negative case
1.2002 + * is then rounded to the destination precision.
1.2003 + * </ul>
1.2004 + * </ul>
1.2005 + *
1.2006 + * @param n power to raise this {@code BigDecimal} to.
1.2007 + * @param mc the context to use.
1.2008 + * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
1.2009 + * algorithm
1.2010 + * @throws ArithmeticException if the result is inexact but the
1.2011 + * rounding mode is {@code UNNECESSARY}, or {@code n} is out
1.2012 + * of range.
1.2013 + * @since 1.5
1.2014 + */
1.2015 + public BigDecimal pow(int n, MathContext mc) {
1.2016 + if (mc.precision == 0)
1.2017 + return pow(n);
1.2018 + if (n < -999999999 || n > 999999999)
1.2019 + throw new ArithmeticException("Invalid operation");
1.2020 + if (n == 0)
1.2021 + return ONE; // x**0 == 1 in X3.274
1.2022 + this.inflate();
1.2023 + BigDecimal lhs = this;
1.2024 + MathContext workmc = mc; // working settings
1.2025 + int mag = Math.abs(n); // magnitude of n
1.2026 + if (mc.precision > 0) {
1.2027 +
1.2028 + int elength = longDigitLength(mag); // length of n in digits
1.2029 + if (elength > mc.precision) // X3.274 rule
1.2030 + throw new ArithmeticException("Invalid operation");
1.2031 + workmc = new MathContext(mc.precision + elength + 1,
1.2032 + mc.roundingMode);
1.2033 + }
1.2034 + // ready to carry out power calculation...
1.2035 + BigDecimal acc = ONE; // accumulator
1.2036 + boolean seenbit = false; // set once we've seen a 1-bit
1.2037 + for (int i=1;;i++) { // for each bit [top bit ignored]
1.2038 + mag += mag; // shift left 1 bit
1.2039 + if (mag < 0) { // top bit is set
1.2040 + seenbit = true; // OK, we're off
1.2041 + acc = acc.multiply(lhs, workmc); // acc=acc*x
1.2042 + }
1.2043 + if (i == 31)
1.2044 + break; // that was the last bit
1.2045 + if (seenbit)
1.2046 + acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
1.2047 + // else (!seenbit) no point in squaring ONE
1.2048 + }
1.2049 + // if negative n, calculate the reciprocal using working precision
1.2050 + if (n<0) // [hence mc.precision>0]
1.2051 + acc=ONE.divide(acc, workmc);
1.2052 + // round to final precision and strip zeros
1.2053 + return doRound(acc, mc);
1.2054 + }
1.2055 +
1.2056 + /**
1.2057 + * Returns a {@code BigDecimal} whose value is the absolute value
1.2058 + * of this {@code BigDecimal}, and whose scale is
1.2059 + * {@code this.scale()}.
1.2060 + *
1.2061 + * @return {@code abs(this)}
1.2062 + */
1.2063 + public BigDecimal abs() {
1.2064 + return (signum() < 0 ? negate() : this);
1.2065 + }
1.2066 +
1.2067 + /**
1.2068 + * Returns a {@code BigDecimal} whose value is the absolute value
1.2069 + * of this {@code BigDecimal}, with rounding according to the
1.2070 + * context settings.
1.2071 + *
1.2072 + * @param mc the context to use.
1.2073 + * @return {@code abs(this)}, rounded as necessary.
1.2074 + * @throws ArithmeticException if the result is inexact but the
1.2075 + * rounding mode is {@code UNNECESSARY}.
1.2076 + * @since 1.5
1.2077 + */
1.2078 + public BigDecimal abs(MathContext mc) {
1.2079 + return (signum() < 0 ? negate(mc) : plus(mc));
1.2080 + }
1.2081 +
1.2082 + /**
1.2083 + * Returns a {@code BigDecimal} whose value is {@code (-this)},
1.2084 + * and whose scale is {@code this.scale()}.
1.2085 + *
1.2086 + * @return {@code -this}.
1.2087 + */
1.2088 + public BigDecimal negate() {
1.2089 + BigDecimal result;
1.2090 + if (intCompact != INFLATED)
1.2091 + result = BigDecimal.valueOf(-intCompact, scale);
1.2092 + else {
1.2093 + result = new BigDecimal(intVal.negate(), scale);
1.2094 + result.precision = precision;
1.2095 + }
1.2096 + return result;
1.2097 + }
1.2098 +
1.2099 + /**
1.2100 + * Returns a {@code BigDecimal} whose value is {@code (-this)},
1.2101 + * with rounding according to the context settings.
1.2102 + *
1.2103 + * @param mc the context to use.
1.2104 + * @return {@code -this}, rounded as necessary.
1.2105 + * @throws ArithmeticException if the result is inexact but the
1.2106 + * rounding mode is {@code UNNECESSARY}.
1.2107 + * @since 1.5
1.2108 + */
1.2109 + public BigDecimal negate(MathContext mc) {
1.2110 + return negate().plus(mc);
1.2111 + }
1.2112 +
1.2113 + /**
1.2114 + * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
1.2115 + * scale is {@code this.scale()}.
1.2116 + *
1.2117 + * <p>This method, which simply returns this {@code BigDecimal}
1.2118 + * is included for symmetry with the unary minus method {@link
1.2119 + * #negate()}.
1.2120 + *
1.2121 + * @return {@code this}.
1.2122 + * @see #negate()
1.2123 + * @since 1.5
1.2124 + */
1.2125 + public BigDecimal plus() {
1.2126 + return this;
1.2127 + }
1.2128 +
1.2129 + /**
1.2130 + * Returns a {@code BigDecimal} whose value is {@code (+this)},
1.2131 + * with rounding according to the context settings.
1.2132 + *
1.2133 + * <p>The effect of this method is identical to that of the {@link
1.2134 + * #round(MathContext)} method.
1.2135 + *
1.2136 + * @param mc the context to use.
1.2137 + * @return {@code this}, rounded as necessary. A zero result will
1.2138 + * have a scale of 0.
1.2139 + * @throws ArithmeticException if the result is inexact but the
1.2140 + * rounding mode is {@code UNNECESSARY}.
1.2141 + * @see #round(MathContext)
1.2142 + * @since 1.5
1.2143 + */
1.2144 + public BigDecimal plus(MathContext mc) {
1.2145 + if (mc.precision == 0) // no rounding please
1.2146 + return this;
1.2147 + return doRound(this, mc);
1.2148 + }
1.2149 +
1.2150 + /**
1.2151 + * Returns the signum function of this {@code BigDecimal}.
1.2152 + *
1.2153 + * @return -1, 0, or 1 as the value of this {@code BigDecimal}
1.2154 + * is negative, zero, or positive.
1.2155 + */
1.2156 + public int signum() {
1.2157 + return (intCompact != INFLATED)?
1.2158 + Long.signum(intCompact):
1.2159 + intVal.signum();
1.2160 + }
1.2161 +
1.2162 + /**
1.2163 + * Returns the <i>scale</i> of this {@code BigDecimal}. If zero
1.2164 + * or positive, the scale is the number of digits to the right of
1.2165 + * the decimal point. If negative, the unscaled value of the
1.2166 + * number is multiplied by ten to the power of the negation of the
1.2167 + * scale. For example, a scale of {@code -3} means the unscaled
1.2168 + * value is multiplied by 1000.
1.2169 + *
1.2170 + * @return the scale of this {@code BigDecimal}.
1.2171 + */
1.2172 + public int scale() {
1.2173 + return scale;
1.2174 + }
1.2175 +
1.2176 + /**
1.2177 + * Returns the <i>precision</i> of this {@code BigDecimal}. (The
1.2178 + * precision is the number of digits in the unscaled value.)
1.2179 + *
1.2180 + * <p>The precision of a zero value is 1.
1.2181 + *
1.2182 + * @return the precision of this {@code BigDecimal}.
1.2183 + * @since 1.5
1.2184 + */
1.2185 + public int precision() {
1.2186 + int result = precision;
1.2187 + if (result == 0) {
1.2188 + long s = intCompact;
1.2189 + if (s != INFLATED)
1.2190 + result = longDigitLength(s);
1.2191 + else
1.2192 + result = bigDigitLength(inflate());
1.2193 + precision = result;
1.2194 + }
1.2195 + return result;
1.2196 + }
1.2197 +
1.2198 +
1.2199 + /**
1.2200 + * Returns a {@code BigInteger} whose value is the <i>unscaled
1.2201 + * value</i> of this {@code BigDecimal}. (Computes <tt>(this *
1.2202 + * 10<sup>this.scale()</sup>)</tt>.)
1.2203 + *
1.2204 + * @return the unscaled value of this {@code BigDecimal}.
1.2205 + * @since 1.2
1.2206 + */
1.2207 + public BigInteger unscaledValue() {
1.2208 + return this.inflate();
1.2209 + }
1.2210 +
1.2211 + // Rounding Modes
1.2212 +
1.2213 + /**
1.2214 + * Rounding mode to round away from zero. Always increments the
1.2215 + * digit prior to a nonzero discarded fraction. Note that this rounding
1.2216 + * mode never decreases the magnitude of the calculated value.
1.2217 + */
1.2218 + public final static int ROUND_UP = 0;
1.2219 +
1.2220 + /**
1.2221 + * Rounding mode to round towards zero. Never increments the digit
1.2222 + * prior to a discarded fraction (i.e., truncates). Note that this
1.2223 + * rounding mode never increases the magnitude of the calculated value.
1.2224 + */
1.2225 + public final static int ROUND_DOWN = 1;
1.2226 +
1.2227 + /**
1.2228 + * Rounding mode to round towards positive infinity. If the
1.2229 + * {@code BigDecimal} is positive, behaves as for
1.2230 + * {@code ROUND_UP}; if negative, behaves as for
1.2231 + * {@code ROUND_DOWN}. Note that this rounding mode never
1.2232 + * decreases the calculated value.
1.2233 + */
1.2234 + public final static int ROUND_CEILING = 2;
1.2235 +
1.2236 + /**
1.2237 + * Rounding mode to round towards negative infinity. If the
1.2238 + * {@code BigDecimal} is positive, behave as for
1.2239 + * {@code ROUND_DOWN}; if negative, behave as for
1.2240 + * {@code ROUND_UP}. Note that this rounding mode never
1.2241 + * increases the calculated value.
1.2242 + */
1.2243 + public final static int ROUND_FLOOR = 3;
1.2244 +
1.2245 + /**
1.2246 + * Rounding mode to round towards {@literal "nearest neighbor"}
1.2247 + * unless both neighbors are equidistant, in which case round up.
1.2248 + * Behaves as for {@code ROUND_UP} if the discarded fraction is
1.2249 + * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note
1.2250 + * that this is the rounding mode that most of us were taught in
1.2251 + * grade school.
1.2252 + */
1.2253 + public final static int ROUND_HALF_UP = 4;
1.2254 +
1.2255 + /**
1.2256 + * Rounding mode to round towards {@literal "nearest neighbor"}
1.2257 + * unless both neighbors are equidistant, in which case round
1.2258 + * down. Behaves as for {@code ROUND_UP} if the discarded
1.2259 + * fraction is {@literal >} 0.5; otherwise, behaves as for
1.2260 + * {@code ROUND_DOWN}.
1.2261 + */
1.2262 + public final static int ROUND_HALF_DOWN = 5;
1.2263 +
1.2264 + /**
1.2265 + * Rounding mode to round towards the {@literal "nearest neighbor"}
1.2266 + * unless both neighbors are equidistant, in which case, round
1.2267 + * towards the even neighbor. Behaves as for
1.2268 + * {@code ROUND_HALF_UP} if the digit to the left of the
1.2269 + * discarded fraction is odd; behaves as for
1.2270 + * {@code ROUND_HALF_DOWN} if it's even. Note that this is the
1.2271 + * rounding mode that minimizes cumulative error when applied
1.2272 + * repeatedly over a sequence of calculations.
1.2273 + */
1.2274 + public final static int ROUND_HALF_EVEN = 6;
1.2275 +
1.2276 + /**
1.2277 + * Rounding mode to assert that the requested operation has an exact
1.2278 + * result, hence no rounding is necessary. If this rounding mode is
1.2279 + * specified on an operation that yields an inexact result, an
1.2280 + * {@code ArithmeticException} is thrown.
1.2281 + */
1.2282 + public final static int ROUND_UNNECESSARY = 7;
1.2283 +
1.2284 +
1.2285 + // Scaling/Rounding Operations
1.2286 +
1.2287 + /**
1.2288 + * Returns a {@code BigDecimal} rounded according to the
1.2289 + * {@code MathContext} settings. If the precision setting is 0 then
1.2290 + * no rounding takes place.
1.2291 + *
1.2292 + * <p>The effect of this method is identical to that of the
1.2293 + * {@link #plus(MathContext)} method.
1.2294 + *
1.2295 + * @param mc the context to use.
1.2296 + * @return a {@code BigDecimal} rounded according to the
1.2297 + * {@code MathContext} settings.
1.2298 + * @throws ArithmeticException if the rounding mode is
1.2299 + * {@code UNNECESSARY} and the
1.2300 + * {@code BigDecimal} operation would require rounding.
1.2301 + * @see #plus(MathContext)
1.2302 + * @since 1.5
1.2303 + */
1.2304 + public BigDecimal round(MathContext mc) {
1.2305 + return plus(mc);
1.2306 + }
1.2307 +
1.2308 + /**
1.2309 + * Returns a {@code BigDecimal} whose scale is the specified
1.2310 + * value, and whose unscaled value is determined by multiplying or
1.2311 + * dividing this {@code BigDecimal}'s unscaled value by the
1.2312 + * appropriate power of ten to maintain its overall value. If the
1.2313 + * scale is reduced by the operation, the unscaled value must be
1.2314 + * divided (rather than multiplied), and the value may be changed;
1.2315 + * in this case, the specified rounding mode is applied to the
1.2316 + * division.
1.2317 + *
1.2318 + * <p>Note that since BigDecimal objects are immutable, calls of
1.2319 + * this method do <i>not</i> result in the original object being
1.2320 + * modified, contrary to the usual convention of having methods
1.2321 + * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
1.2322 + * Instead, {@code setScale} returns an object with the proper
1.2323 + * scale; the returned object may or may not be newly allocated.
1.2324 + *
1.2325 + * @param newScale scale of the {@code BigDecimal} value to be returned.
1.2326 + * @param roundingMode The rounding mode to apply.
1.2327 + * @return a {@code BigDecimal} whose scale is the specified value,
1.2328 + * and whose unscaled value is determined by multiplying or
1.2329 + * dividing this {@code BigDecimal}'s unscaled value by the
1.2330 + * appropriate power of ten to maintain its overall value.
1.2331 + * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
1.2332 + * and the specified scaling operation would require
1.2333 + * rounding.
1.2334 + * @see RoundingMode
1.2335 + * @since 1.5
1.2336 + */
1.2337 + public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
1.2338 + return setScale(newScale, roundingMode.oldMode);
1.2339 + }
1.2340 +
1.2341 + /**
1.2342 + * Returns a {@code BigDecimal} whose scale is the specified
1.2343 + * value, and whose unscaled value is determined by multiplying or
1.2344 + * dividing this {@code BigDecimal}'s unscaled value by the
1.2345 + * appropriate power of ten to maintain its overall value. If the
1.2346 + * scale is reduced by the operation, the unscaled value must be
1.2347 + * divided (rather than multiplied), and the value may be changed;
1.2348 + * in this case, the specified rounding mode is applied to the
1.2349 + * division.
1.2350 + *
1.2351 + * <p>Note that since BigDecimal objects are immutable, calls of
1.2352 + * this method do <i>not</i> result in the original object being
1.2353 + * modified, contrary to the usual convention of having methods
1.2354 + * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
1.2355 + * Instead, {@code setScale} returns an object with the proper
1.2356 + * scale; the returned object may or may not be newly allocated.
1.2357 + *
1.2358 + * <p>The new {@link #setScale(int, RoundingMode)} method should
1.2359 + * be used in preference to this legacy method.
1.2360 + *
1.2361 + * @param newScale scale of the {@code BigDecimal} value to be returned.
1.2362 + * @param roundingMode The rounding mode to apply.
1.2363 + * @return a {@code BigDecimal} whose scale is the specified value,
1.2364 + * and whose unscaled value is determined by multiplying or
1.2365 + * dividing this {@code BigDecimal}'s unscaled value by the
1.2366 + * appropriate power of ten to maintain its overall value.
1.2367 + * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
1.2368 + * and the specified scaling operation would require
1.2369 + * rounding.
1.2370 + * @throws IllegalArgumentException if {@code roundingMode} does not
1.2371 + * represent a valid rounding mode.
1.2372 + * @see #ROUND_UP
1.2373 + * @see #ROUND_DOWN
1.2374 + * @see #ROUND_CEILING
1.2375 + * @see #ROUND_FLOOR
1.2376 + * @see #ROUND_HALF_UP
1.2377 + * @see #ROUND_HALF_DOWN
1.2378 + * @see #ROUND_HALF_EVEN
1.2379 + * @see #ROUND_UNNECESSARY
1.2380 + */
1.2381 + public BigDecimal setScale(int newScale, int roundingMode) {
1.2382 + if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1.2383 + throw new IllegalArgumentException("Invalid rounding mode");
1.2384 +
1.2385 + int oldScale = this.scale;
1.2386 + if (newScale == oldScale) // easy case
1.2387 + return this;
1.2388 + if (this.signum() == 0) // zero can have any scale
1.2389 + return BigDecimal.valueOf(0, newScale);
1.2390 +
1.2391 + long rs = this.intCompact;
1.2392 + if (newScale > oldScale) {
1.2393 + int raise = checkScale((long)newScale - oldScale);
1.2394 + BigInteger rb = null;
1.2395 + if (rs == INFLATED ||
1.2396 + (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
1.2397 + rb = bigMultiplyPowerTen(raise);
1.2398 + return new BigDecimal(rb, rs, newScale,
1.2399 + (precision > 0) ? precision + raise : 0);
1.2400 + } else {
1.2401 + // newScale < oldScale -- drop some digits
1.2402 + // Can't predict the precision due to the effect of rounding.
1.2403 + int drop = checkScale((long)oldScale - newScale);
1.2404 + if (drop < LONG_TEN_POWERS_TABLE.length)
1.2405 + return divideAndRound(rs, this.intVal,
1.2406 + LONG_TEN_POWERS_TABLE[drop], null,
1.2407 + newScale, roundingMode, newScale);
1.2408 + else
1.2409 + return divideAndRound(rs, this.intVal,
1.2410 + INFLATED, bigTenToThe(drop),
1.2411 + newScale, roundingMode, newScale);
1.2412 + }
1.2413 + }
1.2414 +
1.2415 + /**
1.2416 + * Returns a {@code BigDecimal} whose scale is the specified
1.2417 + * value, and whose value is numerically equal to this
1.2418 + * {@code BigDecimal}'s. Throws an {@code ArithmeticException}
1.2419 + * if this is not possible.
1.2420 + *
1.2421 + * <p>This call is typically used to increase the scale, in which
1.2422 + * case it is guaranteed that there exists a {@code BigDecimal}
1.2423 + * of the specified scale and the correct value. The call can
1.2424 + * also be used to reduce the scale if the caller knows that the
1.2425 + * {@code BigDecimal} has sufficiently many zeros at the end of
1.2426 + * its fractional part (i.e., factors of ten in its integer value)
1.2427 + * to allow for the rescaling without changing its value.
1.2428 + *
1.2429 + * <p>This method returns the same result as the two-argument
1.2430 + * versions of {@code setScale}, but saves the caller the trouble
1.2431 + * of specifying a rounding mode in cases where it is irrelevant.
1.2432 + *
1.2433 + * <p>Note that since {@code BigDecimal} objects are immutable,
1.2434 + * calls of this method do <i>not</i> result in the original
1.2435 + * object being modified, contrary to the usual convention of
1.2436 + * having methods named <tt>set<i>X</i></tt> mutate field
1.2437 + * <i>{@code X}</i>. Instead, {@code setScale} returns an
1.2438 + * object with the proper scale; the returned object may or may
1.2439 + * not be newly allocated.
1.2440 + *
1.2441 + * @param newScale scale of the {@code BigDecimal} value to be returned.
1.2442 + * @return a {@code BigDecimal} whose scale is the specified value, and
1.2443 + * whose unscaled value is determined by multiplying or dividing
1.2444 + * this {@code BigDecimal}'s unscaled value by the appropriate
1.2445 + * power of ten to maintain its overall value.
1.2446 + * @throws ArithmeticException if the specified scaling operation would
1.2447 + * require rounding.
1.2448 + * @see #setScale(int, int)
1.2449 + * @see #setScale(int, RoundingMode)
1.2450 + */
1.2451 + public BigDecimal setScale(int newScale) {
1.2452 + return setScale(newScale, ROUND_UNNECESSARY);
1.2453 + }
1.2454 +
1.2455 + // Decimal Point Motion Operations
1.2456 +
1.2457 + /**
1.2458 + * Returns a {@code BigDecimal} which is equivalent to this one
1.2459 + * with the decimal point moved {@code n} places to the left. If
1.2460 + * {@code n} is non-negative, the call merely adds {@code n} to
1.2461 + * the scale. If {@code n} is negative, the call is equivalent
1.2462 + * to {@code movePointRight(-n)}. The {@code BigDecimal}
1.2463 + * returned by this call has value <tt>(this ×
1.2464 + * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
1.2465 + * 0)}.
1.2466 + *
1.2467 + * @param n number of places to move the decimal point to the left.
1.2468 + * @return a {@code BigDecimal} which is equivalent to this one with the
1.2469 + * decimal point moved {@code n} places to the left.
1.2470 + * @throws ArithmeticException if scale overflows.
1.2471 + */
1.2472 + public BigDecimal movePointLeft(int n) {
1.2473 + // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
1.2474 + int newScale = checkScale((long)scale + n);
1.2475 + BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
1.2476 + return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
1.2477 + }
1.2478 +
1.2479 + /**
1.2480 + * Returns a {@code BigDecimal} which is equivalent to this one
1.2481 + * with the decimal point moved {@code n} places to the right.
1.2482 + * If {@code n} is non-negative, the call merely subtracts
1.2483 + * {@code n} from the scale. If {@code n} is negative, the call
1.2484 + * is equivalent to {@code movePointLeft(-n)}. The
1.2485 + * {@code BigDecimal} returned by this call has value <tt>(this
1.2486 + * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
1.2487 + * 0)}.
1.2488 + *
1.2489 + * @param n number of places to move the decimal point to the right.
1.2490 + * @return a {@code BigDecimal} which is equivalent to this one
1.2491 + * with the decimal point moved {@code n} places to the right.
1.2492 + * @throws ArithmeticException if scale overflows.
1.2493 + */
1.2494 + public BigDecimal movePointRight(int n) {
1.2495 + // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
1.2496 + int newScale = checkScale((long)scale - n);
1.2497 + BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
1.2498 + return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
1.2499 + }
1.2500 +
1.2501 + /**
1.2502 + * Returns a BigDecimal whose numerical value is equal to
1.2503 + * ({@code this} * 10<sup>n</sup>). The scale of
1.2504 + * the result is {@code (this.scale() - n)}.
1.2505 + *
1.2506 + * @throws ArithmeticException if the scale would be
1.2507 + * outside the range of a 32-bit integer.
1.2508 + *
1.2509 + * @since 1.5
1.2510 + */
1.2511 + public BigDecimal scaleByPowerOfTen(int n) {
1.2512 + return new BigDecimal(intVal, intCompact,
1.2513 + checkScale((long)scale - n), precision);
1.2514 + }
1.2515 +
1.2516 + /**
1.2517 + * Returns a {@code BigDecimal} which is numerically equal to
1.2518 + * this one but with any trailing zeros removed from the
1.2519 + * representation. For example, stripping the trailing zeros from
1.2520 + * the {@code BigDecimal} value {@code 600.0}, which has
1.2521 + * [{@code BigInteger}, {@code scale}] components equals to
1.2522 + * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
1.2523 + * {@code scale}] components equals to [6, -2]
1.2524 + *
1.2525 + * @return a numerically equal {@code BigDecimal} with any
1.2526 + * trailing zeros removed.
1.2527 + * @since 1.5
1.2528 + */
1.2529 + public BigDecimal stripTrailingZeros() {
1.2530 + this.inflate();
1.2531 + BigDecimal result = new BigDecimal(intVal, scale);
1.2532 + result.stripZerosToMatchScale(Long.MIN_VALUE);
1.2533 + return result;
1.2534 + }
1.2535 +
1.2536 + // Comparison Operations
1.2537 +
1.2538 + /**
1.2539 + * Compares this {@code BigDecimal} with the specified
1.2540 + * {@code BigDecimal}. Two {@code BigDecimal} objects that are
1.2541 + * equal in value but have a different scale (like 2.0 and 2.00)
1.2542 + * are considered equal by this method. This method is provided
1.2543 + * in preference to individual methods for each of the six boolean
1.2544 + * comparison operators ({@literal <}, ==,
1.2545 + * {@literal >}, {@literal >=}, !=, {@literal <=}). The
1.2546 + * suggested idiom for performing these comparisons is:
1.2547 + * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
1.2548 + * <<i>op</i>> is one of the six comparison operators.
1.2549 + *
1.2550 + * @param val {@code BigDecimal} to which this {@code BigDecimal} is
1.2551 + * to be compared.
1.2552 + * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
1.2553 + * less than, equal to, or greater than {@code val}.
1.2554 + */
1.2555 + public int compareTo(BigDecimal val) {
1.2556 + // Quick path for equal scale and non-inflated case.
1.2557 + if (scale == val.scale) {
1.2558 + long xs = intCompact;
1.2559 + long ys = val.intCompact;
1.2560 + if (xs != INFLATED && ys != INFLATED)
1.2561 + return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
1.2562 + }
1.2563 + int xsign = this.signum();
1.2564 + int ysign = val.signum();
1.2565 + if (xsign != ysign)
1.2566 + return (xsign > ysign) ? 1 : -1;
1.2567 + if (xsign == 0)
1.2568 + return 0;
1.2569 + int cmp = compareMagnitude(val);
1.2570 + return (xsign > 0) ? cmp : -cmp;
1.2571 + }
1.2572 +
1.2573 + /**
1.2574 + * Version of compareTo that ignores sign.
1.2575 + */
1.2576 + private int compareMagnitude(BigDecimal val) {
1.2577 + // Match scales, avoid unnecessary inflation
1.2578 + long ys = val.intCompact;
1.2579 + long xs = this.intCompact;
1.2580 + if (xs == 0)
1.2581 + return (ys == 0) ? 0 : -1;
1.2582 + if (ys == 0)
1.2583 + return 1;
1.2584 +
1.2585 + int sdiff = this.scale - val.scale;
1.2586 + if (sdiff != 0) {
1.2587 + // Avoid matching scales if the (adjusted) exponents differ
1.2588 + int xae = this.precision() - this.scale; // [-1]
1.2589 + int yae = val.precision() - val.scale; // [-1]
1.2590 + if (xae < yae)
1.2591 + return -1;
1.2592 + if (xae > yae)
1.2593 + return 1;
1.2594 + BigInteger rb = null;
1.2595 + if (sdiff < 0) {
1.2596 + if ( (xs == INFLATED ||
1.2597 + (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
1.2598 + ys == INFLATED) {
1.2599 + rb = bigMultiplyPowerTen(-sdiff);
1.2600 + return rb.compareMagnitude(val.intVal);
1.2601 + }
1.2602 + } else { // sdiff > 0
1.2603 + if ( (ys == INFLATED ||
1.2604 + (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
1.2605 + xs == INFLATED) {
1.2606 + rb = val.bigMultiplyPowerTen(sdiff);
1.2607 + return this.intVal.compareMagnitude(rb);
1.2608 + }
1.2609 + }
1.2610 + }
1.2611 + if (xs != INFLATED)
1.2612 + return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
1.2613 + else if (ys != INFLATED)
1.2614 + return 1;
1.2615 + else
1.2616 + return this.intVal.compareMagnitude(val.intVal);
1.2617 + }
1.2618 +
1.2619 + /**
1.2620 + * Compares this {@code BigDecimal} with the specified
1.2621 + * {@code Object} for equality. Unlike {@link
1.2622 + * #compareTo(BigDecimal) compareTo}, this method considers two
1.2623 + * {@code BigDecimal} objects equal only if they are equal in
1.2624 + * value and scale (thus 2.0 is not equal to 2.00 when compared by
1.2625 + * this method).
1.2626 + *
1.2627 + * @param x {@code Object} to which this {@code BigDecimal} is
1.2628 + * to be compared.
1.2629 + * @return {@code true} if and only if the specified {@code Object} is a
1.2630 + * {@code BigDecimal} whose value and scale are equal to this
1.2631 + * {@code BigDecimal}'s.
1.2632 + * @see #compareTo(java.math.BigDecimal)
1.2633 + * @see #hashCode
1.2634 + */
1.2635 + @Override
1.2636 + public boolean equals(Object x) {
1.2637 + if (!(x instanceof BigDecimal))
1.2638 + return false;
1.2639 + BigDecimal xDec = (BigDecimal) x;
1.2640 + if (x == this)
1.2641 + return true;
1.2642 + if (scale != xDec.scale)
1.2643 + return false;
1.2644 + long s = this.intCompact;
1.2645 + long xs = xDec.intCompact;
1.2646 + if (s != INFLATED) {
1.2647 + if (xs == INFLATED)
1.2648 + xs = compactValFor(xDec.intVal);
1.2649 + return xs == s;
1.2650 + } else if (xs != INFLATED)
1.2651 + return xs == compactValFor(this.intVal);
1.2652 +
1.2653 + return this.inflate().equals(xDec.inflate());
1.2654 + }
1.2655 +
1.2656 + /**
1.2657 + * Returns the minimum of this {@code BigDecimal} and
1.2658 + * {@code val}.
1.2659 + *
1.2660 + * @param val value with which the minimum is to be computed.
1.2661 + * @return the {@code BigDecimal} whose value is the lesser of this
1.2662 + * {@code BigDecimal} and {@code val}. If they are equal,
1.2663 + * as defined by the {@link #compareTo(BigDecimal) compareTo}
1.2664 + * method, {@code this} is returned.
1.2665 + * @see #compareTo(java.math.BigDecimal)
1.2666 + */
1.2667 + public BigDecimal min(BigDecimal val) {
1.2668 + return (compareTo(val) <= 0 ? this : val);
1.2669 + }
1.2670 +
1.2671 + /**
1.2672 + * Returns the maximum of this {@code BigDecimal} and {@code val}.
1.2673 + *
1.2674 + * @param val value with which the maximum is to be computed.
1.2675 + * @return the {@code BigDecimal} whose value is the greater of this
1.2676 + * {@code BigDecimal} and {@code val}. If they are equal,
1.2677 + * as defined by the {@link #compareTo(BigDecimal) compareTo}
1.2678 + * method, {@code this} is returned.
1.2679 + * @see #compareTo(java.math.BigDecimal)
1.2680 + */
1.2681 + public BigDecimal max(BigDecimal val) {
1.2682 + return (compareTo(val) >= 0 ? this : val);
1.2683 + }
1.2684 +
1.2685 + // Hash Function
1.2686 +
1.2687 + /**
1.2688 + * Returns the hash code for this {@code BigDecimal}. Note that
1.2689 + * two {@code BigDecimal} objects that are numerically equal but
1.2690 + * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
1.2691 + * have the same hash code.
1.2692 + *
1.2693 + * @return hash code for this {@code BigDecimal}.
1.2694 + * @see #equals(Object)
1.2695 + */
1.2696 + @Override
1.2697 + public int hashCode() {
1.2698 + if (intCompact != INFLATED) {
1.2699 + long val2 = (intCompact < 0)? -intCompact : intCompact;
1.2700 + int temp = (int)( ((int)(val2 >>> 32)) * 31 +
1.2701 + (val2 & LONG_MASK));
1.2702 + return 31*((intCompact < 0) ?-temp:temp) + scale;
1.2703 + } else
1.2704 + return 31*intVal.hashCode() + scale;
1.2705 + }
1.2706 +
1.2707 + // Format Converters
1.2708 +
1.2709 + /**
1.2710 + * Returns the string representation of this {@code BigDecimal},
1.2711 + * using scientific notation if an exponent is needed.
1.2712 + *
1.2713 + * <p>A standard canonical string form of the {@code BigDecimal}
1.2714 + * is created as though by the following steps: first, the
1.2715 + * absolute value of the unscaled value of the {@code BigDecimal}
1.2716 + * is converted to a string in base ten using the characters
1.2717 + * {@code '0'} through {@code '9'} with no leading zeros (except
1.2718 + * if its value is zero, in which case a single {@code '0'}
1.2719 + * character is used).
1.2720 + *
1.2721 + * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
1.2722 + * negated scale, plus the number of characters in the converted
1.2723 + * unscaled value, less one. That is,
1.2724 + * {@code -scale+(ulength-1)}, where {@code ulength} is the
1.2725 + * length of the absolute value of the unscaled value in decimal
1.2726 + * digits (its <i>precision</i>).
1.2727 + *
1.2728 + * <p>If the scale is greater than or equal to zero and the
1.2729 + * adjusted exponent is greater than or equal to {@code -6}, the
1.2730 + * number will be converted to a character form without using
1.2731 + * exponential notation. In this case, if the scale is zero then
1.2732 + * no decimal point is added and if the scale is positive a
1.2733 + * decimal point will be inserted with the scale specifying the
1.2734 + * number of characters to the right of the decimal point.
1.2735 + * {@code '0'} characters are added to the left of the converted
1.2736 + * unscaled value as necessary. If no character precedes the
1.2737 + * decimal point after this insertion then a conventional
1.2738 + * {@code '0'} character is prefixed.
1.2739 + *
1.2740 + * <p>Otherwise (that is, if the scale is negative, or the
1.2741 + * adjusted exponent is less than {@code -6}), the number will be
1.2742 + * converted to a character form using exponential notation. In
1.2743 + * this case, if the converted {@code BigInteger} has more than
1.2744 + * one digit a decimal point is inserted after the first digit.
1.2745 + * An exponent in character form is then suffixed to the converted
1.2746 + * unscaled value (perhaps with inserted decimal point); this
1.2747 + * comprises the letter {@code 'E'} followed immediately by the
1.2748 + * adjusted exponent converted to a character form. The latter is
1.2749 + * in base ten, using the characters {@code '0'} through
1.2750 + * {@code '9'} with no leading zeros, and is always prefixed by a
1.2751 + * sign character {@code '-'} (<tt>'\u002D'</tt>) if the
1.2752 + * adjusted exponent is negative, {@code '+'}
1.2753 + * (<tt>'\u002B'</tt>) otherwise).
1.2754 + *
1.2755 + * <p>Finally, the entire string is prefixed by a minus sign
1.2756 + * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled
1.2757 + * value is less than zero. No sign character is prefixed if the
1.2758 + * unscaled value is zero or positive.
1.2759 + *
1.2760 + * <p><b>Examples:</b>
1.2761 + * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
1.2762 + * on the left, the resulting string is shown on the right.
1.2763 + * <pre>
1.2764 + * [123,0] "123"
1.2765 + * [-123,0] "-123"
1.2766 + * [123,-1] "1.23E+3"
1.2767 + * [123,-3] "1.23E+5"
1.2768 + * [123,1] "12.3"
1.2769 + * [123,5] "0.00123"
1.2770 + * [123,10] "1.23E-8"
1.2771 + * [-123,12] "-1.23E-10"
1.2772 + * </pre>
1.2773 + *
1.2774 + * <b>Notes:</b>
1.2775 + * <ol>
1.2776 + *
1.2777 + * <li>There is a one-to-one mapping between the distinguishable
1.2778 + * {@code BigDecimal} values and the result of this conversion.
1.2779 + * That is, every distinguishable {@code BigDecimal} value
1.2780 + * (unscaled value and scale) has a unique string representation
1.2781 + * as a result of using {@code toString}. If that string
1.2782 + * representation is converted back to a {@code BigDecimal} using
1.2783 + * the {@link #BigDecimal(String)} constructor, then the original
1.2784 + * value will be recovered.
1.2785 + *
1.2786 + * <li>The string produced for a given number is always the same;
1.2787 + * it is not affected by locale. This means that it can be used
1.2788 + * as a canonical string representation for exchanging decimal
1.2789 + * data, or as a key for a Hashtable, etc. Locale-sensitive
1.2790 + * number formatting and parsing is handled by the {@link
1.2791 + * java.text.NumberFormat} class and its subclasses.
1.2792 + *
1.2793 + * <li>The {@link #toEngineeringString} method may be used for
1.2794 + * presenting numbers with exponents in engineering notation, and the
1.2795 + * {@link #setScale(int,RoundingMode) setScale} method may be used for
1.2796 + * rounding a {@code BigDecimal} so it has a known number of digits after
1.2797 + * the decimal point.
1.2798 + *
1.2799 + * <li>The digit-to-character mapping provided by
1.2800 + * {@code Character.forDigit} is used.
1.2801 + *
1.2802 + * </ol>
1.2803 + *
1.2804 + * @return string representation of this {@code BigDecimal}.
1.2805 + * @see Character#forDigit
1.2806 + * @see #BigDecimal(java.lang.String)
1.2807 + */
1.2808 + @Override
1.2809 + public String toString() {
1.2810 + String sc = stringCache;
1.2811 + if (sc == null)
1.2812 + stringCache = sc = layoutChars(true);
1.2813 + return sc;
1.2814 + }
1.2815 +
1.2816 + /**
1.2817 + * Returns a string representation of this {@code BigDecimal},
1.2818 + * using engineering notation if an exponent is needed.
1.2819 + *
1.2820 + * <p>Returns a string that represents the {@code BigDecimal} as
1.2821 + * described in the {@link #toString()} method, except that if
1.2822 + * exponential notation is used, the power of ten is adjusted to
1.2823 + * be a multiple of three (engineering notation) such that the
1.2824 + * integer part of nonzero values will be in the range 1 through
1.2825 + * 999. If exponential notation is used for zero values, a
1.2826 + * decimal point and one or two fractional zero digits are used so
1.2827 + * that the scale of the zero value is preserved. Note that
1.2828 + * unlike the output of {@link #toString()}, the output of this
1.2829 + * method is <em>not</em> guaranteed to recover the same [integer,
1.2830 + * scale] pair of this {@code BigDecimal} if the output string is
1.2831 + * converting back to a {@code BigDecimal} using the {@linkplain
1.2832 + * #BigDecimal(String) string constructor}. The result of this method meets
1.2833 + * the weaker constraint of always producing a numerically equal
1.2834 + * result from applying the string constructor to the method's output.
1.2835 + *
1.2836 + * @return string representation of this {@code BigDecimal}, using
1.2837 + * engineering notation if an exponent is needed.
1.2838 + * @since 1.5
1.2839 + */
1.2840 + public String toEngineeringString() {
1.2841 + return layoutChars(false);
1.2842 + }
1.2843 +
1.2844 + /**
1.2845 + * Returns a string representation of this {@code BigDecimal}
1.2846 + * without an exponent field. For values with a positive scale,
1.2847 + * the number of digits to the right of the decimal point is used
1.2848 + * to indicate scale. For values with a zero or negative scale,
1.2849 + * the resulting string is generated as if the value were
1.2850 + * converted to a numerically equal value with zero scale and as
1.2851 + * if all the trailing zeros of the zero scale value were present
1.2852 + * in the result.
1.2853 + *
1.2854 + * The entire string is prefixed by a minus sign character '-'
1.2855 + * (<tt>'\u002D'</tt>) if the unscaled value is less than
1.2856 + * zero. No sign character is prefixed if the unscaled value is
1.2857 + * zero or positive.
1.2858 + *
1.2859 + * Note that if the result of this method is passed to the
1.2860 + * {@linkplain #BigDecimal(String) string constructor}, only the
1.2861 + * numerical value of this {@code BigDecimal} will necessarily be
1.2862 + * recovered; the representation of the new {@code BigDecimal}
1.2863 + * may have a different scale. In particular, if this
1.2864 + * {@code BigDecimal} has a negative scale, the string resulting
1.2865 + * from this method will have a scale of zero when processed by
1.2866 + * the string constructor.
1.2867 + *
1.2868 + * (This method behaves analogously to the {@code toString}
1.2869 + * method in 1.4 and earlier releases.)
1.2870 + *
1.2871 + * @return a string representation of this {@code BigDecimal}
1.2872 + * without an exponent field.
1.2873 + * @since 1.5
1.2874 + * @see #toString()
1.2875 + * @see #toEngineeringString()
1.2876 + */
1.2877 + public String toPlainString() {
1.2878 + BigDecimal bd = this;
1.2879 + if (bd.scale < 0)
1.2880 + bd = bd.setScale(0);
1.2881 + bd.inflate();
1.2882 + if (bd.scale == 0) // No decimal point
1.2883 + return bd.intVal.toString();
1.2884 + return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
1.2885 + }
1.2886 +
1.2887 + /* Returns a digit.digit string */
1.2888 + private String getValueString(int signum, String intString, int scale) {
1.2889 + /* Insert decimal point */
1.2890 + StringBuilder buf;
1.2891 + int insertionPoint = intString.length() - scale;
1.2892 + if (insertionPoint == 0) { /* Point goes right before intVal */
1.2893 + return (signum<0 ? "-0." : "0.") + intString;
1.2894 + } else if (insertionPoint > 0) { /* Point goes inside intVal */
1.2895 + buf = new StringBuilder(intString);
1.2896 + buf.insert(insertionPoint, '.');
1.2897 + if (signum < 0)
1.2898 + buf.insert(0, '-');
1.2899 + } else { /* We must insert zeros between point and intVal */
1.2900 + buf = new StringBuilder(3-insertionPoint + intString.length());
1.2901 + buf.append(signum<0 ? "-0." : "0.");
1.2902 + for (int i=0; i<-insertionPoint; i++)
1.2903 + buf.append('0');
1.2904 + buf.append(intString);
1.2905 + }
1.2906 + return buf.toString();
1.2907 + }
1.2908 +
1.2909 + /**
1.2910 + * Converts this {@code BigDecimal} to a {@code BigInteger}.
1.2911 + * This conversion is analogous to the
1.2912 + * <i>narrowing primitive conversion</i> from {@code double} to
1.2913 + * {@code long} as defined in section 5.1.3 of
1.2914 + * <cite>The Java™ Language Specification</cite>:
1.2915 + * any fractional part of this
1.2916 + * {@code BigDecimal} will be discarded. Note that this
1.2917 + * conversion can lose information about the precision of the
1.2918 + * {@code BigDecimal} value.
1.2919 + * <p>
1.2920 + * To have an exception thrown if the conversion is inexact (in
1.2921 + * other words if a nonzero fractional part is discarded), use the
1.2922 + * {@link #toBigIntegerExact()} method.
1.2923 + *
1.2924 + * @return this {@code BigDecimal} converted to a {@code BigInteger}.
1.2925 + */
1.2926 + public BigInteger toBigInteger() {
1.2927 + // force to an integer, quietly
1.2928 + return this.setScale(0, ROUND_DOWN).inflate();
1.2929 + }
1.2930 +
1.2931 + /**
1.2932 + * Converts this {@code BigDecimal} to a {@code BigInteger},
1.2933 + * checking for lost information. An exception is thrown if this
1.2934 + * {@code BigDecimal} has a nonzero fractional part.
1.2935 + *
1.2936 + * @return this {@code BigDecimal} converted to a {@code BigInteger}.
1.2937 + * @throws ArithmeticException if {@code this} has a nonzero
1.2938 + * fractional part.
1.2939 + * @since 1.5
1.2940 + */
1.2941 + public BigInteger toBigIntegerExact() {
1.2942 + // round to an integer, with Exception if decimal part non-0
1.2943 + return this.setScale(0, ROUND_UNNECESSARY).inflate();
1.2944 + }
1.2945 +
1.2946 + /**
1.2947 + * Converts this {@code BigDecimal} to a {@code long}.
1.2948 + * This conversion is analogous to the
1.2949 + * <i>narrowing primitive conversion</i> from {@code double} to
1.2950 + * {@code short} as defined in section 5.1.3 of
1.2951 + * <cite>The Java™ Language Specification</cite>:
1.2952 + * any fractional part of this
1.2953 + * {@code BigDecimal} will be discarded, and if the resulting
1.2954 + * "{@code BigInteger}" is too big to fit in a
1.2955 + * {@code long}, only the low-order 64 bits are returned.
1.2956 + * Note that this conversion can lose information about the
1.2957 + * overall magnitude and precision of this {@code BigDecimal} value as well
1.2958 + * as return a result with the opposite sign.
1.2959 + *
1.2960 + * @return this {@code BigDecimal} converted to a {@code long}.
1.2961 + */
1.2962 + public long longValue(){
1.2963 + return (intCompact != INFLATED && scale == 0) ?
1.2964 + intCompact:
1.2965 + toBigInteger().longValue();
1.2966 + }
1.2967 +
1.2968 + /**
1.2969 + * Converts this {@code BigDecimal} to a {@code long}, checking
1.2970 + * for lost information. If this {@code BigDecimal} has a
1.2971 + * nonzero fractional part or is out of the possible range for a
1.2972 + * {@code long} result then an {@code ArithmeticException} is
1.2973 + * thrown.
1.2974 + *
1.2975 + * @return this {@code BigDecimal} converted to a {@code long}.
1.2976 + * @throws ArithmeticException if {@code this} has a nonzero
1.2977 + * fractional part, or will not fit in a {@code long}.
1.2978 + * @since 1.5
1.2979 + */
1.2980 + public long longValueExact() {
1.2981 + if (intCompact != INFLATED && scale == 0)
1.2982 + return intCompact;
1.2983 + // If more than 19 digits in integer part it cannot possibly fit
1.2984 + if ((precision() - scale) > 19) // [OK for negative scale too]
1.2985 + throw new java.lang.ArithmeticException("Overflow");
1.2986 + // Fastpath zero and < 1.0 numbers (the latter can be very slow
1.2987 + // to round if very small)
1.2988 + if (this.signum() == 0)
1.2989 + return 0;
1.2990 + if ((this.precision() - this.scale) <= 0)
1.2991 + throw new ArithmeticException("Rounding necessary");
1.2992 + // round to an integer, with Exception if decimal part non-0
1.2993 + BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
1.2994 + if (num.precision() >= 19) // need to check carefully
1.2995 + LongOverflow.check(num);
1.2996 + return num.inflate().longValue();
1.2997 + }
1.2998 +
1.2999 + private static class LongOverflow {
1.3000 + /** BigInteger equal to Long.MIN_VALUE. */
1.3001 + private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
1.3002 +
1.3003 + /** BigInteger equal to Long.MAX_VALUE. */
1.3004 + private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
1.3005 +
1.3006 + public static void check(BigDecimal num) {
1.3007 + num.inflate();
1.3008 + if ((num.intVal.compareTo(LONGMIN) < 0) ||
1.3009 + (num.intVal.compareTo(LONGMAX) > 0))
1.3010 + throw new java.lang.ArithmeticException("Overflow");
1.3011 + }
1.3012 + }
1.3013 +
1.3014 + /**
1.3015 + * Converts this {@code BigDecimal} to an {@code int}.
1.3016 + * This conversion is analogous to the
1.3017 + * <i>narrowing primitive conversion</i> from {@code double} to
1.3018 + * {@code short} as defined in section 5.1.3 of
1.3019 + * <cite>The Java™ Language Specification</cite>:
1.3020 + * any fractional part of this
1.3021 + * {@code BigDecimal} will be discarded, and if the resulting
1.3022 + * "{@code BigInteger}" is too big to fit in an
1.3023 + * {@code int}, only the low-order 32 bits are returned.
1.3024 + * Note that this conversion can lose information about the
1.3025 + * overall magnitude and precision of this {@code BigDecimal}
1.3026 + * value as well as return a result with the opposite sign.
1.3027 + *
1.3028 + * @return this {@code BigDecimal} converted to an {@code int}.
1.3029 + */
1.3030 + public int intValue() {
1.3031 + return (intCompact != INFLATED && scale == 0) ?
1.3032 + (int)intCompact :
1.3033 + toBigInteger().intValue();
1.3034 + }
1.3035 +
1.3036 + /**
1.3037 + * Converts this {@code BigDecimal} to an {@code int}, checking
1.3038 + * for lost information. If this {@code BigDecimal} has a
1.3039 + * nonzero fractional part or is out of the possible range for an
1.3040 + * {@code int} result then an {@code ArithmeticException} is
1.3041 + * thrown.
1.3042 + *
1.3043 + * @return this {@code BigDecimal} converted to an {@code int}.
1.3044 + * @throws ArithmeticException if {@code this} has a nonzero
1.3045 + * fractional part, or will not fit in an {@code int}.
1.3046 + * @since 1.5
1.3047 + */
1.3048 + public int intValueExact() {
1.3049 + long num;
1.3050 + num = this.longValueExact(); // will check decimal part
1.3051 + if ((int)num != num)
1.3052 + throw new java.lang.ArithmeticException("Overflow");
1.3053 + return (int)num;
1.3054 + }
1.3055 +
1.3056 + /**
1.3057 + * Converts this {@code BigDecimal} to a {@code short}, checking
1.3058 + * for lost information. If this {@code BigDecimal} has a
1.3059 + * nonzero fractional part or is out of the possible range for a
1.3060 + * {@code short} result then an {@code ArithmeticException} is
1.3061 + * thrown.
1.3062 + *
1.3063 + * @return this {@code BigDecimal} converted to a {@code short}.
1.3064 + * @throws ArithmeticException if {@code this} has a nonzero
1.3065 + * fractional part, or will not fit in a {@code short}.
1.3066 + * @since 1.5
1.3067 + */
1.3068 + public short shortValueExact() {
1.3069 + long num;
1.3070 + num = this.longValueExact(); // will check decimal part
1.3071 + if ((short)num != num)
1.3072 + throw new java.lang.ArithmeticException("Overflow");
1.3073 + return (short)num;
1.3074 + }
1.3075 +
1.3076 + /**
1.3077 + * Converts this {@code BigDecimal} to a {@code byte}, checking
1.3078 + * for lost information. If this {@code BigDecimal} has a
1.3079 + * nonzero fractional part or is out of the possible range for a
1.3080 + * {@code byte} result then an {@code ArithmeticException} is
1.3081 + * thrown.
1.3082 + *
1.3083 + * @return this {@code BigDecimal} converted to a {@code byte}.
1.3084 + * @throws ArithmeticException if {@code this} has a nonzero
1.3085 + * fractional part, or will not fit in a {@code byte}.
1.3086 + * @since 1.5
1.3087 + */
1.3088 + public byte byteValueExact() {
1.3089 + long num;
1.3090 + num = this.longValueExact(); // will check decimal part
1.3091 + if ((byte)num != num)
1.3092 + throw new java.lang.ArithmeticException("Overflow");
1.3093 + return (byte)num;
1.3094 + }
1.3095 +
1.3096 + /**
1.3097 + * Converts this {@code BigDecimal} to a {@code float}.
1.3098 + * This conversion is similar to the
1.3099 + * <i>narrowing primitive conversion</i> from {@code double} to
1.3100 + * {@code float} as defined in section 5.1.3 of
1.3101 + * <cite>The Java™ Language Specification</cite>:
1.3102 + * if this {@code BigDecimal} has too great a
1.3103 + * magnitude to represent as a {@code float}, it will be
1.3104 + * converted to {@link Float#NEGATIVE_INFINITY} or {@link
1.3105 + * Float#POSITIVE_INFINITY} as appropriate. Note that even when
1.3106 + * the return value is finite, this conversion can lose
1.3107 + * information about the precision of the {@code BigDecimal}
1.3108 + * value.
1.3109 + *
1.3110 + * @return this {@code BigDecimal} converted to a {@code float}.
1.3111 + */
1.3112 + public float floatValue(){
1.3113 + if (scale == 0 && intCompact != INFLATED)
1.3114 + return (float)intCompact;
1.3115 + // Somewhat inefficient, but guaranteed to work.
1.3116 + return Float.parseFloat(this.toString());
1.3117 + }
1.3118 +
1.3119 + /**
1.3120 + * Converts this {@code BigDecimal} to a {@code double}.
1.3121 + * This conversion is similar to the
1.3122 + * <i>narrowing primitive conversion</i> from {@code double} to
1.3123 + * {@code float} as defined in section 5.1.3 of
1.3124 + * <cite>The Java™ Language Specification</cite>:
1.3125 + * if this {@code BigDecimal} has too great a
1.3126 + * magnitude represent as a {@code double}, it will be
1.3127 + * converted to {@link Double#NEGATIVE_INFINITY} or {@link
1.3128 + * Double#POSITIVE_INFINITY} as appropriate. Note that even when
1.3129 + * the return value is finite, this conversion can lose
1.3130 + * information about the precision of the {@code BigDecimal}
1.3131 + * value.
1.3132 + *
1.3133 + * @return this {@code BigDecimal} converted to a {@code double}.
1.3134 + */
1.3135 + public double doubleValue(){
1.3136 + if (scale == 0 && intCompact != INFLATED)
1.3137 + return (double)intCompact;
1.3138 + // Somewhat inefficient, but guaranteed to work.
1.3139 + return Double.parseDouble(this.toString());
1.3140 + }
1.3141 +
1.3142 + /**
1.3143 + * Returns the size of an ulp, a unit in the last place, of this
1.3144 + * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
1.3145 + * value is the positive distance between this value and the
1.3146 + * {@code BigDecimal} value next larger in magnitude with the
1.3147 + * same number of digits. An ulp of a zero value is numerically
1.3148 + * equal to 1 with the scale of {@code this}. The result is
1.3149 + * stored with the same scale as {@code this} so the result
1.3150 + * for zero and nonzero values is equal to {@code [1,
1.3151 + * this.scale()]}.
1.3152 + *
1.3153 + * @return the size of an ulp of {@code this}
1.3154 + * @since 1.5
1.3155 + */
1.3156 + public BigDecimal ulp() {
1.3157 + return BigDecimal.valueOf(1, this.scale());
1.3158 + }
1.3159 +
1.3160 +
1.3161 + // Private class to build a string representation for BigDecimal object.
1.3162 + // "StringBuilderHelper" is constructed as a thread local variable so it is
1.3163 + // thread safe. The StringBuilder field acts as a buffer to hold the temporary
1.3164 + // representation of BigDecimal. The cmpCharArray holds all the characters for
1.3165 + // the compact representation of BigDecimal (except for '-' sign' if it is
1.3166 + // negative) if its intCompact field is not INFLATED. It is shared by all
1.3167 + // calls to toString() and its variants in that particular thread.
1.3168 + static class StringBuilderHelper {
1.3169 + final StringBuilder sb; // Placeholder for BigDecimal string
1.3170 + final char[] cmpCharArray; // character array to place the intCompact
1.3171 +
1.3172 + StringBuilderHelper() {
1.3173 + sb = new StringBuilder();
1.3174 + // All non negative longs can be made to fit into 19 character array.
1.3175 + cmpCharArray = new char[19];
1.3176 + }
1.3177 +
1.3178 + // Accessors.
1.3179 + StringBuilder getStringBuilder() {
1.3180 + sb.setLength(0);
1.3181 + return sb;
1.3182 + }
1.3183 +
1.3184 + char[] getCompactCharArray() {
1.3185 + return cmpCharArray;
1.3186 + }
1.3187 +
1.3188 + /**
1.3189 + * Places characters representing the intCompact in {@code long} into
1.3190 + * cmpCharArray and returns the offset to the array where the
1.3191 + * representation starts.
1.3192 + *
1.3193 + * @param intCompact the number to put into the cmpCharArray.
1.3194 + * @return offset to the array where the representation starts.
1.3195 + * Note: intCompact must be greater or equal to zero.
1.3196 + */
1.3197 + int putIntCompact(long intCompact) {
1.3198 + assert intCompact >= 0;
1.3199 +
1.3200 + long q;
1.3201 + int r;
1.3202 + // since we start from the least significant digit, charPos points to
1.3203 + // the last character in cmpCharArray.
1.3204 + int charPos = cmpCharArray.length;
1.3205 +
1.3206 + // Get 2 digits/iteration using longs until quotient fits into an int
1.3207 + while (intCompact > Integer.MAX_VALUE) {
1.3208 + q = intCompact / 100;
1.3209 + r = (int)(intCompact - q * 100);
1.3210 + intCompact = q;
1.3211 + cmpCharArray[--charPos] = DIGIT_ONES[r];
1.3212 + cmpCharArray[--charPos] = DIGIT_TENS[r];
1.3213 + }
1.3214 +
1.3215 + // Get 2 digits/iteration using ints when i2 >= 100
1.3216 + int q2;
1.3217 + int i2 = (int)intCompact;
1.3218 + while (i2 >= 100) {
1.3219 + q2 = i2 / 100;
1.3220 + r = i2 - q2 * 100;
1.3221 + i2 = q2;
1.3222 + cmpCharArray[--charPos] = DIGIT_ONES[r];
1.3223 + cmpCharArray[--charPos] = DIGIT_TENS[r];
1.3224 + }
1.3225 +
1.3226 + cmpCharArray[--charPos] = DIGIT_ONES[i2];
1.3227 + if (i2 >= 10)
1.3228 + cmpCharArray[--charPos] = DIGIT_TENS[i2];
1.3229 +
1.3230 + return charPos;
1.3231 + }
1.3232 +
1.3233 + final static char[] DIGIT_TENS = {
1.3234 + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
1.3235 + '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
1.3236 + '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
1.3237 + '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
1.3238 + '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
1.3239 + '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
1.3240 + '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
1.3241 + '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
1.3242 + '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
1.3243 + '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
1.3244 + };
1.3245 +
1.3246 + final static char[] DIGIT_ONES = {
1.3247 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3248 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3249 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3250 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3251 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3252 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3253 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3254 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3255 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3256 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1.3257 + };
1.3258 + }
1.3259 +
1.3260 + /**
1.3261 + * Lay out this {@code BigDecimal} into a {@code char[]} array.
1.3262 + * The Java 1.2 equivalent to this was called {@code getValueString}.
1.3263 + *
1.3264 + * @param sci {@code true} for Scientific exponential notation;
1.3265 + * {@code false} for Engineering
1.3266 + * @return string with canonical string representation of this
1.3267 + * {@code BigDecimal}
1.3268 + */
1.3269 + private String layoutChars(boolean sci) {
1.3270 + if (scale == 0) // zero scale is trivial
1.3271 + return (intCompact != INFLATED) ?
1.3272 + Long.toString(intCompact):
1.3273 + intVal.toString();
1.3274 +
1.3275 + StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
1.3276 + char[] coeff;
1.3277 + int offset; // offset is the starting index for coeff array
1.3278 + // Get the significand as an absolute value
1.3279 + if (intCompact != INFLATED) {
1.3280 + offset = sbHelper.putIntCompact(Math.abs(intCompact));
1.3281 + coeff = sbHelper.getCompactCharArray();
1.3282 + } else {
1.3283 + offset = 0;
1.3284 + coeff = intVal.abs().toString().toCharArray();
1.3285 + }
1.3286 +
1.3287 + // Construct a buffer, with sufficient capacity for all cases.
1.3288 + // If E-notation is needed, length will be: +1 if negative, +1
1.3289 + // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
1.3290 + // Otherwise it could have +1 if negative, plus leading "0.00000"
1.3291 + StringBuilder buf = sbHelper.getStringBuilder();
1.3292 + if (signum() < 0) // prefix '-' if negative
1.3293 + buf.append('-');
1.3294 + int coeffLen = coeff.length - offset;
1.3295 + long adjusted = -(long)scale + (coeffLen -1);
1.3296 + if ((scale >= 0) && (adjusted >= -6)) { // plain number
1.3297 + int pad = scale - coeffLen; // count of padding zeros
1.3298 + if (pad >= 0) { // 0.xxx form
1.3299 + buf.append('0');
1.3300 + buf.append('.');
1.3301 + for (; pad>0; pad--) {
1.3302 + buf.append('0');
1.3303 + }
1.3304 + buf.append(coeff, offset, coeffLen);
1.3305 + } else { // xx.xx form
1.3306 + buf.append(coeff, offset, -pad);
1.3307 + buf.append('.');
1.3308 + buf.append(coeff, -pad + offset, scale);
1.3309 + }
1.3310 + } else { // E-notation is needed
1.3311 + if (sci) { // Scientific notation
1.3312 + buf.append(coeff[offset]); // first character
1.3313 + if (coeffLen > 1) { // more to come
1.3314 + buf.append('.');
1.3315 + buf.append(coeff, offset + 1, coeffLen - 1);
1.3316 + }
1.3317 + } else { // Engineering notation
1.3318 + int sig = (int)(adjusted % 3);
1.3319 + if (sig < 0)
1.3320 + sig += 3; // [adjusted was negative]
1.3321 + adjusted -= sig; // now a multiple of 3
1.3322 + sig++;
1.3323 + if (signum() == 0) {
1.3324 + switch (sig) {
1.3325 + case 1:
1.3326 + buf.append('0'); // exponent is a multiple of three
1.3327 + break;
1.3328 + case 2:
1.3329 + buf.append("0.00");
1.3330 + adjusted += 3;
1.3331 + break;
1.3332 + case 3:
1.3333 + buf.append("0.0");
1.3334 + adjusted += 3;
1.3335 + break;
1.3336 + default:
1.3337 + throw new AssertionError("Unexpected sig value " + sig);
1.3338 + }
1.3339 + } else if (sig >= coeffLen) { // significand all in integer
1.3340 + buf.append(coeff, offset, coeffLen);
1.3341 + // may need some zeros, too
1.3342 + for (int i = sig - coeffLen; i > 0; i--)
1.3343 + buf.append('0');
1.3344 + } else { // xx.xxE form
1.3345 + buf.append(coeff, offset, sig);
1.3346 + buf.append('.');
1.3347 + buf.append(coeff, offset + sig, coeffLen - sig);
1.3348 + }
1.3349 + }
1.3350 + if (adjusted != 0) { // [!sci could have made 0]
1.3351 + buf.append('E');
1.3352 + if (adjusted > 0) // force sign for positive
1.3353 + buf.append('+');
1.3354 + buf.append(adjusted);
1.3355 + }
1.3356 + }
1.3357 + return buf.toString();
1.3358 + }
1.3359 +
1.3360 + /**
1.3361 + * Return 10 to the power n, as a {@code BigInteger}.
1.3362 + *
1.3363 + * @param n the power of ten to be returned (>=0)
1.3364 + * @return a {@code BigInteger} with the value (10<sup>n</sup>)
1.3365 + */
1.3366 + private static BigInteger bigTenToThe(int n) {
1.3367 + if (n < 0)
1.3368 + return BigInteger.ZERO;
1.3369 +
1.3370 + if (n < BIG_TEN_POWERS_TABLE_MAX) {
1.3371 + BigInteger[] pows = BIG_TEN_POWERS_TABLE;
1.3372 + if (n < pows.length)
1.3373 + return pows[n];
1.3374 + else
1.3375 + return expandBigIntegerTenPowers(n);
1.3376 + }
1.3377 + // BigInteger.pow is slow, so make 10**n by constructing a
1.3378 + // BigInteger from a character string (still not very fast)
1.3379 + char tenpow[] = new char[n + 1];
1.3380 + tenpow[0] = '1';
1.3381 + for (int i = 1; i <= n; i++)
1.3382 + tenpow[i] = '0';
1.3383 + return new BigInteger(tenpow);
1.3384 + }
1.3385 +
1.3386 + /**
1.3387 + * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
1.3388 + *
1.3389 + * @param n the power of ten to be returned (>=0)
1.3390 + * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
1.3391 + * in the meantime, the BIG_TEN_POWERS_TABLE array gets
1.3392 + * expanded to the size greater than n.
1.3393 + */
1.3394 + private static BigInteger expandBigIntegerTenPowers(int n) {
1.3395 + synchronized(BigDecimal.class) {
1.3396 + BigInteger[] pows = BIG_TEN_POWERS_TABLE;
1.3397 + int curLen = pows.length;
1.3398 + // The following comparison and the above synchronized statement is
1.3399 + // to prevent multiple threads from expanding the same array.
1.3400 + if (curLen <= n) {
1.3401 + int newLen = curLen << 1;
1.3402 + while (newLen <= n)
1.3403 + newLen <<= 1;
1.3404 + pows = Arrays.copyOf(pows, newLen);
1.3405 + for (int i = curLen; i < newLen; i++)
1.3406 + pows[i] = pows[i - 1].multiply(BigInteger.TEN);
1.3407 + // Based on the following facts:
1.3408 + // 1. pows is a private local varible;
1.3409 + // 2. the following store is a volatile store.
1.3410 + // the newly created array elements can be safely published.
1.3411 + BIG_TEN_POWERS_TABLE = pows;
1.3412 + }
1.3413 + return pows[n];
1.3414 + }
1.3415 + }
1.3416 +
1.3417 + private static final long[] LONG_TEN_POWERS_TABLE = {
1.3418 + 1, // 0 / 10^0
1.3419 + 10, // 1 / 10^1
1.3420 + 100, // 2 / 10^2
1.3421 + 1000, // 3 / 10^3
1.3422 + 10000, // 4 / 10^4
1.3423 + 100000, // 5 / 10^5
1.3424 + 1000000, // 6 / 10^6
1.3425 + 10000000, // 7 / 10^7
1.3426 + 100000000, // 8 / 10^8
1.3427 + 1000000000, // 9 / 10^9
1.3428 + 10000000000L, // 10 / 10^10
1.3429 + 100000000000L, // 11 / 10^11
1.3430 + 1000000000000L, // 12 / 10^12
1.3431 + 10000000000000L, // 13 / 10^13
1.3432 + 100000000000000L, // 14 / 10^14
1.3433 + 1000000000000000L, // 15 / 10^15
1.3434 + 10000000000000000L, // 16 / 10^16
1.3435 + 100000000000000000L, // 17 / 10^17
1.3436 + 1000000000000000000L // 18 / 10^18
1.3437 + };
1.3438 +
1.3439 + private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
1.3440 + BigInteger.valueOf(10), BigInteger.valueOf(100),
1.3441 + BigInteger.valueOf(1000), BigInteger.valueOf(10000),
1.3442 + BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
1.3443 + BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
1.3444 + BigInteger.valueOf(1000000000),
1.3445 + BigInteger.valueOf(10000000000L),
1.3446 + BigInteger.valueOf(100000000000L),
1.3447 + BigInteger.valueOf(1000000000000L),
1.3448 + BigInteger.valueOf(10000000000000L),
1.3449 + BigInteger.valueOf(100000000000000L),
1.3450 + BigInteger.valueOf(1000000000000000L),
1.3451 + BigInteger.valueOf(10000000000000000L),
1.3452 + BigInteger.valueOf(100000000000000000L),
1.3453 + BigInteger.valueOf(1000000000000000000L)
1.3454 + };
1.3455 +
1.3456 + private static final int BIG_TEN_POWERS_TABLE_INITLEN =
1.3457 + BIG_TEN_POWERS_TABLE.length;
1.3458 + private static final int BIG_TEN_POWERS_TABLE_MAX =
1.3459 + 16 * BIG_TEN_POWERS_TABLE_INITLEN;
1.3460 +
1.3461 + private static final long THRESHOLDS_TABLE[] = {
1.3462 + Long.MAX_VALUE, // 0
1.3463 + Long.MAX_VALUE/10L, // 1
1.3464 + Long.MAX_VALUE/100L, // 2
1.3465 + Long.MAX_VALUE/1000L, // 3
1.3466 + Long.MAX_VALUE/10000L, // 4
1.3467 + Long.MAX_VALUE/100000L, // 5
1.3468 + Long.MAX_VALUE/1000000L, // 6
1.3469 + Long.MAX_VALUE/10000000L, // 7
1.3470 + Long.MAX_VALUE/100000000L, // 8
1.3471 + Long.MAX_VALUE/1000000000L, // 9
1.3472 + Long.MAX_VALUE/10000000000L, // 10
1.3473 + Long.MAX_VALUE/100000000000L, // 11
1.3474 + Long.MAX_VALUE/1000000000000L, // 12
1.3475 + Long.MAX_VALUE/10000000000000L, // 13
1.3476 + Long.MAX_VALUE/100000000000000L, // 14
1.3477 + Long.MAX_VALUE/1000000000000000L, // 15
1.3478 + Long.MAX_VALUE/10000000000000000L, // 16
1.3479 + Long.MAX_VALUE/100000000000000000L, // 17
1.3480 + Long.MAX_VALUE/1000000000000000000L // 18
1.3481 + };
1.3482 +
1.3483 + /**
1.3484 + * Compute val * 10 ^ n; return this product if it is
1.3485 + * representable as a long, INFLATED otherwise.
1.3486 + */
1.3487 + private static long longMultiplyPowerTen(long val, int n) {
1.3488 + if (val == 0 || n <= 0)
1.3489 + return val;
1.3490 + long[] tab = LONG_TEN_POWERS_TABLE;
1.3491 + long[] bounds = THRESHOLDS_TABLE;
1.3492 + if (n < tab.length && n < bounds.length) {
1.3493 + long tenpower = tab[n];
1.3494 + if (val == 1)
1.3495 + return tenpower;
1.3496 + if (Math.abs(val) <= bounds[n])
1.3497 + return val * tenpower;
1.3498 + }
1.3499 + return INFLATED;
1.3500 + }
1.3501 +
1.3502 + /**
1.3503 + * Compute this * 10 ^ n.
1.3504 + * Needed mainly to allow special casing to trap zero value
1.3505 + */
1.3506 + private BigInteger bigMultiplyPowerTen(int n) {
1.3507 + if (n <= 0)
1.3508 + return this.inflate();
1.3509 +
1.3510 + if (intCompact != INFLATED)
1.3511 + return bigTenToThe(n).multiply(intCompact);
1.3512 + else
1.3513 + return intVal.multiply(bigTenToThe(n));
1.3514 + }
1.3515 +
1.3516 + /**
1.3517 + * Assign appropriate BigInteger to intVal field if intVal is
1.3518 + * null, i.e. the compact representation is in use.
1.3519 + */
1.3520 + private BigInteger inflate() {
1.3521 + if (intVal == null)
1.3522 + intVal = BigInteger.valueOf(intCompact);
1.3523 + return intVal;
1.3524 + }
1.3525 +
1.3526 + /**
1.3527 + * Match the scales of two {@code BigDecimal}s to align their
1.3528 + * least significant digits.
1.3529 + *
1.3530 + * <p>If the scales of val[0] and val[1] differ, rescale
1.3531 + * (non-destructively) the lower-scaled {@code BigDecimal} so
1.3532 + * they match. That is, the lower-scaled reference will be
1.3533 + * replaced by a reference to a new object with the same scale as
1.3534 + * the other {@code BigDecimal}.
1.3535 + *
1.3536 + * @param val array of two elements referring to the two
1.3537 + * {@code BigDecimal}s to be aligned.
1.3538 + */
1.3539 + private static void matchScale(BigDecimal[] val) {
1.3540 + if (val[0].scale == val[1].scale) {
1.3541 + return;
1.3542 + } else if (val[0].scale < val[1].scale) {
1.3543 + val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
1.3544 + } else if (val[1].scale < val[0].scale) {
1.3545 + val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
1.3546 + }
1.3547 + }
1.3548 +
1.3549 + /**
1.3550 + * Reconstitute the {@code BigDecimal} instance from a stream (that is,
1.3551 + * deserialize it).
1.3552 + *
1.3553 + * @param s the stream being read.
1.3554 + */
1.3555 + private void readObject(java.io.ObjectInputStream s)
1.3556 + throws java.io.IOException, ClassNotFoundException {
1.3557 + // Read in all fields
1.3558 + s.defaultReadObject();
1.3559 + // validate possibly bad fields
1.3560 + if (intVal == null) {
1.3561 + String message = "BigDecimal: null intVal in stream";
1.3562 + throw new java.io.StreamCorruptedException(message);
1.3563 + // [all values of scale are now allowed]
1.3564 + }
1.3565 + intCompact = compactValFor(intVal);
1.3566 + }
1.3567 +
1.3568 + /**
1.3569 + * Serialize this {@code BigDecimal} to the stream in question
1.3570 + *
1.3571 + * @param s the stream to serialize to.
1.3572 + */
1.3573 + private void writeObject(java.io.ObjectOutputStream s)
1.3574 + throws java.io.IOException {
1.3575 + // Must inflate to maintain compatible serial form.
1.3576 + this.inflate();
1.3577 +
1.3578 + // Write proper fields
1.3579 + s.defaultWriteObject();
1.3580 + }
1.3581 +
1.3582 +
1.3583 + /**
1.3584 + * Returns the length of the absolute value of a {@code long}, in decimal
1.3585 + * digits.
1.3586 + *
1.3587 + * @param x the {@code long}
1.3588 + * @return the length of the unscaled value, in deciaml digits.
1.3589 + */
1.3590 + private static int longDigitLength(long x) {
1.3591 + /*
1.3592 + * As described in "Bit Twiddling Hacks" by Sean Anderson,
1.3593 + * (http://graphics.stanford.edu/~seander/bithacks.html)
1.3594 + * integer log 10 of x is within 1 of
1.3595 + * (1233/4096)* (1 + integer log 2 of x).
1.3596 + * The fraction 1233/4096 approximates log10(2). So we first
1.3597 + * do a version of log2 (a variant of Long class with
1.3598 + * pre-checks and opposite directionality) and then scale and
1.3599 + * check against powers table. This is a little simpler in
1.3600 + * present context than the version in Hacker's Delight sec
1.3601 + * 11-4. Adding one to bit length allows comparing downward
1.3602 + * from the LONG_TEN_POWERS_TABLE that we need anyway.
1.3603 + */
1.3604 + assert x != INFLATED;
1.3605 + if (x < 0)
1.3606 + x = -x;
1.3607 + if (x < 10) // must screen for 0, might as well 10
1.3608 + return 1;
1.3609 + int n = 64; // not 63, to avoid needing to add 1 later
1.3610 + int y = (int)(x >>> 32);
1.3611 + if (y == 0) { n -= 32; y = (int)x; }
1.3612 + if (y >>> 16 == 0) { n -= 16; y <<= 16; }
1.3613 + if (y >>> 24 == 0) { n -= 8; y <<= 8; }
1.3614 + if (y >>> 28 == 0) { n -= 4; y <<= 4; }
1.3615 + if (y >>> 30 == 0) { n -= 2; y <<= 2; }
1.3616 + int r = (((y >>> 31) + n) * 1233) >>> 12;
1.3617 + long[] tab = LONG_TEN_POWERS_TABLE;
1.3618 + // if r >= length, must have max possible digits for long
1.3619 + return (r >= tab.length || x < tab[r])? r : r+1;
1.3620 + }
1.3621 +
1.3622 + /**
1.3623 + * Returns the length of the absolute value of a BigInteger, in
1.3624 + * decimal digits.
1.3625 + *
1.3626 + * @param b the BigInteger
1.3627 + * @return the length of the unscaled value, in decimal digits
1.3628 + */
1.3629 + private static int bigDigitLength(BigInteger b) {
1.3630 + /*
1.3631 + * Same idea as the long version, but we need a better
1.3632 + * approximation of log10(2). Using 646456993/2^31
1.3633 + * is accurate up to max possible reported bitLength.
1.3634 + */
1.3635 + if (b.signum == 0)
1.3636 + return 1;
1.3637 + int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
1.3638 + return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
1.3639 + }
1.3640 +
1.3641 +
1.3642 + /**
1.3643 + * Remove insignificant trailing zeros from this
1.3644 + * {@code BigDecimal} until the preferred scale is reached or no
1.3645 + * more zeros can be removed. If the preferred scale is less than
1.3646 + * Integer.MIN_VALUE, all the trailing zeros will be removed.
1.3647 + *
1.3648 + * {@code BigInteger} assistance could help, here?
1.3649 + *
1.3650 + * <p>WARNING: This method should only be called on new objects as
1.3651 + * it mutates the value fields.
1.3652 + *
1.3653 + * @return this {@code BigDecimal} with a scale possibly reduced
1.3654 + * to be closed to the preferred scale.
1.3655 + */
1.3656 + private BigDecimal stripZerosToMatchScale(long preferredScale) {
1.3657 + this.inflate();
1.3658 + BigInteger qr[]; // quotient-remainder pair
1.3659 + while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
1.3660 + scale > preferredScale) {
1.3661 + if (intVal.testBit(0))
1.3662 + break; // odd number cannot end in 0
1.3663 + qr = intVal.divideAndRemainder(BigInteger.TEN);
1.3664 + if (qr[1].signum() != 0)
1.3665 + break; // non-0 remainder
1.3666 + intVal=qr[0];
1.3667 + scale = checkScale((long)scale-1); // could Overflow
1.3668 + if (precision > 0) // adjust precision if known
1.3669 + precision--;
1.3670 + }
1.3671 + if (intVal != null)
1.3672 + intCompact = compactValFor(intVal);
1.3673 + return this;
1.3674 + }
1.3675 +
1.3676 + /**
1.3677 + * Check a scale for Underflow or Overflow. If this BigDecimal is
1.3678 + * nonzero, throw an exception if the scale is outof range. If this
1.3679 + * is zero, saturate the scale to the extreme value of the right
1.3680 + * sign if the scale is out of range.
1.3681 + *
1.3682 + * @param val The new scale.
1.3683 + * @throws ArithmeticException (overflow or underflow) if the new
1.3684 + * scale is out of range.
1.3685 + * @return validated scale as an int.
1.3686 + */
1.3687 + private int checkScale(long val) {
1.3688 + int asInt = (int)val;
1.3689 + if (asInt != val) {
1.3690 + asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
1.3691 + BigInteger b;
1.3692 + if (intCompact != 0 &&
1.3693 + ((b = intVal) == null || b.signum() != 0))
1.3694 + throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
1.3695 + }
1.3696 + return asInt;
1.3697 + }
1.3698 +
1.3699 + /**
1.3700 + * Round an operand; used only if digits > 0. Does not change
1.3701 + * {@code this}; if rounding is needed a new {@code BigDecimal}
1.3702 + * is created and returned.
1.3703 + *
1.3704 + * @param mc the context to use.
1.3705 + * @throws ArithmeticException if the result is inexact but the
1.3706 + * rounding mode is {@code UNNECESSARY}.
1.3707 + */
1.3708 + private BigDecimal roundOp(MathContext mc) {
1.3709 + BigDecimal rounded = doRound(this, mc);
1.3710 + return rounded;
1.3711 + }
1.3712 +
1.3713 + /** Round this BigDecimal according to the MathContext settings;
1.3714 + * used only if precision {@literal >} 0.
1.3715 + *
1.3716 + * <p>WARNING: This method should only be called on new objects as
1.3717 + * it mutates the value fields.
1.3718 + *
1.3719 + * @param mc the context to use.
1.3720 + * @throws ArithmeticException if the rounding mode is
1.3721 + * {@code RoundingMode.UNNECESSARY} and the
1.3722 + * {@code BigDecimal} operation would require rounding.
1.3723 + */
1.3724 + private void roundThis(MathContext mc) {
1.3725 + BigDecimal rounded = doRound(this, mc);
1.3726 + if (rounded == this) // wasn't rounded
1.3727 + return;
1.3728 + this.intVal = rounded.intVal;
1.3729 + this.intCompact = rounded.intCompact;
1.3730 + this.scale = rounded.scale;
1.3731 + this.precision = rounded.precision;
1.3732 + }
1.3733 +
1.3734 + /**
1.3735 + * Returns a {@code BigDecimal} rounded according to the
1.3736 + * MathContext settings; used only if {@code mc.precision > 0}.
1.3737 + * Does not change {@code this}; if rounding is needed a new
1.3738 + * {@code BigDecimal} is created and returned.
1.3739 + *
1.3740 + * @param mc the context to use.
1.3741 + * @return a {@code BigDecimal} rounded according to the MathContext
1.3742 + * settings. May return this, if no rounding needed.
1.3743 + * @throws ArithmeticException if the rounding mode is
1.3744 + * {@code RoundingMode.UNNECESSARY} and the
1.3745 + * result is inexact.
1.3746 + */
1.3747 + private static BigDecimal doRound(BigDecimal d, MathContext mc) {
1.3748 + int mcp = mc.precision;
1.3749 + int drop;
1.3750 + // This might (rarely) iterate to cover the 999=>1000 case
1.3751 + while ((drop = d.precision() - mcp) > 0) {
1.3752 + int newScale = d.checkScale((long)d.scale - drop);
1.3753 + int mode = mc.roundingMode.oldMode;
1.3754 + if (drop < LONG_TEN_POWERS_TABLE.length)
1.3755 + d = divideAndRound(d.intCompact, d.intVal,
1.3756 + LONG_TEN_POWERS_TABLE[drop], null,
1.3757 + newScale, mode, newScale);
1.3758 + else
1.3759 + d = divideAndRound(d.intCompact, d.intVal,
1.3760 + INFLATED, bigTenToThe(drop),
1.3761 + newScale, mode, newScale);
1.3762 + }
1.3763 + return d;
1.3764 + }
1.3765 +
1.3766 + /**
1.3767 + * Returns the compact value for given {@code BigInteger}, or
1.3768 + * INFLATED if too big. Relies on internal representation of
1.3769 + * {@code BigInteger}.
1.3770 + */
1.3771 + private static long compactValFor(BigInteger b) {
1.3772 + int[] m = b.mag;
1.3773 + int len = m.length;
1.3774 + if (len == 0)
1.3775 + return 0;
1.3776 + int d = m[0];
1.3777 + if (len > 2 || (len == 2 && d < 0))
1.3778 + return INFLATED;
1.3779 +
1.3780 + long u = (len == 2)?
1.3781 + (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
1.3782 + (((long)d) & LONG_MASK);
1.3783 + return (b.signum < 0)? -u : u;
1.3784 + }
1.3785 +
1.3786 + private static int longCompareMagnitude(long x, long y) {
1.3787 + if (x < 0)
1.3788 + x = -x;
1.3789 + if (y < 0)
1.3790 + y = -y;
1.3791 + return (x < y) ? -1 : ((x == y) ? 0 : 1);
1.3792 + }
1.3793 +
1.3794 + private static int saturateLong(long s) {
1.3795 + int i = (int)s;
1.3796 + return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
1.3797 + }
1.3798 +
1.3799 + /*
1.3800 + * Internal printing routine
1.3801 + */
1.3802 + private static void print(String name, BigDecimal bd) {
1.3803 + System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
1.3804 + name,
1.3805 + bd.intCompact,
1.3806 + bd.intVal,
1.3807 + bd.scale,
1.3808 + bd.precision);
1.3809 + }
1.3810 +
1.3811 + /**
1.3812 + * Check internal invariants of this BigDecimal. These invariants
1.3813 + * include:
1.3814 + *
1.3815 + * <ul>
1.3816 + *
1.3817 + * <li>The object must be initialized; either intCompact must not be
1.3818 + * INFLATED or intVal is non-null. Both of these conditions may
1.3819 + * be true.
1.3820 + *
1.3821 + * <li>If both intCompact and intVal and set, their values must be
1.3822 + * consistent.
1.3823 + *
1.3824 + * <li>If precision is nonzero, it must have the right value.
1.3825 + * </ul>
1.3826 + *
1.3827 + * Note: Since this is an audit method, we are not supposed to change the
1.3828 + * state of this BigDecimal object.
1.3829 + */
1.3830 + private BigDecimal audit() {
1.3831 + if (intCompact == INFLATED) {
1.3832 + if (intVal == null) {
1.3833 + print("audit", this);
1.3834 + throw new AssertionError("null intVal");
1.3835 + }
1.3836 + // Check precision
1.3837 + if (precision > 0 && precision != bigDigitLength(intVal)) {
1.3838 + print("audit", this);
1.3839 + throw new AssertionError("precision mismatch");
1.3840 + }
1.3841 + } else {
1.3842 + if (intVal != null) {
1.3843 + long val = intVal.longValue();
1.3844 + if (val != intCompact) {
1.3845 + print("audit", this);
1.3846 + throw new AssertionError("Inconsistent state, intCompact=" +
1.3847 + intCompact + "\t intVal=" + val);
1.3848 + }
1.3849 + }
1.3850 + // Check precision
1.3851 + if (precision > 0 && precision != longDigitLength(intCompact)) {
1.3852 + print("audit", this);
1.3853 + throw new AssertionError("precision mismatch");
1.3854 + }
1.3855 + }
1.3856 + return this;
1.3857 + }
1.3858 +}