emul/compact/src/main/java/java/math/BigDecimal.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 07 Sep 2013 13:51:24 +0200
branchjdk7-b147
changeset 1258 724f3e1ea53e
permissions -rw-r--r--
Additional set of classes to make porting of lookup library more easier
jaroslav@1258
     1
/*
jaroslav@1258
     2
 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
jaroslav@1258
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1258
     4
 *
jaroslav@1258
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1258
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1258
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1258
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1258
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1258
    10
 *
jaroslav@1258
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1258
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1258
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1258
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1258
    15
 * accompanied this code).
jaroslav@1258
    16
 *
jaroslav@1258
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1258
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1258
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1258
    20
 *
jaroslav@1258
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1258
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1258
    23
 * questions.
jaroslav@1258
    24
 */
jaroslav@1258
    25
jaroslav@1258
    26
/*
jaroslav@1258
    27
 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
jaroslav@1258
    28
 */
jaroslav@1258
    29
jaroslav@1258
    30
package java.math;
jaroslav@1258
    31
jaroslav@1258
    32
import java.util.Arrays;
jaroslav@1258
    33
import static java.math.BigInteger.LONG_MASK;
jaroslav@1258
    34
jaroslav@1258
    35
/**
jaroslav@1258
    36
 * Immutable, arbitrary-precision signed decimal numbers.  A
jaroslav@1258
    37
 * {@code BigDecimal} consists of an arbitrary precision integer
jaroslav@1258
    38
 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>.  If zero
jaroslav@1258
    39
 * or positive, the scale is the number of digits to the right of the
jaroslav@1258
    40
 * decimal point.  If negative, the unscaled value of the number is
jaroslav@1258
    41
 * multiplied by ten to the power of the negation of the scale.  The
jaroslav@1258
    42
 * value of the number represented by the {@code BigDecimal} is
jaroslav@1258
    43
 * therefore <tt>(unscaledValue &times; 10<sup>-scale</sup>)</tt>.
jaroslav@1258
    44
 *
jaroslav@1258
    45
 * <p>The {@code BigDecimal} class provides operations for
jaroslav@1258
    46
 * arithmetic, scale manipulation, rounding, comparison, hashing, and
jaroslav@1258
    47
 * format conversion.  The {@link #toString} method provides a
jaroslav@1258
    48
 * canonical representation of a {@code BigDecimal}.
jaroslav@1258
    49
 *
jaroslav@1258
    50
 * <p>The {@code BigDecimal} class gives its user complete control
jaroslav@1258
    51
 * over rounding behavior.  If no rounding mode is specified and the
jaroslav@1258
    52
 * exact result cannot be represented, an exception is thrown;
jaroslav@1258
    53
 * otherwise, calculations can be carried out to a chosen precision
jaroslav@1258
    54
 * and rounding mode by supplying an appropriate {@link MathContext}
jaroslav@1258
    55
 * object to the operation.  In either case, eight <em>rounding
jaroslav@1258
    56
 * modes</em> are provided for the control of rounding.  Using the
jaroslav@1258
    57
 * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
jaroslav@1258
    58
 * represent rounding mode is largely obsolete; the enumeration values
jaroslav@1258
    59
 * of the {@code RoundingMode} {@code enum}, (such as {@link
jaroslav@1258
    60
 * RoundingMode#HALF_UP}) should be used instead.
jaroslav@1258
    61
 *
jaroslav@1258
    62
 * <p>When a {@code MathContext} object is supplied with a precision
jaroslav@1258
    63
 * setting of 0 (for example, {@link MathContext#UNLIMITED}),
jaroslav@1258
    64
 * arithmetic operations are exact, as are the arithmetic methods
jaroslav@1258
    65
 * which take no {@code MathContext} object.  (This is the only
jaroslav@1258
    66
 * behavior that was supported in releases prior to 5.)  As a
jaroslav@1258
    67
 * corollary of computing the exact result, the rounding mode setting
jaroslav@1258
    68
 * of a {@code MathContext} object with a precision setting of 0 is
jaroslav@1258
    69
 * not used and thus irrelevant.  In the case of divide, the exact
jaroslav@1258
    70
 * quotient could have an infinitely long decimal expansion; for
jaroslav@1258
    71
 * example, 1 divided by 3.  If the quotient has a nonterminating
jaroslav@1258
    72
 * decimal expansion and the operation is specified to return an exact
jaroslav@1258
    73
 * result, an {@code ArithmeticException} is thrown.  Otherwise, the
jaroslav@1258
    74
 * exact result of the division is returned, as done for other
jaroslav@1258
    75
 * operations.
jaroslav@1258
    76
 *
jaroslav@1258
    77
 * <p>When the precision setting is not 0, the rules of
jaroslav@1258
    78
 * {@code BigDecimal} arithmetic are broadly compatible with selected
jaroslav@1258
    79
 * modes of operation of the arithmetic defined in ANSI X3.274-1996
jaroslav@1258
    80
 * and ANSI X3.274-1996/AM 1-2000 (section 7.4).  Unlike those
jaroslav@1258
    81
 * standards, {@code BigDecimal} includes many rounding modes, which
jaroslav@1258
    82
 * were mandatory for division in {@code BigDecimal} releases prior
jaroslav@1258
    83
 * to 5.  Any conflicts between these ANSI standards and the
jaroslav@1258
    84
 * {@code BigDecimal} specification are resolved in favor of
jaroslav@1258
    85
 * {@code BigDecimal}.
jaroslav@1258
    86
 *
jaroslav@1258
    87
 * <p>Since the same numerical value can have different
jaroslav@1258
    88
 * representations (with different scales), the rules of arithmetic
jaroslav@1258
    89
 * and rounding must specify both the numerical result and the scale
jaroslav@1258
    90
 * used in the result's representation.
jaroslav@1258
    91
 *
jaroslav@1258
    92
 *
jaroslav@1258
    93
 * <p>In general the rounding modes and precision setting determine
jaroslav@1258
    94
 * how operations return results with a limited number of digits when
jaroslav@1258
    95
 * the exact result has more digits (perhaps infinitely many in the
jaroslav@1258
    96
 * case of division) than the number of digits returned.
jaroslav@1258
    97
 *
jaroslav@1258
    98
 * First, the
jaroslav@1258
    99
 * total number of digits to return is specified by the
jaroslav@1258
   100
 * {@code MathContext}'s {@code precision} setting; this determines
jaroslav@1258
   101
 * the result's <i>precision</i>.  The digit count starts from the
jaroslav@1258
   102
 * leftmost nonzero digit of the exact result.  The rounding mode
jaroslav@1258
   103
 * determines how any discarded trailing digits affect the returned
jaroslav@1258
   104
 * result.
jaroslav@1258
   105
 *
jaroslav@1258
   106
 * <p>For all arithmetic operators , the operation is carried out as
jaroslav@1258
   107
 * though an exact intermediate result were first calculated and then
jaroslav@1258
   108
 * rounded to the number of digits specified by the precision setting
jaroslav@1258
   109
 * (if necessary), using the selected rounding mode.  If the exact
jaroslav@1258
   110
 * result is not returned, some digit positions of the exact result
jaroslav@1258
   111
 * are discarded.  When rounding increases the magnitude of the
jaroslav@1258
   112
 * returned result, it is possible for a new digit position to be
jaroslav@1258
   113
 * created by a carry propagating to a leading {@literal "9"} digit.
jaroslav@1258
   114
 * For example, rounding the value 999.9 to three digits rounding up
jaroslav@1258
   115
 * would be numerically equal to one thousand, represented as
jaroslav@1258
   116
 * 100&times;10<sup>1</sup>.  In such cases, the new {@literal "1"} is
jaroslav@1258
   117
 * the leading digit position of the returned result.
jaroslav@1258
   118
 *
jaroslav@1258
   119
 * <p>Besides a logical exact result, each arithmetic operation has a
jaroslav@1258
   120
 * preferred scale for representing a result.  The preferred
jaroslav@1258
   121
 * scale for each operation is listed in the table below.
jaroslav@1258
   122
 *
jaroslav@1258
   123
 * <table border>
jaroslav@1258
   124
 * <caption><b>Preferred Scales for Results of Arithmetic Operations
jaroslav@1258
   125
 * </b></caption>
jaroslav@1258
   126
 * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
jaroslav@1258
   127
 * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
jaroslav@1258
   128
 * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
jaroslav@1258
   129
 * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
jaroslav@1258
   130
 * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
jaroslav@1258
   131
 * </table>
jaroslav@1258
   132
 *
jaroslav@1258
   133
 * These scales are the ones used by the methods which return exact
jaroslav@1258
   134
 * arithmetic results; except that an exact divide may have to use a
jaroslav@1258
   135
 * larger scale since the exact result may have more digits.  For
jaroslav@1258
   136
 * example, {@code 1/32} is {@code 0.03125}.
jaroslav@1258
   137
 *
jaroslav@1258
   138
 * <p>Before rounding, the scale of the logical exact intermediate
jaroslav@1258
   139
 * result is the preferred scale for that operation.  If the exact
jaroslav@1258
   140
 * numerical result cannot be represented in {@code precision}
jaroslav@1258
   141
 * digits, rounding selects the set of digits to return and the scale
jaroslav@1258
   142
 * of the result is reduced from the scale of the intermediate result
jaroslav@1258
   143
 * to the least scale which can represent the {@code precision}
jaroslav@1258
   144
 * digits actually returned.  If the exact result can be represented
jaroslav@1258
   145
 * with at most {@code precision} digits, the representation
jaroslav@1258
   146
 * of the result with the scale closest to the preferred scale is
jaroslav@1258
   147
 * returned.  In particular, an exactly representable quotient may be
jaroslav@1258
   148
 * represented in fewer than {@code precision} digits by removing
jaroslav@1258
   149
 * trailing zeros and decreasing the scale.  For example, rounding to
jaroslav@1258
   150
 * three digits using the {@linkplain RoundingMode#FLOOR floor}
jaroslav@1258
   151
 * rounding mode, <br>
jaroslav@1258
   152
 *
jaroslav@1258
   153
 * {@code 19/100 = 0.19   // integer=19,  scale=2} <br>
jaroslav@1258
   154
 *
jaroslav@1258
   155
 * but<br>
jaroslav@1258
   156
 *
jaroslav@1258
   157
 * {@code 21/110 = 0.190  // integer=190, scale=3} <br>
jaroslav@1258
   158
 *
jaroslav@1258
   159
 * <p>Note that for add, subtract, and multiply, the reduction in
jaroslav@1258
   160
 * scale will equal the number of digit positions of the exact result
jaroslav@1258
   161
 * which are discarded. If the rounding causes a carry propagation to
jaroslav@1258
   162
 * create a new high-order digit position, an additional digit of the
jaroslav@1258
   163
 * result is discarded than when no new digit position is created.
jaroslav@1258
   164
 *
jaroslav@1258
   165
 * <p>Other methods may have slightly different rounding semantics.
jaroslav@1258
   166
 * For example, the result of the {@code pow} method using the
jaroslav@1258
   167
 * {@linkplain #pow(int, MathContext) specified algorithm} can
jaroslav@1258
   168
 * occasionally differ from the rounded mathematical result by more
jaroslav@1258
   169
 * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
jaroslav@1258
   170
 *
jaroslav@1258
   171
 * <p>Two types of operations are provided for manipulating the scale
jaroslav@1258
   172
 * of a {@code BigDecimal}: scaling/rounding operations and decimal
jaroslav@1258
   173
 * point motion operations.  Scaling/rounding operations ({@link
jaroslav@1258
   174
 * #setScale setScale} and {@link #round round}) return a
jaroslav@1258
   175
 * {@code BigDecimal} whose value is approximately (or exactly) equal
jaroslav@1258
   176
 * to that of the operand, but whose scale or precision is the
jaroslav@1258
   177
 * specified value; that is, they increase or decrease the precision
jaroslav@1258
   178
 * of the stored number with minimal effect on its value.  Decimal
jaroslav@1258
   179
 * point motion operations ({@link #movePointLeft movePointLeft} and
jaroslav@1258
   180
 * {@link #movePointRight movePointRight}) return a
jaroslav@1258
   181
 * {@code BigDecimal} created from the operand by moving the decimal
jaroslav@1258
   182
 * point a specified distance in the specified direction.
jaroslav@1258
   183
 *
jaroslav@1258
   184
 * <p>For the sake of brevity and clarity, pseudo-code is used
jaroslav@1258
   185
 * throughout the descriptions of {@code BigDecimal} methods.  The
jaroslav@1258
   186
 * pseudo-code expression {@code (i + j)} is shorthand for "a
jaroslav@1258
   187
 * {@code BigDecimal} whose value is that of the {@code BigDecimal}
jaroslav@1258
   188
 * {@code i} added to that of the {@code BigDecimal}
jaroslav@1258
   189
 * {@code j}." The pseudo-code expression {@code (i == j)} is
jaroslav@1258
   190
 * shorthand for "{@code true} if and only if the
jaroslav@1258
   191
 * {@code BigDecimal} {@code i} represents the same value as the
jaroslav@1258
   192
 * {@code BigDecimal} {@code j}." Other pseudo-code expressions
jaroslav@1258
   193
 * are interpreted similarly.  Square brackets are used to represent
jaroslav@1258
   194
 * the particular {@code BigInteger} and scale pair defining a
jaroslav@1258
   195
 * {@code BigDecimal} value; for example [19, 2] is the
jaroslav@1258
   196
 * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
jaroslav@1258
   197
 *
jaroslav@1258
   198
 * <p>Note: care should be exercised if {@code BigDecimal} objects
jaroslav@1258
   199
 * are used as keys in a {@link java.util.SortedMap SortedMap} or
jaroslav@1258
   200
 * elements in a {@link java.util.SortedSet SortedSet} since
jaroslav@1258
   201
 * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
jaroslav@1258
   202
 * with equals</i>.  See {@link Comparable}, {@link
jaroslav@1258
   203
 * java.util.SortedMap} or {@link java.util.SortedSet} for more
jaroslav@1258
   204
 * information.
jaroslav@1258
   205
 *
jaroslav@1258
   206
 * <p>All methods and constructors for this class throw
jaroslav@1258
   207
 * {@code NullPointerException} when passed a {@code null} object
jaroslav@1258
   208
 * reference for any input parameter.
jaroslav@1258
   209
 *
jaroslav@1258
   210
 * @see     BigInteger
jaroslav@1258
   211
 * @see     MathContext
jaroslav@1258
   212
 * @see     RoundingMode
jaroslav@1258
   213
 * @see     java.util.SortedMap
jaroslav@1258
   214
 * @see     java.util.SortedSet
jaroslav@1258
   215
 * @author  Josh Bloch
jaroslav@1258
   216
 * @author  Mike Cowlishaw
jaroslav@1258
   217
 * @author  Joseph D. Darcy
jaroslav@1258
   218
 */
jaroslav@1258
   219
public class BigDecimal extends Number implements Comparable<BigDecimal> {
jaroslav@1258
   220
    /**
jaroslav@1258
   221
     * The unscaled value of this BigDecimal, as returned by {@link
jaroslav@1258
   222
     * #unscaledValue}.
jaroslav@1258
   223
     *
jaroslav@1258
   224
     * @serial
jaroslav@1258
   225
     * @see #unscaledValue
jaroslav@1258
   226
     */
jaroslav@1258
   227
    private volatile BigInteger intVal;
jaroslav@1258
   228
jaroslav@1258
   229
    /**
jaroslav@1258
   230
     * The scale of this BigDecimal, as returned by {@link #scale}.
jaroslav@1258
   231
     *
jaroslav@1258
   232
     * @serial
jaroslav@1258
   233
     * @see #scale
jaroslav@1258
   234
     */
jaroslav@1258
   235
    private int scale;  // Note: this may have any value, so
jaroslav@1258
   236
                        // calculations must be done in longs
jaroslav@1258
   237
    /**
jaroslav@1258
   238
     * The number of decimal digits in this BigDecimal, or 0 if the
jaroslav@1258
   239
     * number of digits are not known (lookaside information).  If
jaroslav@1258
   240
     * nonzero, the value is guaranteed correct.  Use the precision()
jaroslav@1258
   241
     * method to obtain and set the value if it might be 0.  This
jaroslav@1258
   242
     * field is mutable until set nonzero.
jaroslav@1258
   243
     *
jaroslav@1258
   244
     * @since  1.5
jaroslav@1258
   245
     */
jaroslav@1258
   246
    private transient int precision;
jaroslav@1258
   247
jaroslav@1258
   248
    /**
jaroslav@1258
   249
     * Used to store the canonical string representation, if computed.
jaroslav@1258
   250
     */
jaroslav@1258
   251
    private transient String stringCache;
jaroslav@1258
   252
jaroslav@1258
   253
    /**
jaroslav@1258
   254
     * Sentinel value for {@link #intCompact} indicating the
jaroslav@1258
   255
     * significand information is only available from {@code intVal}.
jaroslav@1258
   256
     */
jaroslav@1258
   257
    static final long INFLATED = Long.MIN_VALUE;
jaroslav@1258
   258
jaroslav@1258
   259
    /**
jaroslav@1258
   260
     * If the absolute value of the significand of this BigDecimal is
jaroslav@1258
   261
     * less than or equal to {@code Long.MAX_VALUE}, the value can be
jaroslav@1258
   262
     * compactly stored in this field and used in computations.
jaroslav@1258
   263
     */
jaroslav@1258
   264
    private transient long intCompact;
jaroslav@1258
   265
jaroslav@1258
   266
    // All 18-digit base ten strings fit into a long; not all 19-digit
jaroslav@1258
   267
    // strings will
jaroslav@1258
   268
    private static final int MAX_COMPACT_DIGITS = 18;
jaroslav@1258
   269
jaroslav@1258
   270
    private static final int MAX_BIGINT_BITS = 62;
jaroslav@1258
   271
jaroslav@1258
   272
    /* Appease the serialization gods */
jaroslav@1258
   273
    private static final long serialVersionUID = 6108874887143696463L;
jaroslav@1258
   274
jaroslav@1258
   275
    private static final ThreadLocal<StringBuilderHelper>
jaroslav@1258
   276
        threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
jaroslav@1258
   277
        @Override
jaroslav@1258
   278
        protected StringBuilderHelper initialValue() {
jaroslav@1258
   279
            return new StringBuilderHelper();
jaroslav@1258
   280
        }
jaroslav@1258
   281
    };
jaroslav@1258
   282
jaroslav@1258
   283
    // Cache of common small BigDecimal values.
jaroslav@1258
   284
    private static final BigDecimal zeroThroughTen[] = {
jaroslav@1258
   285
        new BigDecimal(BigInteger.ZERO,         0,  0, 1),
jaroslav@1258
   286
        new BigDecimal(BigInteger.ONE,          1,  0, 1),
jaroslav@1258
   287
        new BigDecimal(BigInteger.valueOf(2),   2,  0, 1),
jaroslav@1258
   288
        new BigDecimal(BigInteger.valueOf(3),   3,  0, 1),
jaroslav@1258
   289
        new BigDecimal(BigInteger.valueOf(4),   4,  0, 1),
jaroslav@1258
   290
        new BigDecimal(BigInteger.valueOf(5),   5,  0, 1),
jaroslav@1258
   291
        new BigDecimal(BigInteger.valueOf(6),   6,  0, 1),
jaroslav@1258
   292
        new BigDecimal(BigInteger.valueOf(7),   7,  0, 1),
jaroslav@1258
   293
        new BigDecimal(BigInteger.valueOf(8),   8,  0, 1),
jaroslav@1258
   294
        new BigDecimal(BigInteger.valueOf(9),   9,  0, 1),
jaroslav@1258
   295
        new BigDecimal(BigInteger.TEN,          10, 0, 2),
jaroslav@1258
   296
    };
jaroslav@1258
   297
jaroslav@1258
   298
    // Cache of zero scaled by 0 - 15
jaroslav@1258
   299
    private static final BigDecimal[] ZERO_SCALED_BY = {
jaroslav@1258
   300
        zeroThroughTen[0],
jaroslav@1258
   301
        new BigDecimal(BigInteger.ZERO, 0, 1, 1),
jaroslav@1258
   302
        new BigDecimal(BigInteger.ZERO, 0, 2, 1),
jaroslav@1258
   303
        new BigDecimal(BigInteger.ZERO, 0, 3, 1),
jaroslav@1258
   304
        new BigDecimal(BigInteger.ZERO, 0, 4, 1),
jaroslav@1258
   305
        new BigDecimal(BigInteger.ZERO, 0, 5, 1),
jaroslav@1258
   306
        new BigDecimal(BigInteger.ZERO, 0, 6, 1),
jaroslav@1258
   307
        new BigDecimal(BigInteger.ZERO, 0, 7, 1),
jaroslav@1258
   308
        new BigDecimal(BigInteger.ZERO, 0, 8, 1),
jaroslav@1258
   309
        new BigDecimal(BigInteger.ZERO, 0, 9, 1),
jaroslav@1258
   310
        new BigDecimal(BigInteger.ZERO, 0, 10, 1),
jaroslav@1258
   311
        new BigDecimal(BigInteger.ZERO, 0, 11, 1),
jaroslav@1258
   312
        new BigDecimal(BigInteger.ZERO, 0, 12, 1),
jaroslav@1258
   313
        new BigDecimal(BigInteger.ZERO, 0, 13, 1),
jaroslav@1258
   314
        new BigDecimal(BigInteger.ZERO, 0, 14, 1),
jaroslav@1258
   315
        new BigDecimal(BigInteger.ZERO, 0, 15, 1),
jaroslav@1258
   316
    };
jaroslav@1258
   317
jaroslav@1258
   318
    // Half of Long.MIN_VALUE & Long.MAX_VALUE.
jaroslav@1258
   319
    private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
jaroslav@1258
   320
    private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
jaroslav@1258
   321
jaroslav@1258
   322
    // Constants
jaroslav@1258
   323
    /**
jaroslav@1258
   324
     * The value 0, with a scale of 0.
jaroslav@1258
   325
     *
jaroslav@1258
   326
     * @since  1.5
jaroslav@1258
   327
     */
jaroslav@1258
   328
    public static final BigDecimal ZERO =
jaroslav@1258
   329
        zeroThroughTen[0];
jaroslav@1258
   330
jaroslav@1258
   331
    /**
jaroslav@1258
   332
     * The value 1, with a scale of 0.
jaroslav@1258
   333
     *
jaroslav@1258
   334
     * @since  1.5
jaroslav@1258
   335
     */
jaroslav@1258
   336
    public static final BigDecimal ONE =
jaroslav@1258
   337
        zeroThroughTen[1];
jaroslav@1258
   338
jaroslav@1258
   339
    /**
jaroslav@1258
   340
     * The value 10, with a scale of 0.
jaroslav@1258
   341
     *
jaroslav@1258
   342
     * @since  1.5
jaroslav@1258
   343
     */
jaroslav@1258
   344
    public static final BigDecimal TEN =
jaroslav@1258
   345
        zeroThroughTen[10];
jaroslav@1258
   346
jaroslav@1258
   347
    // Constructors
jaroslav@1258
   348
jaroslav@1258
   349
    /**
jaroslav@1258
   350
     * Trusted package private constructor.
jaroslav@1258
   351
     * Trusted simply means if val is INFLATED, intVal could not be null and
jaroslav@1258
   352
     * if intVal is null, val could not be INFLATED.
jaroslav@1258
   353
     */
jaroslav@1258
   354
    BigDecimal(BigInteger intVal, long val, int scale, int prec) {
jaroslav@1258
   355
        this.scale = scale;
jaroslav@1258
   356
        this.precision = prec;
jaroslav@1258
   357
        this.intCompact = val;
jaroslav@1258
   358
        this.intVal = intVal;
jaroslav@1258
   359
    }
jaroslav@1258
   360
jaroslav@1258
   361
    /**
jaroslav@1258
   362
     * Translates a character array representation of a
jaroslav@1258
   363
     * {@code BigDecimal} into a {@code BigDecimal}, accepting the
jaroslav@1258
   364
     * same sequence of characters as the {@link #BigDecimal(String)}
jaroslav@1258
   365
     * constructor, while allowing a sub-array to be specified.
jaroslav@1258
   366
     *
jaroslav@1258
   367
     * <p>Note that if the sequence of characters is already available
jaroslav@1258
   368
     * within a character array, using this constructor is faster than
jaroslav@1258
   369
     * converting the {@code char} array to string and using the
jaroslav@1258
   370
     * {@code BigDecimal(String)} constructor .
jaroslav@1258
   371
     *
jaroslav@1258
   372
     * @param  in {@code char} array that is the source of characters.
jaroslav@1258
   373
     * @param  offset first character in the array to inspect.
jaroslav@1258
   374
     * @param  len number of characters to consider.
jaroslav@1258
   375
     * @throws NumberFormatException if {@code in} is not a valid
jaroslav@1258
   376
     *         representation of a {@code BigDecimal} or the defined subarray
jaroslav@1258
   377
     *         is not wholly within {@code in}.
jaroslav@1258
   378
     * @since  1.5
jaroslav@1258
   379
     */
jaroslav@1258
   380
    public BigDecimal(char[] in, int offset, int len) {
jaroslav@1258
   381
        // protect against huge length.
jaroslav@1258
   382
        if (offset+len > in.length || offset < 0)
jaroslav@1258
   383
            throw new NumberFormatException();
jaroslav@1258
   384
        // This is the primary string to BigDecimal constructor; all
jaroslav@1258
   385
        // incoming strings end up here; it uses explicit (inline)
jaroslav@1258
   386
        // parsing for speed and generates at most one intermediate
jaroslav@1258
   387
        // (temporary) object (a char[] array) for non-compact case.
jaroslav@1258
   388
jaroslav@1258
   389
        // Use locals for all fields values until completion
jaroslav@1258
   390
        int prec = 0;                 // record precision value
jaroslav@1258
   391
        int scl = 0;                  // record scale value
jaroslav@1258
   392
        long rs = 0;                  // the compact value in long
jaroslav@1258
   393
        BigInteger rb = null;         // the inflated value in BigInteger
jaroslav@1258
   394
jaroslav@1258
   395
        // use array bounds checking to handle too-long, len == 0,
jaroslav@1258
   396
        // bad offset, etc.
jaroslav@1258
   397
        try {
jaroslav@1258
   398
            // handle the sign
jaroslav@1258
   399
            boolean isneg = false;          // assume positive
jaroslav@1258
   400
            if (in[offset] == '-') {
jaroslav@1258
   401
                isneg = true;               // leading minus means negative
jaroslav@1258
   402
                offset++;
jaroslav@1258
   403
                len--;
jaroslav@1258
   404
            } else if (in[offset] == '+') { // leading + allowed
jaroslav@1258
   405
                offset++;
jaroslav@1258
   406
                len--;
jaroslav@1258
   407
            }
jaroslav@1258
   408
jaroslav@1258
   409
            // should now be at numeric part of the significand
jaroslav@1258
   410
            boolean dot = false;             // true when there is a '.'
jaroslav@1258
   411
            int cfirst = offset;             // record start of integer
jaroslav@1258
   412
            long exp = 0;                    // exponent
jaroslav@1258
   413
            char c;                          // current character
jaroslav@1258
   414
jaroslav@1258
   415
            boolean isCompact = (len <= MAX_COMPACT_DIGITS);
jaroslav@1258
   416
            // integer significand array & idx is the index to it. The array
jaroslav@1258
   417
            // is ONLY used when we can't use a compact representation.
jaroslav@1258
   418
            char coeff[] = isCompact ? null : new char[len];
jaroslav@1258
   419
            int idx = 0;
jaroslav@1258
   420
jaroslav@1258
   421
            for (; len > 0; offset++, len--) {
jaroslav@1258
   422
                c = in[offset];
jaroslav@1258
   423
                // have digit
jaroslav@1258
   424
                if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
jaroslav@1258
   425
                    // First compact case, we need not to preserve the character
jaroslav@1258
   426
                    // and we can just compute the value in place.
jaroslav@1258
   427
                    if (isCompact) {
jaroslav@1258
   428
                        int digit = Character.digit(c, 10);
jaroslav@1258
   429
                        if (digit == 0) {
jaroslav@1258
   430
                            if (prec == 0)
jaroslav@1258
   431
                                prec = 1;
jaroslav@1258
   432
                            else if (rs != 0) {
jaroslav@1258
   433
                                rs *= 10;
jaroslav@1258
   434
                                ++prec;
jaroslav@1258
   435
                            } // else digit is a redundant leading zero
jaroslav@1258
   436
                        } else {
jaroslav@1258
   437
                            if (prec != 1 || rs != 0)
jaroslav@1258
   438
                                ++prec; // prec unchanged if preceded by 0s
jaroslav@1258
   439
                            rs = rs * 10 + digit;
jaroslav@1258
   440
                        }
jaroslav@1258
   441
                    } else { // the unscaled value is likely a BigInteger object.
jaroslav@1258
   442
                        if (c == '0' || Character.digit(c, 10) == 0) {
jaroslav@1258
   443
                            if (prec == 0) {
jaroslav@1258
   444
                                coeff[idx] = c;
jaroslav@1258
   445
                                prec = 1;
jaroslav@1258
   446
                            } else if (idx != 0) {
jaroslav@1258
   447
                                coeff[idx++] = c;
jaroslav@1258
   448
                                ++prec;
jaroslav@1258
   449
                            } // else c must be a redundant leading zero
jaroslav@1258
   450
                        } else {
jaroslav@1258
   451
                            if (prec != 1 || idx != 0)
jaroslav@1258
   452
                                ++prec; // prec unchanged if preceded by 0s
jaroslav@1258
   453
                            coeff[idx++] = c;
jaroslav@1258
   454
                        }
jaroslav@1258
   455
                    }
jaroslav@1258
   456
                    if (dot)
jaroslav@1258
   457
                        ++scl;
jaroslav@1258
   458
                    continue;
jaroslav@1258
   459
                }
jaroslav@1258
   460
                // have dot
jaroslav@1258
   461
                if (c == '.') {
jaroslav@1258
   462
                    // have dot
jaroslav@1258
   463
                    if (dot)         // two dots
jaroslav@1258
   464
                        throw new NumberFormatException();
jaroslav@1258
   465
                    dot = true;
jaroslav@1258
   466
                    continue;
jaroslav@1258
   467
                }
jaroslav@1258
   468
                // exponent expected
jaroslav@1258
   469
                if ((c != 'e') && (c != 'E'))
jaroslav@1258
   470
                    throw new NumberFormatException();
jaroslav@1258
   471
                offset++;
jaroslav@1258
   472
                c = in[offset];
jaroslav@1258
   473
                len--;
jaroslav@1258
   474
                boolean negexp = (c == '-');
jaroslav@1258
   475
                // optional sign
jaroslav@1258
   476
                if (negexp || c == '+') {
jaroslav@1258
   477
                    offset++;
jaroslav@1258
   478
                    c = in[offset];
jaroslav@1258
   479
                    len--;
jaroslav@1258
   480
                }
jaroslav@1258
   481
                if (len <= 0)    // no exponent digits
jaroslav@1258
   482
                    throw new NumberFormatException();
jaroslav@1258
   483
                // skip leading zeros in the exponent
jaroslav@1258
   484
                while (len > 10 && Character.digit(c, 10) == 0) {
jaroslav@1258
   485
                    offset++;
jaroslav@1258
   486
                    c = in[offset];
jaroslav@1258
   487
                    len--;
jaroslav@1258
   488
                }
jaroslav@1258
   489
                if (len > 10)  // too many nonzero exponent digits
jaroslav@1258
   490
                    throw new NumberFormatException();
jaroslav@1258
   491
                // c now holds first digit of exponent
jaroslav@1258
   492
                for (;; len--) {
jaroslav@1258
   493
                    int v;
jaroslav@1258
   494
                    if (c >= '0' && c <= '9') {
jaroslav@1258
   495
                        v = c - '0';
jaroslav@1258
   496
                    } else {
jaroslav@1258
   497
                        v = Character.digit(c, 10);
jaroslav@1258
   498
                        if (v < 0)            // not a digit
jaroslav@1258
   499
                            throw new NumberFormatException();
jaroslav@1258
   500
                    }
jaroslav@1258
   501
                    exp = exp * 10 + v;
jaroslav@1258
   502
                    if (len == 1)
jaroslav@1258
   503
                        break;               // that was final character
jaroslav@1258
   504
                    offset++;
jaroslav@1258
   505
                    c = in[offset];
jaroslav@1258
   506
                }
jaroslav@1258
   507
                if (negexp)                  // apply sign
jaroslav@1258
   508
                    exp = -exp;
jaroslav@1258
   509
                // Next test is required for backwards compatibility
jaroslav@1258
   510
                if ((int)exp != exp)         // overflow
jaroslav@1258
   511
                    throw new NumberFormatException();
jaroslav@1258
   512
                break;                       // [saves a test]
jaroslav@1258
   513
            }
jaroslav@1258
   514
            // here when no characters left
jaroslav@1258
   515
            if (prec == 0)              // no digits found
jaroslav@1258
   516
                throw new NumberFormatException();
jaroslav@1258
   517
jaroslav@1258
   518
            // Adjust scale if exp is not zero.
jaroslav@1258
   519
            if (exp != 0) {                  // had significant exponent
jaroslav@1258
   520
                // Can't call checkScale which relies on proper fields value
jaroslav@1258
   521
                long adjustedScale = scl - exp;
jaroslav@1258
   522
                if (adjustedScale > Integer.MAX_VALUE ||
jaroslav@1258
   523
                    adjustedScale < Integer.MIN_VALUE)
jaroslav@1258
   524
                    throw new NumberFormatException("Scale out of range.");
jaroslav@1258
   525
                scl = (int)adjustedScale;
jaroslav@1258
   526
            }
jaroslav@1258
   527
jaroslav@1258
   528
            // Remove leading zeros from precision (digits count)
jaroslav@1258
   529
            if (isCompact) {
jaroslav@1258
   530
                rs = isneg ? -rs : rs;
jaroslav@1258
   531
            } else {
jaroslav@1258
   532
                char quick[];
jaroslav@1258
   533
                if (!isneg) {
jaroslav@1258
   534
                    quick = (coeff.length != prec) ?
jaroslav@1258
   535
                        Arrays.copyOf(coeff, prec) : coeff;
jaroslav@1258
   536
                } else {
jaroslav@1258
   537
                    quick = new char[prec + 1];
jaroslav@1258
   538
                    quick[0] = '-';
jaroslav@1258
   539
                    System.arraycopy(coeff, 0, quick, 1, prec);
jaroslav@1258
   540
                }
jaroslav@1258
   541
                rb = new BigInteger(quick);
jaroslav@1258
   542
                rs = compactValFor(rb);
jaroslav@1258
   543
            }
jaroslav@1258
   544
        } catch (ArrayIndexOutOfBoundsException e) {
jaroslav@1258
   545
            throw new NumberFormatException();
jaroslav@1258
   546
        } catch (NegativeArraySizeException e) {
jaroslav@1258
   547
            throw new NumberFormatException();
jaroslav@1258
   548
        }
jaroslav@1258
   549
        this.scale = scl;
jaroslav@1258
   550
        this.precision = prec;
jaroslav@1258
   551
        this.intCompact = rs;
jaroslav@1258
   552
        this.intVal = (rs != INFLATED) ? null : rb;
jaroslav@1258
   553
    }
jaroslav@1258
   554
jaroslav@1258
   555
    /**
jaroslav@1258
   556
     * Translates a character array representation of a
jaroslav@1258
   557
     * {@code BigDecimal} into a {@code BigDecimal}, accepting the
jaroslav@1258
   558
     * same sequence of characters as the {@link #BigDecimal(String)}
jaroslav@1258
   559
     * constructor, while allowing a sub-array to be specified and
jaroslav@1258
   560
     * with rounding according to the context settings.
jaroslav@1258
   561
     *
jaroslav@1258
   562
     * <p>Note that if the sequence of characters is already available
jaroslav@1258
   563
     * within a character array, using this constructor is faster than
jaroslav@1258
   564
     * converting the {@code char} array to string and using the
jaroslav@1258
   565
     * {@code BigDecimal(String)} constructor .
jaroslav@1258
   566
     *
jaroslav@1258
   567
     * @param  in {@code char} array that is the source of characters.
jaroslav@1258
   568
     * @param  offset first character in the array to inspect.
jaroslav@1258
   569
     * @param  len number of characters to consider..
jaroslav@1258
   570
     * @param  mc the context to use.
jaroslav@1258
   571
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   572
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   573
     * @throws NumberFormatException if {@code in} is not a valid
jaroslav@1258
   574
     *         representation of a {@code BigDecimal} or the defined subarray
jaroslav@1258
   575
     *         is not wholly within {@code in}.
jaroslav@1258
   576
     * @since  1.5
jaroslav@1258
   577
     */
jaroslav@1258
   578
    public BigDecimal(char[] in, int offset, int len, MathContext mc) {
jaroslav@1258
   579
        this(in, offset, len);
jaroslav@1258
   580
        if (mc.precision > 0)
jaroslav@1258
   581
            roundThis(mc);
jaroslav@1258
   582
    }
jaroslav@1258
   583
jaroslav@1258
   584
    /**
jaroslav@1258
   585
     * Translates a character array representation of a
jaroslav@1258
   586
     * {@code BigDecimal} into a {@code BigDecimal}, accepting the
jaroslav@1258
   587
     * same sequence of characters as the {@link #BigDecimal(String)}
jaroslav@1258
   588
     * constructor.
jaroslav@1258
   589
     *
jaroslav@1258
   590
     * <p>Note that if the sequence of characters is already available
jaroslav@1258
   591
     * as a character array, using this constructor is faster than
jaroslav@1258
   592
     * converting the {@code char} array to string and using the
jaroslav@1258
   593
     * {@code BigDecimal(String)} constructor .
jaroslav@1258
   594
     *
jaroslav@1258
   595
     * @param in {@code char} array that is the source of characters.
jaroslav@1258
   596
     * @throws NumberFormatException if {@code in} is not a valid
jaroslav@1258
   597
     *         representation of a {@code BigDecimal}.
jaroslav@1258
   598
     * @since  1.5
jaroslav@1258
   599
     */
jaroslav@1258
   600
    public BigDecimal(char[] in) {
jaroslav@1258
   601
        this(in, 0, in.length);
jaroslav@1258
   602
    }
jaroslav@1258
   603
jaroslav@1258
   604
    /**
jaroslav@1258
   605
     * Translates a character array representation of a
jaroslav@1258
   606
     * {@code BigDecimal} into a {@code BigDecimal}, accepting the
jaroslav@1258
   607
     * same sequence of characters as the {@link #BigDecimal(String)}
jaroslav@1258
   608
     * constructor and with rounding according to the context
jaroslav@1258
   609
     * settings.
jaroslav@1258
   610
     *
jaroslav@1258
   611
     * <p>Note that if the sequence of characters is already available
jaroslav@1258
   612
     * as a character array, using this constructor is faster than
jaroslav@1258
   613
     * converting the {@code char} array to string and using the
jaroslav@1258
   614
     * {@code BigDecimal(String)} constructor .
jaroslav@1258
   615
     *
jaroslav@1258
   616
     * @param  in {@code char} array that is the source of characters.
jaroslav@1258
   617
     * @param  mc the context to use.
jaroslav@1258
   618
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   619
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   620
     * @throws NumberFormatException if {@code in} is not a valid
jaroslav@1258
   621
     *         representation of a {@code BigDecimal}.
jaroslav@1258
   622
     * @since  1.5
jaroslav@1258
   623
     */
jaroslav@1258
   624
    public BigDecimal(char[] in, MathContext mc) {
jaroslav@1258
   625
        this(in, 0, in.length, mc);
jaroslav@1258
   626
    }
jaroslav@1258
   627
jaroslav@1258
   628
    /**
jaroslav@1258
   629
     * Translates the string representation of a {@code BigDecimal}
jaroslav@1258
   630
     * into a {@code BigDecimal}.  The string representation consists
jaroslav@1258
   631
     * of an optional sign, {@code '+'} (<tt> '&#92;u002B'</tt>) or
jaroslav@1258
   632
     * {@code '-'} (<tt>'&#92;u002D'</tt>), followed by a sequence of
jaroslav@1258
   633
     * zero or more decimal digits ("the integer"), optionally
jaroslav@1258
   634
     * followed by a fraction, optionally followed by an exponent.
jaroslav@1258
   635
     *
jaroslav@1258
   636
     * <p>The fraction consists of a decimal point followed by zero
jaroslav@1258
   637
     * or more decimal digits.  The string must contain at least one
jaroslav@1258
   638
     * digit in either the integer or the fraction.  The number formed
jaroslav@1258
   639
     * by the sign, the integer and the fraction is referred to as the
jaroslav@1258
   640
     * <i>significand</i>.
jaroslav@1258
   641
     *
jaroslav@1258
   642
     * <p>The exponent consists of the character {@code 'e'}
jaroslav@1258
   643
     * (<tt>'&#92;u0065'</tt>) or {@code 'E'} (<tt>'&#92;u0045'</tt>)
jaroslav@1258
   644
     * followed by one or more decimal digits.  The value of the
jaroslav@1258
   645
     * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
jaroslav@1258
   646
     * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
jaroslav@1258
   647
     *
jaroslav@1258
   648
     * <p>More formally, the strings this constructor accepts are
jaroslav@1258
   649
     * described by the following grammar:
jaroslav@1258
   650
     * <blockquote>
jaroslav@1258
   651
     * <dl>
jaroslav@1258
   652
     * <dt><i>BigDecimalString:</i>
jaroslav@1258
   653
     * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
jaroslav@1258
   654
     * <p>
jaroslav@1258
   655
     * <dt><i>Sign:</i>
jaroslav@1258
   656
     * <dd>{@code +}
jaroslav@1258
   657
     * <dd>{@code -}
jaroslav@1258
   658
     * <p>
jaroslav@1258
   659
     * <dt><i>Significand:</i>
jaroslav@1258
   660
     * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
jaroslav@1258
   661
     * <dd>{@code .} <i>FractionPart</i>
jaroslav@1258
   662
     * <dd><i>IntegerPart</i>
jaroslav@1258
   663
     * <p>
jaroslav@1258
   664
     * <dt><i>IntegerPart:</i>
jaroslav@1258
   665
     * <dd><i>Digits</i>
jaroslav@1258
   666
     * <p>
jaroslav@1258
   667
     * <dt><i>FractionPart:</i>
jaroslav@1258
   668
     * <dd><i>Digits</i>
jaroslav@1258
   669
     * <p>
jaroslav@1258
   670
     * <dt><i>Exponent:</i>
jaroslav@1258
   671
     * <dd><i>ExponentIndicator SignedInteger</i>
jaroslav@1258
   672
     * <p>
jaroslav@1258
   673
     * <dt><i>ExponentIndicator:</i>
jaroslav@1258
   674
     * <dd>{@code e}
jaroslav@1258
   675
     * <dd>{@code E}
jaroslav@1258
   676
     * <p>
jaroslav@1258
   677
     * <dt><i>SignedInteger:</i>
jaroslav@1258
   678
     * <dd><i>Sign<sub>opt</sub> Digits</i>
jaroslav@1258
   679
     * <p>
jaroslav@1258
   680
     * <dt><i>Digits:</i>
jaroslav@1258
   681
     * <dd><i>Digit</i>
jaroslav@1258
   682
     * <dd><i>Digits Digit</i>
jaroslav@1258
   683
     * <p>
jaroslav@1258
   684
     * <dt><i>Digit:</i>
jaroslav@1258
   685
     * <dd>any character for which {@link Character#isDigit}
jaroslav@1258
   686
     * returns {@code true}, including 0, 1, 2 ...
jaroslav@1258
   687
     * </dl>
jaroslav@1258
   688
     * </blockquote>
jaroslav@1258
   689
     *
jaroslav@1258
   690
     * <p>The scale of the returned {@code BigDecimal} will be the
jaroslav@1258
   691
     * number of digits in the fraction, or zero if the string
jaroslav@1258
   692
     * contains no decimal point, subject to adjustment for any
jaroslav@1258
   693
     * exponent; if the string contains an exponent, the exponent is
jaroslav@1258
   694
     * subtracted from the scale.  The value of the resulting scale
jaroslav@1258
   695
     * must lie between {@code Integer.MIN_VALUE} and
jaroslav@1258
   696
     * {@code Integer.MAX_VALUE}, inclusive.
jaroslav@1258
   697
     *
jaroslav@1258
   698
     * <p>The character-to-digit mapping is provided by {@link
jaroslav@1258
   699
     * java.lang.Character#digit} set to convert to radix 10.  The
jaroslav@1258
   700
     * String may not contain any extraneous characters (whitespace,
jaroslav@1258
   701
     * for example).
jaroslav@1258
   702
     *
jaroslav@1258
   703
     * <p><b>Examples:</b><br>
jaroslav@1258
   704
     * The value of the returned {@code BigDecimal} is equal to
jaroslav@1258
   705
     * <i>significand</i> &times; 10<sup>&nbsp;<i>exponent</i></sup>.
jaroslav@1258
   706
     * For each string on the left, the resulting representation
jaroslav@1258
   707
     * [{@code BigInteger}, {@code scale}] is shown on the right.
jaroslav@1258
   708
     * <pre>
jaroslav@1258
   709
     * "0"            [0,0]
jaroslav@1258
   710
     * "0.00"         [0,2]
jaroslav@1258
   711
     * "123"          [123,0]
jaroslav@1258
   712
     * "-123"         [-123,0]
jaroslav@1258
   713
     * "1.23E3"       [123,-1]
jaroslav@1258
   714
     * "1.23E+3"      [123,-1]
jaroslav@1258
   715
     * "12.3E+7"      [123,-6]
jaroslav@1258
   716
     * "12.0"         [120,1]
jaroslav@1258
   717
     * "12.3"         [123,1]
jaroslav@1258
   718
     * "0.00123"      [123,5]
jaroslav@1258
   719
     * "-1.23E-12"    [-123,14]
jaroslav@1258
   720
     * "1234.5E-4"    [12345,5]
jaroslav@1258
   721
     * "0E+7"         [0,-7]
jaroslav@1258
   722
     * "-0"           [0,0]
jaroslav@1258
   723
     * </pre>
jaroslav@1258
   724
     *
jaroslav@1258
   725
     * <p>Note: For values other than {@code float} and
jaroslav@1258
   726
     * {@code double} NaN and &plusmn;Infinity, this constructor is
jaroslav@1258
   727
     * compatible with the values returned by {@link Float#toString}
jaroslav@1258
   728
     * and {@link Double#toString}.  This is generally the preferred
jaroslav@1258
   729
     * way to convert a {@code float} or {@code double} into a
jaroslav@1258
   730
     * BigDecimal, as it doesn't suffer from the unpredictability of
jaroslav@1258
   731
     * the {@link #BigDecimal(double)} constructor.
jaroslav@1258
   732
     *
jaroslav@1258
   733
     * @param val String representation of {@code BigDecimal}.
jaroslav@1258
   734
     *
jaroslav@1258
   735
     * @throws NumberFormatException if {@code val} is not a valid
jaroslav@1258
   736
     *         representation of a {@code BigDecimal}.
jaroslav@1258
   737
     */
jaroslav@1258
   738
    public BigDecimal(String val) {
jaroslav@1258
   739
        this(val.toCharArray(), 0, val.length());
jaroslav@1258
   740
    }
jaroslav@1258
   741
jaroslav@1258
   742
    /**
jaroslav@1258
   743
     * Translates the string representation of a {@code BigDecimal}
jaroslav@1258
   744
     * into a {@code BigDecimal}, accepting the same strings as the
jaroslav@1258
   745
     * {@link #BigDecimal(String)} constructor, with rounding
jaroslav@1258
   746
     * according to the context settings.
jaroslav@1258
   747
     *
jaroslav@1258
   748
     * @param  val string representation of a {@code BigDecimal}.
jaroslav@1258
   749
     * @param  mc the context to use.
jaroslav@1258
   750
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   751
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   752
     * @throws NumberFormatException if {@code val} is not a valid
jaroslav@1258
   753
     *         representation of a BigDecimal.
jaroslav@1258
   754
     * @since  1.5
jaroslav@1258
   755
     */
jaroslav@1258
   756
    public BigDecimal(String val, MathContext mc) {
jaroslav@1258
   757
        this(val.toCharArray(), 0, val.length());
jaroslav@1258
   758
        if (mc.precision > 0)
jaroslav@1258
   759
            roundThis(mc);
jaroslav@1258
   760
    }
jaroslav@1258
   761
jaroslav@1258
   762
    /**
jaroslav@1258
   763
     * Translates a {@code double} into a {@code BigDecimal} which
jaroslav@1258
   764
     * is the exact decimal representation of the {@code double}'s
jaroslav@1258
   765
     * binary floating-point value.  The scale of the returned
jaroslav@1258
   766
     * {@code BigDecimal} is the smallest value such that
jaroslav@1258
   767
     * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
jaroslav@1258
   768
     * <p>
jaroslav@1258
   769
     * <b>Notes:</b>
jaroslav@1258
   770
     * <ol>
jaroslav@1258
   771
     * <li>
jaroslav@1258
   772
     * The results of this constructor can be somewhat unpredictable.
jaroslav@1258
   773
     * One might assume that writing {@code new BigDecimal(0.1)} in
jaroslav@1258
   774
     * Java creates a {@code BigDecimal} which is exactly equal to
jaroslav@1258
   775
     * 0.1 (an unscaled value of 1, with a scale of 1), but it is
jaroslav@1258
   776
     * actually equal to
jaroslav@1258
   777
     * 0.1000000000000000055511151231257827021181583404541015625.
jaroslav@1258
   778
     * This is because 0.1 cannot be represented exactly as a
jaroslav@1258
   779
     * {@code double} (or, for that matter, as a binary fraction of
jaroslav@1258
   780
     * any finite length).  Thus, the value that is being passed
jaroslav@1258
   781
     * <i>in</i> to the constructor is not exactly equal to 0.1,
jaroslav@1258
   782
     * appearances notwithstanding.
jaroslav@1258
   783
     *
jaroslav@1258
   784
     * <li>
jaroslav@1258
   785
     * The {@code String} constructor, on the other hand, is
jaroslav@1258
   786
     * perfectly predictable: writing {@code new BigDecimal("0.1")}
jaroslav@1258
   787
     * creates a {@code BigDecimal} which is <i>exactly</i> equal to
jaroslav@1258
   788
     * 0.1, as one would expect.  Therefore, it is generally
jaroslav@1258
   789
     * recommended that the {@linkplain #BigDecimal(String)
jaroslav@1258
   790
     * <tt>String</tt> constructor} be used in preference to this one.
jaroslav@1258
   791
     *
jaroslav@1258
   792
     * <li>
jaroslav@1258
   793
     * When a {@code double} must be used as a source for a
jaroslav@1258
   794
     * {@code BigDecimal}, note that this constructor provides an
jaroslav@1258
   795
     * exact conversion; it does not give the same result as
jaroslav@1258
   796
     * converting the {@code double} to a {@code String} using the
jaroslav@1258
   797
     * {@link Double#toString(double)} method and then using the
jaroslav@1258
   798
     * {@link #BigDecimal(String)} constructor.  To get that result,
jaroslav@1258
   799
     * use the {@code static} {@link #valueOf(double)} method.
jaroslav@1258
   800
     * </ol>
jaroslav@1258
   801
     *
jaroslav@1258
   802
     * @param val {@code double} value to be converted to
jaroslav@1258
   803
     *        {@code BigDecimal}.
jaroslav@1258
   804
     * @throws NumberFormatException if {@code val} is infinite or NaN.
jaroslav@1258
   805
     */
jaroslav@1258
   806
    public BigDecimal(double val) {
jaroslav@1258
   807
        if (Double.isInfinite(val) || Double.isNaN(val))
jaroslav@1258
   808
            throw new NumberFormatException("Infinite or NaN");
jaroslav@1258
   809
jaroslav@1258
   810
        // Translate the double into sign, exponent and significand, according
jaroslav@1258
   811
        // to the formulae in JLS, Section 20.10.22.
jaroslav@1258
   812
        long valBits = Double.doubleToLongBits(val);
jaroslav@1258
   813
        int sign = ((valBits >> 63)==0 ? 1 : -1);
jaroslav@1258
   814
        int exponent = (int) ((valBits >> 52) & 0x7ffL);
jaroslav@1258
   815
        long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
jaroslav@1258
   816
                            : (valBits & ((1L<<52) - 1)) | (1L<<52));
jaroslav@1258
   817
        exponent -= 1075;
jaroslav@1258
   818
        // At this point, val == sign * significand * 2**exponent.
jaroslav@1258
   819
jaroslav@1258
   820
        /*
jaroslav@1258
   821
         * Special case zero to supress nonterminating normalization
jaroslav@1258
   822
         * and bogus scale calculation.
jaroslav@1258
   823
         */
jaroslav@1258
   824
        if (significand == 0) {
jaroslav@1258
   825
            intVal = BigInteger.ZERO;
jaroslav@1258
   826
            intCompact = 0;
jaroslav@1258
   827
            precision = 1;
jaroslav@1258
   828
            return;
jaroslav@1258
   829
        }
jaroslav@1258
   830
jaroslav@1258
   831
        // Normalize
jaroslav@1258
   832
        while((significand & 1) == 0) {    //  i.e., significand is even
jaroslav@1258
   833
            significand >>= 1;
jaroslav@1258
   834
            exponent++;
jaroslav@1258
   835
        }
jaroslav@1258
   836
jaroslav@1258
   837
        // Calculate intVal and scale
jaroslav@1258
   838
        long s = sign * significand;
jaroslav@1258
   839
        BigInteger b;
jaroslav@1258
   840
        if (exponent < 0) {
jaroslav@1258
   841
            b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
jaroslav@1258
   842
            scale = -exponent;
jaroslav@1258
   843
        } else if (exponent > 0) {
jaroslav@1258
   844
            b = BigInteger.valueOf(2).pow(exponent).multiply(s);
jaroslav@1258
   845
        } else {
jaroslav@1258
   846
            b = BigInteger.valueOf(s);
jaroslav@1258
   847
        }
jaroslav@1258
   848
        intCompact = compactValFor(b);
jaroslav@1258
   849
        intVal = (intCompact != INFLATED) ? null : b;
jaroslav@1258
   850
    }
jaroslav@1258
   851
jaroslav@1258
   852
    /**
jaroslav@1258
   853
     * Translates a {@code double} into a {@code BigDecimal}, with
jaroslav@1258
   854
     * rounding according to the context settings.  The scale of the
jaroslav@1258
   855
     * {@code BigDecimal} is the smallest value such that
jaroslav@1258
   856
     * <tt>(10<sup>scale</sup> &times; val)</tt> is an integer.
jaroslav@1258
   857
     *
jaroslav@1258
   858
     * <p>The results of this constructor can be somewhat unpredictable
jaroslav@1258
   859
     * and its use is generally not recommended; see the notes under
jaroslav@1258
   860
     * the {@link #BigDecimal(double)} constructor.
jaroslav@1258
   861
     *
jaroslav@1258
   862
     * @param  val {@code double} value to be converted to
jaroslav@1258
   863
     *         {@code BigDecimal}.
jaroslav@1258
   864
     * @param  mc the context to use.
jaroslav@1258
   865
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   866
     *         RoundingMode is UNNECESSARY.
jaroslav@1258
   867
     * @throws NumberFormatException if {@code val} is infinite or NaN.
jaroslav@1258
   868
     * @since  1.5
jaroslav@1258
   869
     */
jaroslav@1258
   870
    public BigDecimal(double val, MathContext mc) {
jaroslav@1258
   871
        this(val);
jaroslav@1258
   872
        if (mc.precision > 0)
jaroslav@1258
   873
            roundThis(mc);
jaroslav@1258
   874
    }
jaroslav@1258
   875
jaroslav@1258
   876
    /**
jaroslav@1258
   877
     * Translates a {@code BigInteger} into a {@code BigDecimal}.
jaroslav@1258
   878
     * The scale of the {@code BigDecimal} is zero.
jaroslav@1258
   879
     *
jaroslav@1258
   880
     * @param val {@code BigInteger} value to be converted to
jaroslav@1258
   881
     *            {@code BigDecimal}.
jaroslav@1258
   882
     */
jaroslav@1258
   883
    public BigDecimal(BigInteger val) {
jaroslav@1258
   884
        intCompact = compactValFor(val);
jaroslav@1258
   885
        intVal = (intCompact != INFLATED) ? null : val;
jaroslav@1258
   886
    }
jaroslav@1258
   887
jaroslav@1258
   888
    /**
jaroslav@1258
   889
     * Translates a {@code BigInteger} into a {@code BigDecimal}
jaroslav@1258
   890
     * rounding according to the context settings.  The scale of the
jaroslav@1258
   891
     * {@code BigDecimal} is zero.
jaroslav@1258
   892
     *
jaroslav@1258
   893
     * @param val {@code BigInteger} value to be converted to
jaroslav@1258
   894
     *            {@code BigDecimal}.
jaroslav@1258
   895
     * @param  mc the context to use.
jaroslav@1258
   896
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   897
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   898
     * @since  1.5
jaroslav@1258
   899
     */
jaroslav@1258
   900
    public BigDecimal(BigInteger val, MathContext mc) {
jaroslav@1258
   901
        this(val);
jaroslav@1258
   902
        if (mc.precision > 0)
jaroslav@1258
   903
            roundThis(mc);
jaroslav@1258
   904
    }
jaroslav@1258
   905
jaroslav@1258
   906
    /**
jaroslav@1258
   907
     * Translates a {@code BigInteger} unscaled value and an
jaroslav@1258
   908
     * {@code int} scale into a {@code BigDecimal}.  The value of
jaroslav@1258
   909
     * the {@code BigDecimal} is
jaroslav@1258
   910
     * <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
jaroslav@1258
   911
     *
jaroslav@1258
   912
     * @param unscaledVal unscaled value of the {@code BigDecimal}.
jaroslav@1258
   913
     * @param scale scale of the {@code BigDecimal}.
jaroslav@1258
   914
     */
jaroslav@1258
   915
    public BigDecimal(BigInteger unscaledVal, int scale) {
jaroslav@1258
   916
        // Negative scales are now allowed
jaroslav@1258
   917
        this(unscaledVal);
jaroslav@1258
   918
        this.scale = scale;
jaroslav@1258
   919
    }
jaroslav@1258
   920
jaroslav@1258
   921
    /**
jaroslav@1258
   922
     * Translates a {@code BigInteger} unscaled value and an
jaroslav@1258
   923
     * {@code int} scale into a {@code BigDecimal}, with rounding
jaroslav@1258
   924
     * according to the context settings.  The value of the
jaroslav@1258
   925
     * {@code BigDecimal} is <tt>(unscaledVal &times;
jaroslav@1258
   926
     * 10<sup>-scale</sup>)</tt>, rounded according to the
jaroslav@1258
   927
     * {@code precision} and rounding mode settings.
jaroslav@1258
   928
     *
jaroslav@1258
   929
     * @param  unscaledVal unscaled value of the {@code BigDecimal}.
jaroslav@1258
   930
     * @param  scale scale of the {@code BigDecimal}.
jaroslav@1258
   931
     * @param  mc the context to use.
jaroslav@1258
   932
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   933
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   934
     * @since  1.5
jaroslav@1258
   935
     */
jaroslav@1258
   936
    public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
jaroslav@1258
   937
        this(unscaledVal);
jaroslav@1258
   938
        this.scale = scale;
jaroslav@1258
   939
        if (mc.precision > 0)
jaroslav@1258
   940
            roundThis(mc);
jaroslav@1258
   941
    }
jaroslav@1258
   942
jaroslav@1258
   943
    /**
jaroslav@1258
   944
     * Translates an {@code int} into a {@code BigDecimal}.  The
jaroslav@1258
   945
     * scale of the {@code BigDecimal} is zero.
jaroslav@1258
   946
     *
jaroslav@1258
   947
     * @param val {@code int} value to be converted to
jaroslav@1258
   948
     *            {@code BigDecimal}.
jaroslav@1258
   949
     * @since  1.5
jaroslav@1258
   950
     */
jaroslav@1258
   951
    public BigDecimal(int val) {
jaroslav@1258
   952
        intCompact = val;
jaroslav@1258
   953
    }
jaroslav@1258
   954
jaroslav@1258
   955
    /**
jaroslav@1258
   956
     * Translates an {@code int} into a {@code BigDecimal}, with
jaroslav@1258
   957
     * rounding according to the context settings.  The scale of the
jaroslav@1258
   958
     * {@code BigDecimal}, before any rounding, is zero.
jaroslav@1258
   959
     *
jaroslav@1258
   960
     * @param  val {@code int} value to be converted to {@code BigDecimal}.
jaroslav@1258
   961
     * @param  mc the context to use.
jaroslav@1258
   962
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   963
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   964
     * @since  1.5
jaroslav@1258
   965
     */
jaroslav@1258
   966
    public BigDecimal(int val, MathContext mc) {
jaroslav@1258
   967
        intCompact = val;
jaroslav@1258
   968
        if (mc.precision > 0)
jaroslav@1258
   969
            roundThis(mc);
jaroslav@1258
   970
    }
jaroslav@1258
   971
jaroslav@1258
   972
    /**
jaroslav@1258
   973
     * Translates a {@code long} into a {@code BigDecimal}.  The
jaroslav@1258
   974
     * scale of the {@code BigDecimal} is zero.
jaroslav@1258
   975
     *
jaroslav@1258
   976
     * @param val {@code long} value to be converted to {@code BigDecimal}.
jaroslav@1258
   977
     * @since  1.5
jaroslav@1258
   978
     */
jaroslav@1258
   979
    public BigDecimal(long val) {
jaroslav@1258
   980
        this.intCompact = val;
jaroslav@1258
   981
        this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
jaroslav@1258
   982
    }
jaroslav@1258
   983
jaroslav@1258
   984
    /**
jaroslav@1258
   985
     * Translates a {@code long} into a {@code BigDecimal}, with
jaroslav@1258
   986
     * rounding according to the context settings.  The scale of the
jaroslav@1258
   987
     * {@code BigDecimal}, before any rounding, is zero.
jaroslav@1258
   988
     *
jaroslav@1258
   989
     * @param  val {@code long} value to be converted to {@code BigDecimal}.
jaroslav@1258
   990
     * @param  mc the context to use.
jaroslav@1258
   991
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
   992
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
   993
     * @since  1.5
jaroslav@1258
   994
     */
jaroslav@1258
   995
    public BigDecimal(long val, MathContext mc) {
jaroslav@1258
   996
        this(val);
jaroslav@1258
   997
        if (mc.precision > 0)
jaroslav@1258
   998
            roundThis(mc);
jaroslav@1258
   999
    }
jaroslav@1258
  1000
jaroslav@1258
  1001
    // Static Factory Methods
jaroslav@1258
  1002
jaroslav@1258
  1003
    /**
jaroslav@1258
  1004
     * Translates a {@code long} unscaled value and an
jaroslav@1258
  1005
     * {@code int} scale into a {@code BigDecimal}.  This
jaroslav@1258
  1006
     * {@literal "static factory method"} is provided in preference to
jaroslav@1258
  1007
     * a ({@code long}, {@code int}) constructor because it
jaroslav@1258
  1008
     * allows for reuse of frequently used {@code BigDecimal} values..
jaroslav@1258
  1009
     *
jaroslav@1258
  1010
     * @param unscaledVal unscaled value of the {@code BigDecimal}.
jaroslav@1258
  1011
     * @param scale scale of the {@code BigDecimal}.
jaroslav@1258
  1012
     * @return a {@code BigDecimal} whose value is
jaroslav@1258
  1013
     *         <tt>(unscaledVal &times; 10<sup>-scale</sup>)</tt>.
jaroslav@1258
  1014
     */
jaroslav@1258
  1015
    public static BigDecimal valueOf(long unscaledVal, int scale) {
jaroslav@1258
  1016
        if (scale == 0)
jaroslav@1258
  1017
            return valueOf(unscaledVal);
jaroslav@1258
  1018
        else if (unscaledVal == 0) {
jaroslav@1258
  1019
            if (scale > 0 && scale < ZERO_SCALED_BY.length)
jaroslav@1258
  1020
                return ZERO_SCALED_BY[scale];
jaroslav@1258
  1021
            else
jaroslav@1258
  1022
                return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
jaroslav@1258
  1023
        }
jaroslav@1258
  1024
        return new BigDecimal(unscaledVal == INFLATED ?
jaroslav@1258
  1025
                              BigInteger.valueOf(unscaledVal) : null,
jaroslav@1258
  1026
                              unscaledVal, scale, 0);
jaroslav@1258
  1027
    }
jaroslav@1258
  1028
jaroslav@1258
  1029
    /**
jaroslav@1258
  1030
     * Translates a {@code long} value into a {@code BigDecimal}
jaroslav@1258
  1031
     * with a scale of zero.  This {@literal "static factory method"}
jaroslav@1258
  1032
     * is provided in preference to a ({@code long}) constructor
jaroslav@1258
  1033
     * because it allows for reuse of frequently used
jaroslav@1258
  1034
     * {@code BigDecimal} values.
jaroslav@1258
  1035
     *
jaroslav@1258
  1036
     * @param val value of the {@code BigDecimal}.
jaroslav@1258
  1037
     * @return a {@code BigDecimal} whose value is {@code val}.
jaroslav@1258
  1038
     */
jaroslav@1258
  1039
    public static BigDecimal valueOf(long val) {
jaroslav@1258
  1040
        if (val >= 0 && val < zeroThroughTen.length)
jaroslav@1258
  1041
            return zeroThroughTen[(int)val];
jaroslav@1258
  1042
        else if (val != INFLATED)
jaroslav@1258
  1043
            return new BigDecimal(null, val, 0, 0);
jaroslav@1258
  1044
        return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
jaroslav@1258
  1045
    }
jaroslav@1258
  1046
jaroslav@1258
  1047
    /**
jaroslav@1258
  1048
     * Translates a {@code double} into a {@code BigDecimal}, using
jaroslav@1258
  1049
     * the {@code double}'s canonical string representation provided
jaroslav@1258
  1050
     * by the {@link Double#toString(double)} method.
jaroslav@1258
  1051
     *
jaroslav@1258
  1052
     * <p><b>Note:</b> This is generally the preferred way to convert
jaroslav@1258
  1053
     * a {@code double} (or {@code float}) into a
jaroslav@1258
  1054
     * {@code BigDecimal}, as the value returned is equal to that
jaroslav@1258
  1055
     * resulting from constructing a {@code BigDecimal} from the
jaroslav@1258
  1056
     * result of using {@link Double#toString(double)}.
jaroslav@1258
  1057
     *
jaroslav@1258
  1058
     * @param  val {@code double} to convert to a {@code BigDecimal}.
jaroslav@1258
  1059
     * @return a {@code BigDecimal} whose value is equal to or approximately
jaroslav@1258
  1060
     *         equal to the value of {@code val}.
jaroslav@1258
  1061
     * @throws NumberFormatException if {@code val} is infinite or NaN.
jaroslav@1258
  1062
     * @since  1.5
jaroslav@1258
  1063
     */
jaroslav@1258
  1064
    public static BigDecimal valueOf(double val) {
jaroslav@1258
  1065
        // Reminder: a zero double returns '0.0', so we cannot fastpath
jaroslav@1258
  1066
        // to use the constant ZERO.  This might be important enough to
jaroslav@1258
  1067
        // justify a factory approach, a cache, or a few private
jaroslav@1258
  1068
        // constants, later.
jaroslav@1258
  1069
        return new BigDecimal(Double.toString(val));
jaroslav@1258
  1070
    }
jaroslav@1258
  1071
jaroslav@1258
  1072
    // Arithmetic Operations
jaroslav@1258
  1073
    /**
jaroslav@1258
  1074
     * Returns a {@code BigDecimal} whose value is {@code (this +
jaroslav@1258
  1075
     * augend)}, and whose scale is {@code max(this.scale(),
jaroslav@1258
  1076
     * augend.scale())}.
jaroslav@1258
  1077
     *
jaroslav@1258
  1078
     * @param  augend value to be added to this {@code BigDecimal}.
jaroslav@1258
  1079
     * @return {@code this + augend}
jaroslav@1258
  1080
     */
jaroslav@1258
  1081
    public BigDecimal add(BigDecimal augend) {
jaroslav@1258
  1082
        long xs = this.intCompact;
jaroslav@1258
  1083
        long ys = augend.intCompact;
jaroslav@1258
  1084
        BigInteger fst = (xs != INFLATED) ? null : this.intVal;
jaroslav@1258
  1085
        BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
jaroslav@1258
  1086
        int rscale = this.scale;
jaroslav@1258
  1087
jaroslav@1258
  1088
        long sdiff = (long)rscale - augend.scale;
jaroslav@1258
  1089
        if (sdiff != 0) {
jaroslav@1258
  1090
            if (sdiff < 0) {
jaroslav@1258
  1091
                int raise = checkScale(-sdiff);
jaroslav@1258
  1092
                rscale = augend.scale;
jaroslav@1258
  1093
                if (xs == INFLATED ||
jaroslav@1258
  1094
                    (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
jaroslav@1258
  1095
                    fst = bigMultiplyPowerTen(raise);
jaroslav@1258
  1096
            } else {
jaroslav@1258
  1097
                int raise = augend.checkScale(sdiff);
jaroslav@1258
  1098
                if (ys == INFLATED ||
jaroslav@1258
  1099
                    (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
jaroslav@1258
  1100
                    snd = augend.bigMultiplyPowerTen(raise);
jaroslav@1258
  1101
            }
jaroslav@1258
  1102
        }
jaroslav@1258
  1103
        if (xs != INFLATED && ys != INFLATED) {
jaroslav@1258
  1104
            long sum = xs + ys;
jaroslav@1258
  1105
            // See "Hacker's Delight" section 2-12 for explanation of
jaroslav@1258
  1106
            // the overflow test.
jaroslav@1258
  1107
            if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
jaroslav@1258
  1108
                return BigDecimal.valueOf(sum, rscale);
jaroslav@1258
  1109
        }
jaroslav@1258
  1110
        if (fst == null)
jaroslav@1258
  1111
            fst = BigInteger.valueOf(xs);
jaroslav@1258
  1112
        if (snd == null)
jaroslav@1258
  1113
            snd = BigInteger.valueOf(ys);
jaroslav@1258
  1114
        BigInteger sum = fst.add(snd);
jaroslav@1258
  1115
        return (fst.signum == snd.signum) ?
jaroslav@1258
  1116
            new BigDecimal(sum, INFLATED, rscale, 0) :
jaroslav@1258
  1117
            new BigDecimal(sum, rscale);
jaroslav@1258
  1118
    }
jaroslav@1258
  1119
jaroslav@1258
  1120
    /**
jaroslav@1258
  1121
     * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
jaroslav@1258
  1122
     * with rounding according to the context settings.
jaroslav@1258
  1123
     *
jaroslav@1258
  1124
     * If either number is zero and the precision setting is nonzero then
jaroslav@1258
  1125
     * the other number, rounded if necessary, is used as the result.
jaroslav@1258
  1126
     *
jaroslav@1258
  1127
     * @param  augend value to be added to this {@code BigDecimal}.
jaroslav@1258
  1128
     * @param  mc the context to use.
jaroslav@1258
  1129
     * @return {@code this + augend}, rounded as necessary.
jaroslav@1258
  1130
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1131
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  1132
     * @since  1.5
jaroslav@1258
  1133
     */
jaroslav@1258
  1134
    public BigDecimal add(BigDecimal augend, MathContext mc) {
jaroslav@1258
  1135
        if (mc.precision == 0)
jaroslav@1258
  1136
            return add(augend);
jaroslav@1258
  1137
        BigDecimal lhs = this;
jaroslav@1258
  1138
jaroslav@1258
  1139
        // Could optimize if values are compact
jaroslav@1258
  1140
        this.inflate();
jaroslav@1258
  1141
        augend.inflate();
jaroslav@1258
  1142
jaroslav@1258
  1143
        // If either number is zero then the other number, rounded and
jaroslav@1258
  1144
        // scaled if necessary, is used as the result.
jaroslav@1258
  1145
        {
jaroslav@1258
  1146
            boolean lhsIsZero = lhs.signum() == 0;
jaroslav@1258
  1147
            boolean augendIsZero = augend.signum() == 0;
jaroslav@1258
  1148
jaroslav@1258
  1149
            if (lhsIsZero || augendIsZero) {
jaroslav@1258
  1150
                int preferredScale = Math.max(lhs.scale(), augend.scale());
jaroslav@1258
  1151
                BigDecimal result;
jaroslav@1258
  1152
jaroslav@1258
  1153
                // Could use a factory for zero instead of a new object
jaroslav@1258
  1154
                if (lhsIsZero && augendIsZero)
jaroslav@1258
  1155
                    return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
jaroslav@1258
  1156
jaroslav@1258
  1157
                result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
jaroslav@1258
  1158
jaroslav@1258
  1159
                if (result.scale() == preferredScale)
jaroslav@1258
  1160
                    return result;
jaroslav@1258
  1161
                else if (result.scale() > preferredScale) {
jaroslav@1258
  1162
                    BigDecimal scaledResult =
jaroslav@1258
  1163
                        new BigDecimal(result.intVal, result.intCompact,
jaroslav@1258
  1164
                                       result.scale, 0);
jaroslav@1258
  1165
                    scaledResult.stripZerosToMatchScale(preferredScale);
jaroslav@1258
  1166
                    return scaledResult;
jaroslav@1258
  1167
                } else { // result.scale < preferredScale
jaroslav@1258
  1168
                    int precisionDiff = mc.precision - result.precision();
jaroslav@1258
  1169
                    int scaleDiff     = preferredScale - result.scale();
jaroslav@1258
  1170
jaroslav@1258
  1171
                    if (precisionDiff >= scaleDiff)
jaroslav@1258
  1172
                        return result.setScale(preferredScale); // can achieve target scale
jaroslav@1258
  1173
                    else
jaroslav@1258
  1174
                        return result.setScale(result.scale() + precisionDiff);
jaroslav@1258
  1175
                }
jaroslav@1258
  1176
            }
jaroslav@1258
  1177
        }
jaroslav@1258
  1178
jaroslav@1258
  1179
        long padding = (long)lhs.scale - augend.scale;
jaroslav@1258
  1180
        if (padding != 0) {        // scales differ; alignment needed
jaroslav@1258
  1181
            BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
jaroslav@1258
  1182
            matchScale(arg);
jaroslav@1258
  1183
            lhs    = arg[0];
jaroslav@1258
  1184
            augend = arg[1];
jaroslav@1258
  1185
        }
jaroslav@1258
  1186
jaroslav@1258
  1187
        BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
jaroslav@1258
  1188
                                      lhs.scale);
jaroslav@1258
  1189
        return doRound(d, mc);
jaroslav@1258
  1190
    }
jaroslav@1258
  1191
jaroslav@1258
  1192
    /**
jaroslav@1258
  1193
     * Returns an array of length two, the sum of whose entries is
jaroslav@1258
  1194
     * equal to the rounded sum of the {@code BigDecimal} arguments.
jaroslav@1258
  1195
     *
jaroslav@1258
  1196
     * <p>If the digit positions of the arguments have a sufficient
jaroslav@1258
  1197
     * gap between them, the value smaller in magnitude can be
jaroslav@1258
  1198
     * condensed into a {@literal "sticky bit"} and the end result will
jaroslav@1258
  1199
     * round the same way <em>if</em> the precision of the final
jaroslav@1258
  1200
     * result does not include the high order digit of the small
jaroslav@1258
  1201
     * magnitude operand.
jaroslav@1258
  1202
     *
jaroslav@1258
  1203
     * <p>Note that while strictly speaking this is an optimization,
jaroslav@1258
  1204
     * it makes a much wider range of additions practical.
jaroslav@1258
  1205
     *
jaroslav@1258
  1206
     * <p>This corresponds to a pre-shift operation in a fixed
jaroslav@1258
  1207
     * precision floating-point adder; this method is complicated by
jaroslav@1258
  1208
     * variable precision of the result as determined by the
jaroslav@1258
  1209
     * MathContext.  A more nuanced operation could implement a
jaroslav@1258
  1210
     * {@literal "right shift"} on the smaller magnitude operand so
jaroslav@1258
  1211
     * that the number of digits of the smaller operand could be
jaroslav@1258
  1212
     * reduced even though the significands partially overlapped.
jaroslav@1258
  1213
     */
jaroslav@1258
  1214
    private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
jaroslav@1258
  1215
                                  long padding, MathContext mc) {
jaroslav@1258
  1216
        assert padding != 0;
jaroslav@1258
  1217
        BigDecimal big;
jaroslav@1258
  1218
        BigDecimal small;
jaroslav@1258
  1219
jaroslav@1258
  1220
        if (padding < 0) {     // lhs is big;   augend is small
jaroslav@1258
  1221
            big   = lhs;
jaroslav@1258
  1222
            small = augend;
jaroslav@1258
  1223
        } else {               // lhs is small; augend is big
jaroslav@1258
  1224
            big   = augend;
jaroslav@1258
  1225
            small = lhs;
jaroslav@1258
  1226
        }
jaroslav@1258
  1227
jaroslav@1258
  1228
        /*
jaroslav@1258
  1229
         * This is the estimated scale of an ulp of the result; it
jaroslav@1258
  1230
         * assumes that the result doesn't have a carry-out on a true
jaroslav@1258
  1231
         * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
jaroslav@1258
  1232
         * on borrowing (e.g. 100 - 1.2 => 98.8)
jaroslav@1258
  1233
         */
jaroslav@1258
  1234
        long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
jaroslav@1258
  1235
jaroslav@1258
  1236
        /*
jaroslav@1258
  1237
         * The low-order digit position of big is big.scale().  This
jaroslav@1258
  1238
         * is true regardless of whether big has a positive or
jaroslav@1258
  1239
         * negative scale.  The high-order digit position of small is
jaroslav@1258
  1240
         * small.scale - (small.precision() - 1).  To do the full
jaroslav@1258
  1241
         * condensation, the digit positions of big and small must be
jaroslav@1258
  1242
         * disjoint *and* the digit positions of small should not be
jaroslav@1258
  1243
         * directly visible in the result.
jaroslav@1258
  1244
         */
jaroslav@1258
  1245
        long smallHighDigitPos = (long)small.scale - small.precision() + 1;
jaroslav@1258
  1246
        if (smallHighDigitPos > big.scale + 2 &&         // big and small disjoint
jaroslav@1258
  1247
            smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
jaroslav@1258
  1248
            small = BigDecimal.valueOf(small.signum(),
jaroslav@1258
  1249
                                       this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
jaroslav@1258
  1250
        }
jaroslav@1258
  1251
jaroslav@1258
  1252
        // Since addition is symmetric, preserving input order in
jaroslav@1258
  1253
        // returned operands doesn't matter
jaroslav@1258
  1254
        BigDecimal[] result = {big, small};
jaroslav@1258
  1255
        return result;
jaroslav@1258
  1256
    }
jaroslav@1258
  1257
jaroslav@1258
  1258
    /**
jaroslav@1258
  1259
     * Returns a {@code BigDecimal} whose value is {@code (this -
jaroslav@1258
  1260
     * subtrahend)}, and whose scale is {@code max(this.scale(),
jaroslav@1258
  1261
     * subtrahend.scale())}.
jaroslav@1258
  1262
     *
jaroslav@1258
  1263
     * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
jaroslav@1258
  1264
     * @return {@code this - subtrahend}
jaroslav@1258
  1265
     */
jaroslav@1258
  1266
    public BigDecimal subtract(BigDecimal subtrahend) {
jaroslav@1258
  1267
        return add(subtrahend.negate());
jaroslav@1258
  1268
    }
jaroslav@1258
  1269
jaroslav@1258
  1270
    /**
jaroslav@1258
  1271
     * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
jaroslav@1258
  1272
     * with rounding according to the context settings.
jaroslav@1258
  1273
     *
jaroslav@1258
  1274
     * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
jaroslav@1258
  1275
     * result.  If this is zero then the result is {@code subtrahend.negate(mc)}.
jaroslav@1258
  1276
     *
jaroslav@1258
  1277
     * @param  subtrahend value to be subtracted from this {@code BigDecimal}.
jaroslav@1258
  1278
     * @param  mc the context to use.
jaroslav@1258
  1279
     * @return {@code this - subtrahend}, rounded as necessary.
jaroslav@1258
  1280
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1281
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  1282
     * @since  1.5
jaroslav@1258
  1283
     */
jaroslav@1258
  1284
    public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
jaroslav@1258
  1285
        BigDecimal nsubtrahend = subtrahend.negate();
jaroslav@1258
  1286
        if (mc.precision == 0)
jaroslav@1258
  1287
            return add(nsubtrahend);
jaroslav@1258
  1288
        // share the special rounding code in add()
jaroslav@1258
  1289
        return add(nsubtrahend, mc);
jaroslav@1258
  1290
    }
jaroslav@1258
  1291
jaroslav@1258
  1292
    /**
jaroslav@1258
  1293
     * Returns a {@code BigDecimal} whose value is <tt>(this &times;
jaroslav@1258
  1294
     * multiplicand)</tt>, and whose scale is {@code (this.scale() +
jaroslav@1258
  1295
     * multiplicand.scale())}.
jaroslav@1258
  1296
     *
jaroslav@1258
  1297
     * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
jaroslav@1258
  1298
     * @return {@code this * multiplicand}
jaroslav@1258
  1299
     */
jaroslav@1258
  1300
    public BigDecimal multiply(BigDecimal multiplicand) {
jaroslav@1258
  1301
        long x = this.intCompact;
jaroslav@1258
  1302
        long y = multiplicand.intCompact;
jaroslav@1258
  1303
        int productScale = checkScale((long)scale + multiplicand.scale);
jaroslav@1258
  1304
jaroslav@1258
  1305
        // Might be able to do a more clever check incorporating the
jaroslav@1258
  1306
        // inflated check into the overflow computation.
jaroslav@1258
  1307
        if (x != INFLATED && y != INFLATED) {
jaroslav@1258
  1308
            /*
jaroslav@1258
  1309
             * If the product is not an overflowed value, continue
jaroslav@1258
  1310
             * to use the compact representation.  if either of x or y
jaroslav@1258
  1311
             * is INFLATED, the product should also be regarded as
jaroslav@1258
  1312
             * an overflow. Before using the overflow test suggested in
jaroslav@1258
  1313
             * "Hacker's Delight" section 2-12, we perform quick checks
jaroslav@1258
  1314
             * using the precision information to see whether the overflow
jaroslav@1258
  1315
             * would occur since division is expensive on most CPUs.
jaroslav@1258
  1316
             */
jaroslav@1258
  1317
            long product = x * y;
jaroslav@1258
  1318
            long prec = this.precision() + multiplicand.precision();
jaroslav@1258
  1319
            if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
jaroslav@1258
  1320
                return BigDecimal.valueOf(product, productScale);
jaroslav@1258
  1321
            return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
jaroslav@1258
  1322
                                  productScale, 0);
jaroslav@1258
  1323
        }
jaroslav@1258
  1324
        BigInteger rb;
jaroslav@1258
  1325
        if (x == INFLATED && y == INFLATED)
jaroslav@1258
  1326
            rb = this.intVal.multiply(multiplicand.intVal);
jaroslav@1258
  1327
        else if (x != INFLATED)
jaroslav@1258
  1328
            rb = multiplicand.intVal.multiply(x);
jaroslav@1258
  1329
        else
jaroslav@1258
  1330
            rb = this.intVal.multiply(y);
jaroslav@1258
  1331
        return new BigDecimal(rb, INFLATED, productScale, 0);
jaroslav@1258
  1332
    }
jaroslav@1258
  1333
jaroslav@1258
  1334
    /**
jaroslav@1258
  1335
     * Returns a {@code BigDecimal} whose value is <tt>(this &times;
jaroslav@1258
  1336
     * multiplicand)</tt>, with rounding according to the context settings.
jaroslav@1258
  1337
     *
jaroslav@1258
  1338
     * @param  multiplicand value to be multiplied by this {@code BigDecimal}.
jaroslav@1258
  1339
     * @param  mc the context to use.
jaroslav@1258
  1340
     * @return {@code this * multiplicand}, rounded as necessary.
jaroslav@1258
  1341
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1342
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  1343
     * @since  1.5
jaroslav@1258
  1344
     */
jaroslav@1258
  1345
    public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
jaroslav@1258
  1346
        if (mc.precision == 0)
jaroslav@1258
  1347
            return multiply(multiplicand);
jaroslav@1258
  1348
        return doRound(this.multiply(multiplicand), mc);
jaroslav@1258
  1349
    }
jaroslav@1258
  1350
jaroslav@1258
  1351
    /**
jaroslav@1258
  1352
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1353
     * divisor)}, and whose scale is as specified.  If rounding must
jaroslav@1258
  1354
     * be performed to generate a result with the specified scale, the
jaroslav@1258
  1355
     * specified rounding mode is applied.
jaroslav@1258
  1356
     *
jaroslav@1258
  1357
     * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
jaroslav@1258
  1358
     * should be used in preference to this legacy method.
jaroslav@1258
  1359
     *
jaroslav@1258
  1360
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1361
     * @param  scale scale of the {@code BigDecimal} quotient to be returned.
jaroslav@1258
  1362
     * @param  roundingMode rounding mode to apply.
jaroslav@1258
  1363
     * @return {@code this / divisor}
jaroslav@1258
  1364
     * @throws ArithmeticException if {@code divisor} is zero,
jaroslav@1258
  1365
     *         {@code roundingMode==ROUND_UNNECESSARY} and
jaroslav@1258
  1366
     *         the specified scale is insufficient to represent the result
jaroslav@1258
  1367
     *         of the division exactly.
jaroslav@1258
  1368
     * @throws IllegalArgumentException if {@code roundingMode} does not
jaroslav@1258
  1369
     *         represent a valid rounding mode.
jaroslav@1258
  1370
     * @see    #ROUND_UP
jaroslav@1258
  1371
     * @see    #ROUND_DOWN
jaroslav@1258
  1372
     * @see    #ROUND_CEILING
jaroslav@1258
  1373
     * @see    #ROUND_FLOOR
jaroslav@1258
  1374
     * @see    #ROUND_HALF_UP
jaroslav@1258
  1375
     * @see    #ROUND_HALF_DOWN
jaroslav@1258
  1376
     * @see    #ROUND_HALF_EVEN
jaroslav@1258
  1377
     * @see    #ROUND_UNNECESSARY
jaroslav@1258
  1378
     */
jaroslav@1258
  1379
    public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
jaroslav@1258
  1380
        /*
jaroslav@1258
  1381
         * IMPLEMENTATION NOTE: This method *must* return a new object
jaroslav@1258
  1382
         * since divideAndRound uses divide to generate a value whose
jaroslav@1258
  1383
         * scale is then modified.
jaroslav@1258
  1384
         */
jaroslav@1258
  1385
        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
jaroslav@1258
  1386
            throw new IllegalArgumentException("Invalid rounding mode");
jaroslav@1258
  1387
        /*
jaroslav@1258
  1388
         * Rescale dividend or divisor (whichever can be "upscaled" to
jaroslav@1258
  1389
         * produce correctly scaled quotient).
jaroslav@1258
  1390
         * Take care to detect out-of-range scales
jaroslav@1258
  1391
         */
jaroslav@1258
  1392
        BigDecimal dividend = this;
jaroslav@1258
  1393
        if (checkScale((long)scale + divisor.scale) > this.scale)
jaroslav@1258
  1394
            dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
jaroslav@1258
  1395
        else
jaroslav@1258
  1396
            divisor = divisor.setScale(checkScale((long)this.scale - scale),
jaroslav@1258
  1397
                                       ROUND_UNNECESSARY);
jaroslav@1258
  1398
        return divideAndRound(dividend.intCompact, dividend.intVal,
jaroslav@1258
  1399
                              divisor.intCompact, divisor.intVal,
jaroslav@1258
  1400
                              scale, roundingMode, scale);
jaroslav@1258
  1401
    }
jaroslav@1258
  1402
jaroslav@1258
  1403
    /**
jaroslav@1258
  1404
     * Internally used for division operation. The dividend and divisor are
jaroslav@1258
  1405
     * passed both in {@code long} format and {@code BigInteger} format. The
jaroslav@1258
  1406
     * returned {@code BigDecimal} object is the quotient whose scale is set to
jaroslav@1258
  1407
     * the passed in scale. If the remainder is not zero, it will be rounded
jaroslav@1258
  1408
     * based on the passed in roundingMode. Also, if the remainder is zero and
jaroslav@1258
  1409
     * the last parameter, i.e. preferredScale is NOT equal to scale, the
jaroslav@1258
  1410
     * trailing zeros of the result is stripped to match the preferredScale.
jaroslav@1258
  1411
     */
jaroslav@1258
  1412
    private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend,
jaroslav@1258
  1413
                                             long ldivisor,  BigInteger bdivisor,
jaroslav@1258
  1414
                                             int scale, int roundingMode,
jaroslav@1258
  1415
                                             int preferredScale) {
jaroslav@1258
  1416
        boolean isRemainderZero;       // record remainder is zero or not
jaroslav@1258
  1417
        int qsign;                     // quotient sign
jaroslav@1258
  1418
        long q = 0, r = 0;             // store quotient & remainder in long
jaroslav@1258
  1419
        MutableBigInteger mq = null;   // store quotient
jaroslav@1258
  1420
        MutableBigInteger mr = null;   // store remainder
jaroslav@1258
  1421
        MutableBigInteger mdivisor = null;
jaroslav@1258
  1422
        boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
jaroslav@1258
  1423
        if (isLongDivision) {
jaroslav@1258
  1424
            q = ldividend / ldivisor;
jaroslav@1258
  1425
            if (roundingMode == ROUND_DOWN && scale == preferredScale)
jaroslav@1258
  1426
                return new BigDecimal(null, q, scale, 0);
jaroslav@1258
  1427
            r = ldividend % ldivisor;
jaroslav@1258
  1428
            isRemainderZero = (r == 0);
jaroslav@1258
  1429
            qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
jaroslav@1258
  1430
        } else {
jaroslav@1258
  1431
            if (bdividend == null)
jaroslav@1258
  1432
                bdividend = BigInteger.valueOf(ldividend);
jaroslav@1258
  1433
            // Descend into mutables for faster remainder checks
jaroslav@1258
  1434
            MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
jaroslav@1258
  1435
            mq = new MutableBigInteger();
jaroslav@1258
  1436
            if (ldivisor != INFLATED) {
jaroslav@1258
  1437
                r = mdividend.divide(ldivisor, mq);
jaroslav@1258
  1438
                isRemainderZero = (r == 0);
jaroslav@1258
  1439
                qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
jaroslav@1258
  1440
            } else {
jaroslav@1258
  1441
                mdivisor = new MutableBigInteger(bdivisor.mag);
jaroslav@1258
  1442
                mr = mdividend.divide(mdivisor, mq);
jaroslav@1258
  1443
                isRemainderZero = mr.isZero();
jaroslav@1258
  1444
                qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
jaroslav@1258
  1445
            }
jaroslav@1258
  1446
        }
jaroslav@1258
  1447
        boolean increment = false;
jaroslav@1258
  1448
        if (!isRemainderZero) {
jaroslav@1258
  1449
            int cmpFracHalf;
jaroslav@1258
  1450
            /* Round as appropriate */
jaroslav@1258
  1451
            if (roundingMode == ROUND_UNNECESSARY) {  // Rounding prohibited
jaroslav@1258
  1452
                throw new ArithmeticException("Rounding necessary");
jaroslav@1258
  1453
            } else if (roundingMode == ROUND_UP) {      // Away from zero
jaroslav@1258
  1454
                increment = true;
jaroslav@1258
  1455
            } else if (roundingMode == ROUND_DOWN) {    // Towards zero
jaroslav@1258
  1456
                increment = false;
jaroslav@1258
  1457
            } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
jaroslav@1258
  1458
                increment = (qsign > 0);
jaroslav@1258
  1459
            } else if (roundingMode == ROUND_FLOOR) {   // Towards -infinity
jaroslav@1258
  1460
                increment = (qsign < 0);
jaroslav@1258
  1461
            } else {
jaroslav@1258
  1462
                if (isLongDivision || ldivisor != INFLATED) {
jaroslav@1258
  1463
                    if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
jaroslav@1258
  1464
                        cmpFracHalf = 1;    // 2 * r can't fit into long
jaroslav@1258
  1465
                    } else {
jaroslav@1258
  1466
                        cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
jaroslav@1258
  1467
                    }
jaroslav@1258
  1468
                } else {
jaroslav@1258
  1469
                    cmpFracHalf = mr.compareHalf(mdivisor);
jaroslav@1258
  1470
                }
jaroslav@1258
  1471
                if (cmpFracHalf < 0)
jaroslav@1258
  1472
                    increment = false;     // We're closer to higher digit
jaroslav@1258
  1473
                else if (cmpFracHalf > 0)  // We're closer to lower digit
jaroslav@1258
  1474
                    increment = true;
jaroslav@1258
  1475
                else if (roundingMode == ROUND_HALF_UP)
jaroslav@1258
  1476
                    increment = true;
jaroslav@1258
  1477
                else if (roundingMode == ROUND_HALF_DOWN)
jaroslav@1258
  1478
                    increment = false;
jaroslav@1258
  1479
                else  // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
jaroslav@1258
  1480
                    increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
jaroslav@1258
  1481
            }
jaroslav@1258
  1482
        }
jaroslav@1258
  1483
        BigDecimal res;
jaroslav@1258
  1484
        if (isLongDivision)
jaroslav@1258
  1485
            res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
jaroslav@1258
  1486
        else {
jaroslav@1258
  1487
            if (increment)
jaroslav@1258
  1488
                mq.add(MutableBigInteger.ONE);
jaroslav@1258
  1489
            res = mq.toBigDecimal(qsign, scale);
jaroslav@1258
  1490
        }
jaroslav@1258
  1491
        if (isRemainderZero && preferredScale != scale)
jaroslav@1258
  1492
            res.stripZerosToMatchScale(preferredScale);
jaroslav@1258
  1493
        return res;
jaroslav@1258
  1494
    }
jaroslav@1258
  1495
jaroslav@1258
  1496
    /**
jaroslav@1258
  1497
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1498
     * divisor)}, and whose scale is as specified.  If rounding must
jaroslav@1258
  1499
     * be performed to generate a result with the specified scale, the
jaroslav@1258
  1500
     * specified rounding mode is applied.
jaroslav@1258
  1501
     *
jaroslav@1258
  1502
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1503
     * @param  scale scale of the {@code BigDecimal} quotient to be returned.
jaroslav@1258
  1504
     * @param  roundingMode rounding mode to apply.
jaroslav@1258
  1505
     * @return {@code this / divisor}
jaroslav@1258
  1506
     * @throws ArithmeticException if {@code divisor} is zero,
jaroslav@1258
  1507
     *         {@code roundingMode==RoundingMode.UNNECESSARY} and
jaroslav@1258
  1508
     *         the specified scale is insufficient to represent the result
jaroslav@1258
  1509
     *         of the division exactly.
jaroslav@1258
  1510
     * @since 1.5
jaroslav@1258
  1511
     */
jaroslav@1258
  1512
    public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
jaroslav@1258
  1513
        return divide(divisor, scale, roundingMode.oldMode);
jaroslav@1258
  1514
    }
jaroslav@1258
  1515
jaroslav@1258
  1516
    /**
jaroslav@1258
  1517
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1518
     * divisor)}, and whose scale is {@code this.scale()}.  If
jaroslav@1258
  1519
     * rounding must be performed to generate a result with the given
jaroslav@1258
  1520
     * scale, the specified rounding mode is applied.
jaroslav@1258
  1521
     *
jaroslav@1258
  1522
     * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
jaroslav@1258
  1523
     * should be used in preference to this legacy method.
jaroslav@1258
  1524
     *
jaroslav@1258
  1525
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1526
     * @param  roundingMode rounding mode to apply.
jaroslav@1258
  1527
     * @return {@code this / divisor}
jaroslav@1258
  1528
     * @throws ArithmeticException if {@code divisor==0}, or
jaroslav@1258
  1529
     *         {@code roundingMode==ROUND_UNNECESSARY} and
jaroslav@1258
  1530
     *         {@code this.scale()} is insufficient to represent the result
jaroslav@1258
  1531
     *         of the division exactly.
jaroslav@1258
  1532
     * @throws IllegalArgumentException if {@code roundingMode} does not
jaroslav@1258
  1533
     *         represent a valid rounding mode.
jaroslav@1258
  1534
     * @see    #ROUND_UP
jaroslav@1258
  1535
     * @see    #ROUND_DOWN
jaroslav@1258
  1536
     * @see    #ROUND_CEILING
jaroslav@1258
  1537
     * @see    #ROUND_FLOOR
jaroslav@1258
  1538
     * @see    #ROUND_HALF_UP
jaroslav@1258
  1539
     * @see    #ROUND_HALF_DOWN
jaroslav@1258
  1540
     * @see    #ROUND_HALF_EVEN
jaroslav@1258
  1541
     * @see    #ROUND_UNNECESSARY
jaroslav@1258
  1542
     */
jaroslav@1258
  1543
    public BigDecimal divide(BigDecimal divisor, int roundingMode) {
jaroslav@1258
  1544
            return this.divide(divisor, scale, roundingMode);
jaroslav@1258
  1545
    }
jaroslav@1258
  1546
jaroslav@1258
  1547
    /**
jaroslav@1258
  1548
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1549
     * divisor)}, and whose scale is {@code this.scale()}.  If
jaroslav@1258
  1550
     * rounding must be performed to generate a result with the given
jaroslav@1258
  1551
     * scale, the specified rounding mode is applied.
jaroslav@1258
  1552
     *
jaroslav@1258
  1553
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1554
     * @param  roundingMode rounding mode to apply.
jaroslav@1258
  1555
     * @return {@code this / divisor}
jaroslav@1258
  1556
     * @throws ArithmeticException if {@code divisor==0}, or
jaroslav@1258
  1557
     *         {@code roundingMode==RoundingMode.UNNECESSARY} and
jaroslav@1258
  1558
     *         {@code this.scale()} is insufficient to represent the result
jaroslav@1258
  1559
     *         of the division exactly.
jaroslav@1258
  1560
     * @since 1.5
jaroslav@1258
  1561
     */
jaroslav@1258
  1562
    public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
jaroslav@1258
  1563
        return this.divide(divisor, scale, roundingMode.oldMode);
jaroslav@1258
  1564
    }
jaroslav@1258
  1565
jaroslav@1258
  1566
    /**
jaroslav@1258
  1567
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1568
     * divisor)}, and whose preferred scale is {@code (this.scale() -
jaroslav@1258
  1569
     * divisor.scale())}; if the exact quotient cannot be
jaroslav@1258
  1570
     * represented (because it has a non-terminating decimal
jaroslav@1258
  1571
     * expansion) an {@code ArithmeticException} is thrown.
jaroslav@1258
  1572
     *
jaroslav@1258
  1573
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1574
     * @throws ArithmeticException if the exact quotient does not have a
jaroslav@1258
  1575
     *         terminating decimal expansion
jaroslav@1258
  1576
     * @return {@code this / divisor}
jaroslav@1258
  1577
     * @since 1.5
jaroslav@1258
  1578
     * @author Joseph D. Darcy
jaroslav@1258
  1579
     */
jaroslav@1258
  1580
    public BigDecimal divide(BigDecimal divisor) {
jaroslav@1258
  1581
        /*
jaroslav@1258
  1582
         * Handle zero cases first.
jaroslav@1258
  1583
         */
jaroslav@1258
  1584
        if (divisor.signum() == 0) {   // x/0
jaroslav@1258
  1585
            if (this.signum() == 0)    // 0/0
jaroslav@1258
  1586
                throw new ArithmeticException("Division undefined");  // NaN
jaroslav@1258
  1587
            throw new ArithmeticException("Division by zero");
jaroslav@1258
  1588
        }
jaroslav@1258
  1589
jaroslav@1258
  1590
        // Calculate preferred scale
jaroslav@1258
  1591
        int preferredScale = saturateLong((long)this.scale - divisor.scale);
jaroslav@1258
  1592
        if (this.signum() == 0)        // 0/y
jaroslav@1258
  1593
            return (preferredScale >= 0 &&
jaroslav@1258
  1594
                    preferredScale < ZERO_SCALED_BY.length) ?
jaroslav@1258
  1595
                ZERO_SCALED_BY[preferredScale] :
jaroslav@1258
  1596
                BigDecimal.valueOf(0, preferredScale);
jaroslav@1258
  1597
        else {
jaroslav@1258
  1598
            this.inflate();
jaroslav@1258
  1599
            divisor.inflate();
jaroslav@1258
  1600
            /*
jaroslav@1258
  1601
             * If the quotient this/divisor has a terminating decimal
jaroslav@1258
  1602
             * expansion, the expansion can have no more than
jaroslav@1258
  1603
             * (a.precision() + ceil(10*b.precision)/3) digits.
jaroslav@1258
  1604
             * Therefore, create a MathContext object with this
jaroslav@1258
  1605
             * precision and do a divide with the UNNECESSARY rounding
jaroslav@1258
  1606
             * mode.
jaroslav@1258
  1607
             */
jaroslav@1258
  1608
            MathContext mc = new MathContext( (int)Math.min(this.precision() +
jaroslav@1258
  1609
                                                            (long)Math.ceil(10.0*divisor.precision()/3.0),
jaroslav@1258
  1610
                                                            Integer.MAX_VALUE),
jaroslav@1258
  1611
                                              RoundingMode.UNNECESSARY);
jaroslav@1258
  1612
            BigDecimal quotient;
jaroslav@1258
  1613
            try {
jaroslav@1258
  1614
                quotient = this.divide(divisor, mc);
jaroslav@1258
  1615
            } catch (ArithmeticException e) {
jaroslav@1258
  1616
                throw new ArithmeticException("Non-terminating decimal expansion; " +
jaroslav@1258
  1617
                                              "no exact representable decimal result.");
jaroslav@1258
  1618
            }
jaroslav@1258
  1619
jaroslav@1258
  1620
            int quotientScale = quotient.scale();
jaroslav@1258
  1621
jaroslav@1258
  1622
            // divide(BigDecimal, mc) tries to adjust the quotient to
jaroslav@1258
  1623
            // the desired one by removing trailing zeros; since the
jaroslav@1258
  1624
            // exact divide method does not have an explicit digit
jaroslav@1258
  1625
            // limit, we can add zeros too.
jaroslav@1258
  1626
jaroslav@1258
  1627
            if (preferredScale > quotientScale)
jaroslav@1258
  1628
                return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
jaroslav@1258
  1629
jaroslav@1258
  1630
            return quotient;
jaroslav@1258
  1631
        }
jaroslav@1258
  1632
    }
jaroslav@1258
  1633
jaroslav@1258
  1634
    /**
jaroslav@1258
  1635
     * Returns a {@code BigDecimal} whose value is {@code (this /
jaroslav@1258
  1636
     * divisor)}, with rounding according to the context settings.
jaroslav@1258
  1637
     *
jaroslav@1258
  1638
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1639
     * @param  mc the context to use.
jaroslav@1258
  1640
     * @return {@code this / divisor}, rounded as necessary.
jaroslav@1258
  1641
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1642
     *         rounding mode is {@code UNNECESSARY} or
jaroslav@1258
  1643
     *         {@code mc.precision == 0} and the quotient has a
jaroslav@1258
  1644
     *         non-terminating decimal expansion.
jaroslav@1258
  1645
     * @since  1.5
jaroslav@1258
  1646
     */
jaroslav@1258
  1647
    public BigDecimal divide(BigDecimal divisor, MathContext mc) {
jaroslav@1258
  1648
        int mcp = mc.precision;
jaroslav@1258
  1649
        if (mcp == 0)
jaroslav@1258
  1650
            return divide(divisor);
jaroslav@1258
  1651
jaroslav@1258
  1652
        BigDecimal dividend = this;
jaroslav@1258
  1653
        long preferredScale = (long)dividend.scale - divisor.scale;
jaroslav@1258
  1654
        // Now calculate the answer.  We use the existing
jaroslav@1258
  1655
        // divide-and-round method, but as this rounds to scale we have
jaroslav@1258
  1656
        // to normalize the values here to achieve the desired result.
jaroslav@1258
  1657
        // For x/y we first handle y=0 and x=0, and then normalize x and
jaroslav@1258
  1658
        // y to give x' and y' with the following constraints:
jaroslav@1258
  1659
        //   (a) 0.1 <= x' < 1
jaroslav@1258
  1660
        //   (b)  x' <= y' < 10*x'
jaroslav@1258
  1661
        // Dividing x'/y' with the required scale set to mc.precision then
jaroslav@1258
  1662
        // will give a result in the range 0.1 to 1 rounded to exactly
jaroslav@1258
  1663
        // the right number of digits (except in the case of a result of
jaroslav@1258
  1664
        // 1.000... which can arise when x=y, or when rounding overflows
jaroslav@1258
  1665
        // The 1.000... case will reduce properly to 1.
jaroslav@1258
  1666
        if (divisor.signum() == 0) {      // x/0
jaroslav@1258
  1667
            if (dividend.signum() == 0)    // 0/0
jaroslav@1258
  1668
                throw new ArithmeticException("Division undefined");  // NaN
jaroslav@1258
  1669
            throw new ArithmeticException("Division by zero");
jaroslav@1258
  1670
        }
jaroslav@1258
  1671
        if (dividend.signum() == 0)        // 0/y
jaroslav@1258
  1672
            return new BigDecimal(BigInteger.ZERO, 0,
jaroslav@1258
  1673
                                  saturateLong(preferredScale), 1);
jaroslav@1258
  1674
jaroslav@1258
  1675
        // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
jaroslav@1258
  1676
        int xscale = dividend.precision();
jaroslav@1258
  1677
        int yscale = divisor.precision();
jaroslav@1258
  1678
        dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
jaroslav@1258
  1679
                                  xscale, xscale);
jaroslav@1258
  1680
        divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
jaroslav@1258
  1681
                                 yscale, yscale);
jaroslav@1258
  1682
        if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
jaroslav@1258
  1683
            yscale = divisor.scale -= 1;            // [that is, divisor *= 10]
jaroslav@1258
  1684
jaroslav@1258
  1685
        // In order to find out whether the divide generates the exact result,
jaroslav@1258
  1686
        // we avoid calling the above divide method. 'quotient' holds the
jaroslav@1258
  1687
        // return BigDecimal object whose scale will be set to 'scl'.
jaroslav@1258
  1688
        BigDecimal quotient;
jaroslav@1258
  1689
        int scl = checkScale(preferredScale + yscale - xscale + mcp);
jaroslav@1258
  1690
        if (checkScale((long)mcp + yscale) > xscale)
jaroslav@1258
  1691
            dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
jaroslav@1258
  1692
        else
jaroslav@1258
  1693
            divisor = divisor.setScale(checkScale((long)xscale - mcp),
jaroslav@1258
  1694
                                       ROUND_UNNECESSARY);
jaroslav@1258
  1695
        quotient = divideAndRound(dividend.intCompact, dividend.intVal,
jaroslav@1258
  1696
                                  divisor.intCompact, divisor.intVal,
jaroslav@1258
  1697
                                  scl, mc.roundingMode.oldMode,
jaroslav@1258
  1698
                                  checkScale(preferredScale));
jaroslav@1258
  1699
        // doRound, here, only affects 1000000000 case.
jaroslav@1258
  1700
        quotient = doRound(quotient, mc);
jaroslav@1258
  1701
jaroslav@1258
  1702
        return quotient;
jaroslav@1258
  1703
    }
jaroslav@1258
  1704
jaroslav@1258
  1705
    /**
jaroslav@1258
  1706
     * Returns a {@code BigDecimal} whose value is the integer part
jaroslav@1258
  1707
     * of the quotient {@code (this / divisor)} rounded down.  The
jaroslav@1258
  1708
     * preferred scale of the result is {@code (this.scale() -
jaroslav@1258
  1709
     * divisor.scale())}.
jaroslav@1258
  1710
     *
jaroslav@1258
  1711
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1712
     * @return The integer part of {@code this / divisor}.
jaroslav@1258
  1713
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1714
     * @since  1.5
jaroslav@1258
  1715
     */
jaroslav@1258
  1716
    public BigDecimal divideToIntegralValue(BigDecimal divisor) {
jaroslav@1258
  1717
        // Calculate preferred scale
jaroslav@1258
  1718
        int preferredScale = saturateLong((long)this.scale - divisor.scale);
jaroslav@1258
  1719
        if (this.compareMagnitude(divisor) < 0) {
jaroslav@1258
  1720
            // much faster when this << divisor
jaroslav@1258
  1721
            return BigDecimal.valueOf(0, preferredScale);
jaroslav@1258
  1722
        }
jaroslav@1258
  1723
jaroslav@1258
  1724
        if(this.signum() == 0 && divisor.signum() != 0)
jaroslav@1258
  1725
            return this.setScale(preferredScale, ROUND_UNNECESSARY);
jaroslav@1258
  1726
jaroslav@1258
  1727
        // Perform a divide with enough digits to round to a correct
jaroslav@1258
  1728
        // integer value; then remove any fractional digits
jaroslav@1258
  1729
jaroslav@1258
  1730
        int maxDigits = (int)Math.min(this.precision() +
jaroslav@1258
  1731
                                      (long)Math.ceil(10.0*divisor.precision()/3.0) +
jaroslav@1258
  1732
                                      Math.abs((long)this.scale() - divisor.scale()) + 2,
jaroslav@1258
  1733
                                      Integer.MAX_VALUE);
jaroslav@1258
  1734
        BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
jaroslav@1258
  1735
                                                                   RoundingMode.DOWN));
jaroslav@1258
  1736
        if (quotient.scale > 0) {
jaroslav@1258
  1737
            quotient = quotient.setScale(0, RoundingMode.DOWN);
jaroslav@1258
  1738
            quotient.stripZerosToMatchScale(preferredScale);
jaroslav@1258
  1739
        }
jaroslav@1258
  1740
jaroslav@1258
  1741
        if (quotient.scale < preferredScale) {
jaroslav@1258
  1742
            // pad with zeros if necessary
jaroslav@1258
  1743
            quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
jaroslav@1258
  1744
        }
jaroslav@1258
  1745
        return quotient;
jaroslav@1258
  1746
    }
jaroslav@1258
  1747
jaroslav@1258
  1748
    /**
jaroslav@1258
  1749
     * Returns a {@code BigDecimal} whose value is the integer part
jaroslav@1258
  1750
     * of {@code (this / divisor)}.  Since the integer part of the
jaroslav@1258
  1751
     * exact quotient does not depend on the rounding mode, the
jaroslav@1258
  1752
     * rounding mode does not affect the values returned by this
jaroslav@1258
  1753
     * method.  The preferred scale of the result is
jaroslav@1258
  1754
     * {@code (this.scale() - divisor.scale())}.  An
jaroslav@1258
  1755
     * {@code ArithmeticException} is thrown if the integer part of
jaroslav@1258
  1756
     * the exact quotient needs more than {@code mc.precision}
jaroslav@1258
  1757
     * digits.
jaroslav@1258
  1758
     *
jaroslav@1258
  1759
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1760
     * @param  mc the context to use.
jaroslav@1258
  1761
     * @return The integer part of {@code this / divisor}.
jaroslav@1258
  1762
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1763
     * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
jaroslav@1258
  1764
     *         requires a precision of more than {@code mc.precision} digits.
jaroslav@1258
  1765
     * @since  1.5
jaroslav@1258
  1766
     * @author Joseph D. Darcy
jaroslav@1258
  1767
     */
jaroslav@1258
  1768
    public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
jaroslav@1258
  1769
        if (mc.precision == 0 ||                        // exact result
jaroslav@1258
  1770
            (this.compareMagnitude(divisor) < 0) )      // zero result
jaroslav@1258
  1771
            return divideToIntegralValue(divisor);
jaroslav@1258
  1772
jaroslav@1258
  1773
        // Calculate preferred scale
jaroslav@1258
  1774
        int preferredScale = saturateLong((long)this.scale - divisor.scale);
jaroslav@1258
  1775
jaroslav@1258
  1776
        /*
jaroslav@1258
  1777
         * Perform a normal divide to mc.precision digits.  If the
jaroslav@1258
  1778
         * remainder has absolute value less than the divisor, the
jaroslav@1258
  1779
         * integer portion of the quotient fits into mc.precision
jaroslav@1258
  1780
         * digits.  Next, remove any fractional digits from the
jaroslav@1258
  1781
         * quotient and adjust the scale to the preferred value.
jaroslav@1258
  1782
         */
jaroslav@1258
  1783
        BigDecimal result = this.
jaroslav@1258
  1784
            divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
jaroslav@1258
  1785
jaroslav@1258
  1786
        if (result.scale() < 0) {
jaroslav@1258
  1787
            /*
jaroslav@1258
  1788
             * Result is an integer. See if quotient represents the
jaroslav@1258
  1789
             * full integer portion of the exact quotient; if it does,
jaroslav@1258
  1790
             * the computed remainder will be less than the divisor.
jaroslav@1258
  1791
             */
jaroslav@1258
  1792
            BigDecimal product = result.multiply(divisor);
jaroslav@1258
  1793
            // If the quotient is the full integer value,
jaroslav@1258
  1794
            // |dividend-product| < |divisor|.
jaroslav@1258
  1795
            if (this.subtract(product).compareMagnitude(divisor) >= 0) {
jaroslav@1258
  1796
                throw new ArithmeticException("Division impossible");
jaroslav@1258
  1797
            }
jaroslav@1258
  1798
        } else if (result.scale() > 0) {
jaroslav@1258
  1799
            /*
jaroslav@1258
  1800
             * Integer portion of quotient will fit into precision
jaroslav@1258
  1801
             * digits; recompute quotient to scale 0 to avoid double
jaroslav@1258
  1802
             * rounding and then try to adjust, if necessary.
jaroslav@1258
  1803
             */
jaroslav@1258
  1804
            result = result.setScale(0, RoundingMode.DOWN);
jaroslav@1258
  1805
        }
jaroslav@1258
  1806
        // else result.scale() == 0;
jaroslav@1258
  1807
jaroslav@1258
  1808
        int precisionDiff;
jaroslav@1258
  1809
        if ((preferredScale > result.scale()) &&
jaroslav@1258
  1810
            (precisionDiff = mc.precision - result.precision()) > 0) {
jaroslav@1258
  1811
            return result.setScale(result.scale() +
jaroslav@1258
  1812
                                   Math.min(precisionDiff, preferredScale - result.scale) );
jaroslav@1258
  1813
        } else {
jaroslav@1258
  1814
            result.stripZerosToMatchScale(preferredScale);
jaroslav@1258
  1815
            return result;
jaroslav@1258
  1816
        }
jaroslav@1258
  1817
    }
jaroslav@1258
  1818
jaroslav@1258
  1819
    /**
jaroslav@1258
  1820
     * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
jaroslav@1258
  1821
     *
jaroslav@1258
  1822
     * <p>The remainder is given by
jaroslav@1258
  1823
     * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
jaroslav@1258
  1824
     * Note that this is not the modulo operation (the result can be
jaroslav@1258
  1825
     * negative).
jaroslav@1258
  1826
     *
jaroslav@1258
  1827
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1828
     * @return {@code this % divisor}.
jaroslav@1258
  1829
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1830
     * @since  1.5
jaroslav@1258
  1831
     */
jaroslav@1258
  1832
    public BigDecimal remainder(BigDecimal divisor) {
jaroslav@1258
  1833
        BigDecimal divrem[] = this.divideAndRemainder(divisor);
jaroslav@1258
  1834
        return divrem[1];
jaroslav@1258
  1835
    }
jaroslav@1258
  1836
jaroslav@1258
  1837
jaroslav@1258
  1838
    /**
jaroslav@1258
  1839
     * Returns a {@code BigDecimal} whose value is {@code (this %
jaroslav@1258
  1840
     * divisor)}, with rounding according to the context settings.
jaroslav@1258
  1841
     * The {@code MathContext} settings affect the implicit divide
jaroslav@1258
  1842
     * used to compute the remainder.  The remainder computation
jaroslav@1258
  1843
     * itself is by definition exact.  Therefore, the remainder may
jaroslav@1258
  1844
     * contain more than {@code mc.getPrecision()} digits.
jaroslav@1258
  1845
     *
jaroslav@1258
  1846
     * <p>The remainder is given by
jaroslav@1258
  1847
     * {@code this.subtract(this.divideToIntegralValue(divisor,
jaroslav@1258
  1848
     * mc).multiply(divisor))}.  Note that this is not the modulo
jaroslav@1258
  1849
     * operation (the result can be negative).
jaroslav@1258
  1850
     *
jaroslav@1258
  1851
     * @param  divisor value by which this {@code BigDecimal} is to be divided.
jaroslav@1258
  1852
     * @param  mc the context to use.
jaroslav@1258
  1853
     * @return {@code this % divisor}, rounded as necessary.
jaroslav@1258
  1854
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1855
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1856
     *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
jaroslav@1258
  1857
     *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
jaroslav@1258
  1858
     *         require a precision of more than {@code mc.precision} digits.
jaroslav@1258
  1859
     * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
jaroslav@1258
  1860
     * @since  1.5
jaroslav@1258
  1861
     */
jaroslav@1258
  1862
    public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
jaroslav@1258
  1863
        BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
jaroslav@1258
  1864
        return divrem[1];
jaroslav@1258
  1865
    }
jaroslav@1258
  1866
jaroslav@1258
  1867
    /**
jaroslav@1258
  1868
     * Returns a two-element {@code BigDecimal} array containing the
jaroslav@1258
  1869
     * result of {@code divideToIntegralValue} followed by the result of
jaroslav@1258
  1870
     * {@code remainder} on the two operands.
jaroslav@1258
  1871
     *
jaroslav@1258
  1872
     * <p>Note that if both the integer quotient and remainder are
jaroslav@1258
  1873
     * needed, this method is faster than using the
jaroslav@1258
  1874
     * {@code divideToIntegralValue} and {@code remainder} methods
jaroslav@1258
  1875
     * separately because the division need only be carried out once.
jaroslav@1258
  1876
     *
jaroslav@1258
  1877
     * @param  divisor value by which this {@code BigDecimal} is to be divided,
jaroslav@1258
  1878
     *         and the remainder computed.
jaroslav@1258
  1879
     * @return a two element {@code BigDecimal} array: the quotient
jaroslav@1258
  1880
     *         (the result of {@code divideToIntegralValue}) is the initial element
jaroslav@1258
  1881
     *         and the remainder is the final element.
jaroslav@1258
  1882
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1883
     * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
jaroslav@1258
  1884
     * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
jaroslav@1258
  1885
     * @since  1.5
jaroslav@1258
  1886
     */
jaroslav@1258
  1887
    public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
jaroslav@1258
  1888
        // we use the identity  x = i * y + r to determine r
jaroslav@1258
  1889
        BigDecimal[] result = new BigDecimal[2];
jaroslav@1258
  1890
jaroslav@1258
  1891
        result[0] = this.divideToIntegralValue(divisor);
jaroslav@1258
  1892
        result[1] = this.subtract(result[0].multiply(divisor));
jaroslav@1258
  1893
        return result;
jaroslav@1258
  1894
    }
jaroslav@1258
  1895
jaroslav@1258
  1896
    /**
jaroslav@1258
  1897
     * Returns a two-element {@code BigDecimal} array containing the
jaroslav@1258
  1898
     * result of {@code divideToIntegralValue} followed by the result of
jaroslav@1258
  1899
     * {@code remainder} on the two operands calculated with rounding
jaroslav@1258
  1900
     * according to the context settings.
jaroslav@1258
  1901
     *
jaroslav@1258
  1902
     * <p>Note that if both the integer quotient and remainder are
jaroslav@1258
  1903
     * needed, this method is faster than using the
jaroslav@1258
  1904
     * {@code divideToIntegralValue} and {@code remainder} methods
jaroslav@1258
  1905
     * separately because the division need only be carried out once.
jaroslav@1258
  1906
     *
jaroslav@1258
  1907
     * @param  divisor value by which this {@code BigDecimal} is to be divided,
jaroslav@1258
  1908
     *         and the remainder computed.
jaroslav@1258
  1909
     * @param  mc the context to use.
jaroslav@1258
  1910
     * @return a two element {@code BigDecimal} array: the quotient
jaroslav@1258
  1911
     *         (the result of {@code divideToIntegralValue}) is the
jaroslav@1258
  1912
     *         initial element and the remainder is the final element.
jaroslav@1258
  1913
     * @throws ArithmeticException if {@code divisor==0}
jaroslav@1258
  1914
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  1915
     *         rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
jaroslav@1258
  1916
     *         {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
jaroslav@1258
  1917
     *         require a precision of more than {@code mc.precision} digits.
jaroslav@1258
  1918
     * @see    #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
jaroslav@1258
  1919
     * @see    #remainder(java.math.BigDecimal, java.math.MathContext)
jaroslav@1258
  1920
     * @since  1.5
jaroslav@1258
  1921
     */
jaroslav@1258
  1922
    public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
jaroslav@1258
  1923
        if (mc.precision == 0)
jaroslav@1258
  1924
            return divideAndRemainder(divisor);
jaroslav@1258
  1925
jaroslav@1258
  1926
        BigDecimal[] result = new BigDecimal[2];
jaroslav@1258
  1927
        BigDecimal lhs = this;
jaroslav@1258
  1928
jaroslav@1258
  1929
        result[0] = lhs.divideToIntegralValue(divisor, mc);
jaroslav@1258
  1930
        result[1] = lhs.subtract(result[0].multiply(divisor));
jaroslav@1258
  1931
        return result;
jaroslav@1258
  1932
    }
jaroslav@1258
  1933
jaroslav@1258
  1934
    /**
jaroslav@1258
  1935
     * Returns a {@code BigDecimal} whose value is
jaroslav@1258
  1936
     * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
jaroslav@1258
  1937
     * unlimited precision.
jaroslav@1258
  1938
     *
jaroslav@1258
  1939
     * <p>The parameter {@code n} must be in the range 0 through
jaroslav@1258
  1940
     * 999999999, inclusive.  {@code ZERO.pow(0)} returns {@link
jaroslav@1258
  1941
     * #ONE}.
jaroslav@1258
  1942
     *
jaroslav@1258
  1943
     * Note that future releases may expand the allowable exponent
jaroslav@1258
  1944
     * range of this method.
jaroslav@1258
  1945
     *
jaroslav@1258
  1946
     * @param  n power to raise this {@code BigDecimal} to.
jaroslav@1258
  1947
     * @return <tt>this<sup>n</sup></tt>
jaroslav@1258
  1948
     * @throws ArithmeticException if {@code n} is out of range.
jaroslav@1258
  1949
     * @since  1.5
jaroslav@1258
  1950
     */
jaroslav@1258
  1951
    public BigDecimal pow(int n) {
jaroslav@1258
  1952
        if (n < 0 || n > 999999999)
jaroslav@1258
  1953
            throw new ArithmeticException("Invalid operation");
jaroslav@1258
  1954
        // No need to calculate pow(n) if result will over/underflow.
jaroslav@1258
  1955
        // Don't attempt to support "supernormal" numbers.
jaroslav@1258
  1956
        int newScale = checkScale((long)scale * n);
jaroslav@1258
  1957
        this.inflate();
jaroslav@1258
  1958
        return new BigDecimal(intVal.pow(n), newScale);
jaroslav@1258
  1959
    }
jaroslav@1258
  1960
jaroslav@1258
  1961
jaroslav@1258
  1962
    /**
jaroslav@1258
  1963
     * Returns a {@code BigDecimal} whose value is
jaroslav@1258
  1964
     * <tt>(this<sup>n</sup>)</tt>.  The current implementation uses
jaroslav@1258
  1965
     * the core algorithm defined in ANSI standard X3.274-1996 with
jaroslav@1258
  1966
     * rounding according to the context settings.  In general, the
jaroslav@1258
  1967
     * returned numerical value is within two ulps of the exact
jaroslav@1258
  1968
     * numerical value for the chosen precision.  Note that future
jaroslav@1258
  1969
     * releases may use a different algorithm with a decreased
jaroslav@1258
  1970
     * allowable error bound and increased allowable exponent range.
jaroslav@1258
  1971
     *
jaroslav@1258
  1972
     * <p>The X3.274-1996 algorithm is:
jaroslav@1258
  1973
     *
jaroslav@1258
  1974
     * <ul>
jaroslav@1258
  1975
     * <li> An {@code ArithmeticException} exception is thrown if
jaroslav@1258
  1976
     *  <ul>
jaroslav@1258
  1977
     *    <li>{@code abs(n) > 999999999}
jaroslav@1258
  1978
     *    <li>{@code mc.precision == 0} and {@code n < 0}
jaroslav@1258
  1979
     *    <li>{@code mc.precision > 0} and {@code n} has more than
jaroslav@1258
  1980
     *    {@code mc.precision} decimal digits
jaroslav@1258
  1981
     *  </ul>
jaroslav@1258
  1982
     *
jaroslav@1258
  1983
     * <li> if {@code n} is zero, {@link #ONE} is returned even if
jaroslav@1258
  1984
     * {@code this} is zero, otherwise
jaroslav@1258
  1985
     * <ul>
jaroslav@1258
  1986
     *   <li> if {@code n} is positive, the result is calculated via
jaroslav@1258
  1987
     *   the repeated squaring technique into a single accumulator.
jaroslav@1258
  1988
     *   The individual multiplications with the accumulator use the
jaroslav@1258
  1989
     *   same math context settings as in {@code mc} except for a
jaroslav@1258
  1990
     *   precision increased to {@code mc.precision + elength + 1}
jaroslav@1258
  1991
     *   where {@code elength} is the number of decimal digits in
jaroslav@1258
  1992
     *   {@code n}.
jaroslav@1258
  1993
     *
jaroslav@1258
  1994
     *   <li> if {@code n} is negative, the result is calculated as if
jaroslav@1258
  1995
     *   {@code n} were positive; this value is then divided into one
jaroslav@1258
  1996
     *   using the working precision specified above.
jaroslav@1258
  1997
     *
jaroslav@1258
  1998
     *   <li> The final value from either the positive or negative case
jaroslav@1258
  1999
     *   is then rounded to the destination precision.
jaroslav@1258
  2000
     *   </ul>
jaroslav@1258
  2001
     * </ul>
jaroslav@1258
  2002
     *
jaroslav@1258
  2003
     * @param  n power to raise this {@code BigDecimal} to.
jaroslav@1258
  2004
     * @param  mc the context to use.
jaroslav@1258
  2005
     * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
jaroslav@1258
  2006
     *         algorithm
jaroslav@1258
  2007
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  2008
     *         rounding mode is {@code UNNECESSARY}, or {@code n} is out
jaroslav@1258
  2009
     *         of range.
jaroslav@1258
  2010
     * @since  1.5
jaroslav@1258
  2011
     */
jaroslav@1258
  2012
    public BigDecimal pow(int n, MathContext mc) {
jaroslav@1258
  2013
        if (mc.precision == 0)
jaroslav@1258
  2014
            return pow(n);
jaroslav@1258
  2015
        if (n < -999999999 || n > 999999999)
jaroslav@1258
  2016
            throw new ArithmeticException("Invalid operation");
jaroslav@1258
  2017
        if (n == 0)
jaroslav@1258
  2018
            return ONE;                      // x**0 == 1 in X3.274
jaroslav@1258
  2019
        this.inflate();
jaroslav@1258
  2020
        BigDecimal lhs = this;
jaroslav@1258
  2021
        MathContext workmc = mc;           // working settings
jaroslav@1258
  2022
        int mag = Math.abs(n);               // magnitude of n
jaroslav@1258
  2023
        if (mc.precision > 0) {
jaroslav@1258
  2024
jaroslav@1258
  2025
            int elength = longDigitLength(mag); // length of n in digits
jaroslav@1258
  2026
            if (elength > mc.precision)        // X3.274 rule
jaroslav@1258
  2027
                throw new ArithmeticException("Invalid operation");
jaroslav@1258
  2028
            workmc = new MathContext(mc.precision + elength + 1,
jaroslav@1258
  2029
                                      mc.roundingMode);
jaroslav@1258
  2030
        }
jaroslav@1258
  2031
        // ready to carry out power calculation...
jaroslav@1258
  2032
        BigDecimal acc = ONE;           // accumulator
jaroslav@1258
  2033
        boolean seenbit = false;        // set once we've seen a 1-bit
jaroslav@1258
  2034
        for (int i=1;;i++) {            // for each bit [top bit ignored]
jaroslav@1258
  2035
            mag += mag;                 // shift left 1 bit
jaroslav@1258
  2036
            if (mag < 0) {              // top bit is set
jaroslav@1258
  2037
                seenbit = true;         // OK, we're off
jaroslav@1258
  2038
                acc = acc.multiply(lhs, workmc); // acc=acc*x
jaroslav@1258
  2039
            }
jaroslav@1258
  2040
            if (i == 31)
jaroslav@1258
  2041
                break;                  // that was the last bit
jaroslav@1258
  2042
            if (seenbit)
jaroslav@1258
  2043
                acc=acc.multiply(acc, workmc);   // acc=acc*acc [square]
jaroslav@1258
  2044
                // else (!seenbit) no point in squaring ONE
jaroslav@1258
  2045
        }
jaroslav@1258
  2046
        // if negative n, calculate the reciprocal using working precision
jaroslav@1258
  2047
        if (n<0)                          // [hence mc.precision>0]
jaroslav@1258
  2048
            acc=ONE.divide(acc, workmc);
jaroslav@1258
  2049
        // round to final precision and strip zeros
jaroslav@1258
  2050
        return doRound(acc, mc);
jaroslav@1258
  2051
    }
jaroslav@1258
  2052
jaroslav@1258
  2053
    /**
jaroslav@1258
  2054
     * Returns a {@code BigDecimal} whose value is the absolute value
jaroslav@1258
  2055
     * of this {@code BigDecimal}, and whose scale is
jaroslav@1258
  2056
     * {@code this.scale()}.
jaroslav@1258
  2057
     *
jaroslav@1258
  2058
     * @return {@code abs(this)}
jaroslav@1258
  2059
     */
jaroslav@1258
  2060
    public BigDecimal abs() {
jaroslav@1258
  2061
        return (signum() < 0 ? negate() : this);
jaroslav@1258
  2062
    }
jaroslav@1258
  2063
jaroslav@1258
  2064
    /**
jaroslav@1258
  2065
     * Returns a {@code BigDecimal} whose value is the absolute value
jaroslav@1258
  2066
     * of this {@code BigDecimal}, with rounding according to the
jaroslav@1258
  2067
     * context settings.
jaroslav@1258
  2068
     *
jaroslav@1258
  2069
     * @param mc the context to use.
jaroslav@1258
  2070
     * @return {@code abs(this)}, rounded as necessary.
jaroslav@1258
  2071
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  2072
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  2073
     * @since 1.5
jaroslav@1258
  2074
     */
jaroslav@1258
  2075
    public BigDecimal abs(MathContext mc) {
jaroslav@1258
  2076
        return (signum() < 0 ? negate(mc) : plus(mc));
jaroslav@1258
  2077
    }
jaroslav@1258
  2078
jaroslav@1258
  2079
    /**
jaroslav@1258
  2080
     * Returns a {@code BigDecimal} whose value is {@code (-this)},
jaroslav@1258
  2081
     * and whose scale is {@code this.scale()}.
jaroslav@1258
  2082
     *
jaroslav@1258
  2083
     * @return {@code -this}.
jaroslav@1258
  2084
     */
jaroslav@1258
  2085
    public BigDecimal negate() {
jaroslav@1258
  2086
        BigDecimal result;
jaroslav@1258
  2087
        if (intCompact != INFLATED)
jaroslav@1258
  2088
            result = BigDecimal.valueOf(-intCompact, scale);
jaroslav@1258
  2089
        else {
jaroslav@1258
  2090
            result = new BigDecimal(intVal.negate(), scale);
jaroslav@1258
  2091
            result.precision = precision;
jaroslav@1258
  2092
        }
jaroslav@1258
  2093
        return result;
jaroslav@1258
  2094
    }
jaroslav@1258
  2095
jaroslav@1258
  2096
    /**
jaroslav@1258
  2097
     * Returns a {@code BigDecimal} whose value is {@code (-this)},
jaroslav@1258
  2098
     * with rounding according to the context settings.
jaroslav@1258
  2099
     *
jaroslav@1258
  2100
     * @param mc the context to use.
jaroslav@1258
  2101
     * @return {@code -this}, rounded as necessary.
jaroslav@1258
  2102
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  2103
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  2104
     * @since  1.5
jaroslav@1258
  2105
     */
jaroslav@1258
  2106
    public BigDecimal negate(MathContext mc) {
jaroslav@1258
  2107
        return negate().plus(mc);
jaroslav@1258
  2108
    }
jaroslav@1258
  2109
jaroslav@1258
  2110
    /**
jaroslav@1258
  2111
     * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
jaroslav@1258
  2112
     * scale is {@code this.scale()}.
jaroslav@1258
  2113
     *
jaroslav@1258
  2114
     * <p>This method, which simply returns this {@code BigDecimal}
jaroslav@1258
  2115
     * is included for symmetry with the unary minus method {@link
jaroslav@1258
  2116
     * #negate()}.
jaroslav@1258
  2117
     *
jaroslav@1258
  2118
     * @return {@code this}.
jaroslav@1258
  2119
     * @see #negate()
jaroslav@1258
  2120
     * @since  1.5
jaroslav@1258
  2121
     */
jaroslav@1258
  2122
    public BigDecimal plus() {
jaroslav@1258
  2123
        return this;
jaroslav@1258
  2124
    }
jaroslav@1258
  2125
jaroslav@1258
  2126
    /**
jaroslav@1258
  2127
     * Returns a {@code BigDecimal} whose value is {@code (+this)},
jaroslav@1258
  2128
     * with rounding according to the context settings.
jaroslav@1258
  2129
     *
jaroslav@1258
  2130
     * <p>The effect of this method is identical to that of the {@link
jaroslav@1258
  2131
     * #round(MathContext)} method.
jaroslav@1258
  2132
     *
jaroslav@1258
  2133
     * @param mc the context to use.
jaroslav@1258
  2134
     * @return {@code this}, rounded as necessary.  A zero result will
jaroslav@1258
  2135
     *         have a scale of 0.
jaroslav@1258
  2136
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  2137
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  2138
     * @see    #round(MathContext)
jaroslav@1258
  2139
     * @since  1.5
jaroslav@1258
  2140
     */
jaroslav@1258
  2141
    public BigDecimal plus(MathContext mc) {
jaroslav@1258
  2142
        if (mc.precision == 0)                 // no rounding please
jaroslav@1258
  2143
            return this;
jaroslav@1258
  2144
        return doRound(this, mc);
jaroslav@1258
  2145
    }
jaroslav@1258
  2146
jaroslav@1258
  2147
    /**
jaroslav@1258
  2148
     * Returns the signum function of this {@code BigDecimal}.
jaroslav@1258
  2149
     *
jaroslav@1258
  2150
     * @return -1, 0, or 1 as the value of this {@code BigDecimal}
jaroslav@1258
  2151
     *         is negative, zero, or positive.
jaroslav@1258
  2152
     */
jaroslav@1258
  2153
    public int signum() {
jaroslav@1258
  2154
        return (intCompact != INFLATED)?
jaroslav@1258
  2155
            Long.signum(intCompact):
jaroslav@1258
  2156
            intVal.signum();
jaroslav@1258
  2157
    }
jaroslav@1258
  2158
jaroslav@1258
  2159
    /**
jaroslav@1258
  2160
     * Returns the <i>scale</i> of this {@code BigDecimal}.  If zero
jaroslav@1258
  2161
     * or positive, the scale is the number of digits to the right of
jaroslav@1258
  2162
     * the decimal point.  If negative, the unscaled value of the
jaroslav@1258
  2163
     * number is multiplied by ten to the power of the negation of the
jaroslav@1258
  2164
     * scale.  For example, a scale of {@code -3} means the unscaled
jaroslav@1258
  2165
     * value is multiplied by 1000.
jaroslav@1258
  2166
     *
jaroslav@1258
  2167
     * @return the scale of this {@code BigDecimal}.
jaroslav@1258
  2168
     */
jaroslav@1258
  2169
    public int scale() {
jaroslav@1258
  2170
        return scale;
jaroslav@1258
  2171
    }
jaroslav@1258
  2172
jaroslav@1258
  2173
    /**
jaroslav@1258
  2174
     * Returns the <i>precision</i> of this {@code BigDecimal}.  (The
jaroslav@1258
  2175
     * precision is the number of digits in the unscaled value.)
jaroslav@1258
  2176
     *
jaroslav@1258
  2177
     * <p>The precision of a zero value is 1.
jaroslav@1258
  2178
     *
jaroslav@1258
  2179
     * @return the precision of this {@code BigDecimal}.
jaroslav@1258
  2180
     * @since  1.5
jaroslav@1258
  2181
     */
jaroslav@1258
  2182
    public int precision() {
jaroslav@1258
  2183
        int result = precision;
jaroslav@1258
  2184
        if (result == 0) {
jaroslav@1258
  2185
            long s = intCompact;
jaroslav@1258
  2186
            if (s != INFLATED)
jaroslav@1258
  2187
                result = longDigitLength(s);
jaroslav@1258
  2188
            else
jaroslav@1258
  2189
                result = bigDigitLength(inflate());
jaroslav@1258
  2190
            precision = result;
jaroslav@1258
  2191
        }
jaroslav@1258
  2192
        return result;
jaroslav@1258
  2193
    }
jaroslav@1258
  2194
jaroslav@1258
  2195
jaroslav@1258
  2196
    /**
jaroslav@1258
  2197
     * Returns a {@code BigInteger} whose value is the <i>unscaled
jaroslav@1258
  2198
     * value</i> of this {@code BigDecimal}.  (Computes <tt>(this *
jaroslav@1258
  2199
     * 10<sup>this.scale()</sup>)</tt>.)
jaroslav@1258
  2200
     *
jaroslav@1258
  2201
     * @return the unscaled value of this {@code BigDecimal}.
jaroslav@1258
  2202
     * @since  1.2
jaroslav@1258
  2203
     */
jaroslav@1258
  2204
    public BigInteger unscaledValue() {
jaroslav@1258
  2205
        return this.inflate();
jaroslav@1258
  2206
    }
jaroslav@1258
  2207
jaroslav@1258
  2208
    // Rounding Modes
jaroslav@1258
  2209
jaroslav@1258
  2210
    /**
jaroslav@1258
  2211
     * Rounding mode to round away from zero.  Always increments the
jaroslav@1258
  2212
     * digit prior to a nonzero discarded fraction.  Note that this rounding
jaroslav@1258
  2213
     * mode never decreases the magnitude of the calculated value.
jaroslav@1258
  2214
     */
jaroslav@1258
  2215
    public final static int ROUND_UP =           0;
jaroslav@1258
  2216
jaroslav@1258
  2217
    /**
jaroslav@1258
  2218
     * Rounding mode to round towards zero.  Never increments the digit
jaroslav@1258
  2219
     * prior to a discarded fraction (i.e., truncates).  Note that this
jaroslav@1258
  2220
     * rounding mode never increases the magnitude of the calculated value.
jaroslav@1258
  2221
     */
jaroslav@1258
  2222
    public final static int ROUND_DOWN =         1;
jaroslav@1258
  2223
jaroslav@1258
  2224
    /**
jaroslav@1258
  2225
     * Rounding mode to round towards positive infinity.  If the
jaroslav@1258
  2226
     * {@code BigDecimal} is positive, behaves as for
jaroslav@1258
  2227
     * {@code ROUND_UP}; if negative, behaves as for
jaroslav@1258
  2228
     * {@code ROUND_DOWN}.  Note that this rounding mode never
jaroslav@1258
  2229
     * decreases the calculated value.
jaroslav@1258
  2230
     */
jaroslav@1258
  2231
    public final static int ROUND_CEILING =      2;
jaroslav@1258
  2232
jaroslav@1258
  2233
    /**
jaroslav@1258
  2234
     * Rounding mode to round towards negative infinity.  If the
jaroslav@1258
  2235
     * {@code BigDecimal} is positive, behave as for
jaroslav@1258
  2236
     * {@code ROUND_DOWN}; if negative, behave as for
jaroslav@1258
  2237
     * {@code ROUND_UP}.  Note that this rounding mode never
jaroslav@1258
  2238
     * increases the calculated value.
jaroslav@1258
  2239
     */
jaroslav@1258
  2240
    public final static int ROUND_FLOOR =        3;
jaroslav@1258
  2241
jaroslav@1258
  2242
    /**
jaroslav@1258
  2243
     * Rounding mode to round towards {@literal "nearest neighbor"}
jaroslav@1258
  2244
     * unless both neighbors are equidistant, in which case round up.
jaroslav@1258
  2245
     * Behaves as for {@code ROUND_UP} if the discarded fraction is
jaroslav@1258
  2246
     * &ge; 0.5; otherwise, behaves as for {@code ROUND_DOWN}.  Note
jaroslav@1258
  2247
     * that this is the rounding mode that most of us were taught in
jaroslav@1258
  2248
     * grade school.
jaroslav@1258
  2249
     */
jaroslav@1258
  2250
    public final static int ROUND_HALF_UP =      4;
jaroslav@1258
  2251
jaroslav@1258
  2252
    /**
jaroslav@1258
  2253
     * Rounding mode to round towards {@literal "nearest neighbor"}
jaroslav@1258
  2254
     * unless both neighbors are equidistant, in which case round
jaroslav@1258
  2255
     * down.  Behaves as for {@code ROUND_UP} if the discarded
jaroslav@1258
  2256
     * fraction is {@literal >} 0.5; otherwise, behaves as for
jaroslav@1258
  2257
     * {@code ROUND_DOWN}.
jaroslav@1258
  2258
     */
jaroslav@1258
  2259
    public final static int ROUND_HALF_DOWN =    5;
jaroslav@1258
  2260
jaroslav@1258
  2261
    /**
jaroslav@1258
  2262
     * Rounding mode to round towards the {@literal "nearest neighbor"}
jaroslav@1258
  2263
     * unless both neighbors are equidistant, in which case, round
jaroslav@1258
  2264
     * towards the even neighbor.  Behaves as for
jaroslav@1258
  2265
     * {@code ROUND_HALF_UP} if the digit to the left of the
jaroslav@1258
  2266
     * discarded fraction is odd; behaves as for
jaroslav@1258
  2267
     * {@code ROUND_HALF_DOWN} if it's even.  Note that this is the
jaroslav@1258
  2268
     * rounding mode that minimizes cumulative error when applied
jaroslav@1258
  2269
     * repeatedly over a sequence of calculations.
jaroslav@1258
  2270
     */
jaroslav@1258
  2271
    public final static int ROUND_HALF_EVEN =    6;
jaroslav@1258
  2272
jaroslav@1258
  2273
    /**
jaroslav@1258
  2274
     * Rounding mode to assert that the requested operation has an exact
jaroslav@1258
  2275
     * result, hence no rounding is necessary.  If this rounding mode is
jaroslav@1258
  2276
     * specified on an operation that yields an inexact result, an
jaroslav@1258
  2277
     * {@code ArithmeticException} is thrown.
jaroslav@1258
  2278
     */
jaroslav@1258
  2279
    public final static int ROUND_UNNECESSARY =  7;
jaroslav@1258
  2280
jaroslav@1258
  2281
jaroslav@1258
  2282
    // Scaling/Rounding Operations
jaroslav@1258
  2283
jaroslav@1258
  2284
    /**
jaroslav@1258
  2285
     * Returns a {@code BigDecimal} rounded according to the
jaroslav@1258
  2286
     * {@code MathContext} settings.  If the precision setting is 0 then
jaroslav@1258
  2287
     * no rounding takes place.
jaroslav@1258
  2288
     *
jaroslav@1258
  2289
     * <p>The effect of this method is identical to that of the
jaroslav@1258
  2290
     * {@link #plus(MathContext)} method.
jaroslav@1258
  2291
     *
jaroslav@1258
  2292
     * @param mc the context to use.
jaroslav@1258
  2293
     * @return a {@code BigDecimal} rounded according to the
jaroslav@1258
  2294
     *         {@code MathContext} settings.
jaroslav@1258
  2295
     * @throws ArithmeticException if the rounding mode is
jaroslav@1258
  2296
     *         {@code UNNECESSARY} and the
jaroslav@1258
  2297
     *         {@code BigDecimal}  operation would require rounding.
jaroslav@1258
  2298
     * @see    #plus(MathContext)
jaroslav@1258
  2299
     * @since  1.5
jaroslav@1258
  2300
     */
jaroslav@1258
  2301
    public BigDecimal round(MathContext mc) {
jaroslav@1258
  2302
        return plus(mc);
jaroslav@1258
  2303
    }
jaroslav@1258
  2304
jaroslav@1258
  2305
    /**
jaroslav@1258
  2306
     * Returns a {@code BigDecimal} whose scale is the specified
jaroslav@1258
  2307
     * value, and whose unscaled value is determined by multiplying or
jaroslav@1258
  2308
     * dividing this {@code BigDecimal}'s unscaled value by the
jaroslav@1258
  2309
     * appropriate power of ten to maintain its overall value.  If the
jaroslav@1258
  2310
     * scale is reduced by the operation, the unscaled value must be
jaroslav@1258
  2311
     * divided (rather than multiplied), and the value may be changed;
jaroslav@1258
  2312
     * in this case, the specified rounding mode is applied to the
jaroslav@1258
  2313
     * division.
jaroslav@1258
  2314
     *
jaroslav@1258
  2315
     * <p>Note that since BigDecimal objects are immutable, calls of
jaroslav@1258
  2316
     * this method do <i>not</i> result in the original object being
jaroslav@1258
  2317
     * modified, contrary to the usual convention of having methods
jaroslav@1258
  2318
     * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
jaroslav@1258
  2319
     * Instead, {@code setScale} returns an object with the proper
jaroslav@1258
  2320
     * scale; the returned object may or may not be newly allocated.
jaroslav@1258
  2321
     *
jaroslav@1258
  2322
     * @param  newScale scale of the {@code BigDecimal} value to be returned.
jaroslav@1258
  2323
     * @param  roundingMode The rounding mode to apply.
jaroslav@1258
  2324
     * @return a {@code BigDecimal} whose scale is the specified value,
jaroslav@1258
  2325
     *         and whose unscaled value is determined by multiplying or
jaroslav@1258
  2326
     *         dividing this {@code BigDecimal}'s unscaled value by the
jaroslav@1258
  2327
     *         appropriate power of ten to maintain its overall value.
jaroslav@1258
  2328
     * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
jaroslav@1258
  2329
     *         and the specified scaling operation would require
jaroslav@1258
  2330
     *         rounding.
jaroslav@1258
  2331
     * @see    RoundingMode
jaroslav@1258
  2332
     * @since  1.5
jaroslav@1258
  2333
     */
jaroslav@1258
  2334
    public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
jaroslav@1258
  2335
        return setScale(newScale, roundingMode.oldMode);
jaroslav@1258
  2336
    }
jaroslav@1258
  2337
jaroslav@1258
  2338
    /**
jaroslav@1258
  2339
     * Returns a {@code BigDecimal} whose scale is the specified
jaroslav@1258
  2340
     * value, and whose unscaled value is determined by multiplying or
jaroslav@1258
  2341
     * dividing this {@code BigDecimal}'s unscaled value by the
jaroslav@1258
  2342
     * appropriate power of ten to maintain its overall value.  If the
jaroslav@1258
  2343
     * scale is reduced by the operation, the unscaled value must be
jaroslav@1258
  2344
     * divided (rather than multiplied), and the value may be changed;
jaroslav@1258
  2345
     * in this case, the specified rounding mode is applied to the
jaroslav@1258
  2346
     * division.
jaroslav@1258
  2347
     *
jaroslav@1258
  2348
     * <p>Note that since BigDecimal objects are immutable, calls of
jaroslav@1258
  2349
     * this method do <i>not</i> result in the original object being
jaroslav@1258
  2350
     * modified, contrary to the usual convention of having methods
jaroslav@1258
  2351
     * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
jaroslav@1258
  2352
     * Instead, {@code setScale} returns an object with the proper
jaroslav@1258
  2353
     * scale; the returned object may or may not be newly allocated.
jaroslav@1258
  2354
     *
jaroslav@1258
  2355
     * <p>The new {@link #setScale(int, RoundingMode)} method should
jaroslav@1258
  2356
     * be used in preference to this legacy method.
jaroslav@1258
  2357
     *
jaroslav@1258
  2358
     * @param  newScale scale of the {@code BigDecimal} value to be returned.
jaroslav@1258
  2359
     * @param  roundingMode The rounding mode to apply.
jaroslav@1258
  2360
     * @return a {@code BigDecimal} whose scale is the specified value,
jaroslav@1258
  2361
     *         and whose unscaled value is determined by multiplying or
jaroslav@1258
  2362
     *         dividing this {@code BigDecimal}'s unscaled value by the
jaroslav@1258
  2363
     *         appropriate power of ten to maintain its overall value.
jaroslav@1258
  2364
     * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
jaroslav@1258
  2365
     *         and the specified scaling operation would require
jaroslav@1258
  2366
     *         rounding.
jaroslav@1258
  2367
     * @throws IllegalArgumentException if {@code roundingMode} does not
jaroslav@1258
  2368
     *         represent a valid rounding mode.
jaroslav@1258
  2369
     * @see    #ROUND_UP
jaroslav@1258
  2370
     * @see    #ROUND_DOWN
jaroslav@1258
  2371
     * @see    #ROUND_CEILING
jaroslav@1258
  2372
     * @see    #ROUND_FLOOR
jaroslav@1258
  2373
     * @see    #ROUND_HALF_UP
jaroslav@1258
  2374
     * @see    #ROUND_HALF_DOWN
jaroslav@1258
  2375
     * @see    #ROUND_HALF_EVEN
jaroslav@1258
  2376
     * @see    #ROUND_UNNECESSARY
jaroslav@1258
  2377
     */
jaroslav@1258
  2378
    public BigDecimal setScale(int newScale, int roundingMode) {
jaroslav@1258
  2379
        if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
jaroslav@1258
  2380
            throw new IllegalArgumentException("Invalid rounding mode");
jaroslav@1258
  2381
jaroslav@1258
  2382
        int oldScale = this.scale;
jaroslav@1258
  2383
        if (newScale == oldScale)        // easy case
jaroslav@1258
  2384
            return this;
jaroslav@1258
  2385
        if (this.signum() == 0)            // zero can have any scale
jaroslav@1258
  2386
            return BigDecimal.valueOf(0, newScale);
jaroslav@1258
  2387
jaroslav@1258
  2388
        long rs = this.intCompact;
jaroslav@1258
  2389
        if (newScale > oldScale) {
jaroslav@1258
  2390
            int raise = checkScale((long)newScale - oldScale);
jaroslav@1258
  2391
            BigInteger rb = null;
jaroslav@1258
  2392
            if (rs == INFLATED ||
jaroslav@1258
  2393
                (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
jaroslav@1258
  2394
                rb = bigMultiplyPowerTen(raise);
jaroslav@1258
  2395
            return new BigDecimal(rb, rs, newScale,
jaroslav@1258
  2396
                                  (precision > 0) ? precision + raise : 0);
jaroslav@1258
  2397
        } else {
jaroslav@1258
  2398
            // newScale < oldScale -- drop some digits
jaroslav@1258
  2399
            // Can't predict the precision due to the effect of rounding.
jaroslav@1258
  2400
            int drop = checkScale((long)oldScale - newScale);
jaroslav@1258
  2401
            if (drop < LONG_TEN_POWERS_TABLE.length)
jaroslav@1258
  2402
                return divideAndRound(rs, this.intVal,
jaroslav@1258
  2403
                                      LONG_TEN_POWERS_TABLE[drop], null,
jaroslav@1258
  2404
                                      newScale, roundingMode, newScale);
jaroslav@1258
  2405
            else
jaroslav@1258
  2406
                return divideAndRound(rs, this.intVal,
jaroslav@1258
  2407
                                      INFLATED, bigTenToThe(drop),
jaroslav@1258
  2408
                                      newScale, roundingMode, newScale);
jaroslav@1258
  2409
        }
jaroslav@1258
  2410
    }
jaroslav@1258
  2411
jaroslav@1258
  2412
    /**
jaroslav@1258
  2413
     * Returns a {@code BigDecimal} whose scale is the specified
jaroslav@1258
  2414
     * value, and whose value is numerically equal to this
jaroslav@1258
  2415
     * {@code BigDecimal}'s.  Throws an {@code ArithmeticException}
jaroslav@1258
  2416
     * if this is not possible.
jaroslav@1258
  2417
     *
jaroslav@1258
  2418
     * <p>This call is typically used to increase the scale, in which
jaroslav@1258
  2419
     * case it is guaranteed that there exists a {@code BigDecimal}
jaroslav@1258
  2420
     * of the specified scale and the correct value.  The call can
jaroslav@1258
  2421
     * also be used to reduce the scale if the caller knows that the
jaroslav@1258
  2422
     * {@code BigDecimal} has sufficiently many zeros at the end of
jaroslav@1258
  2423
     * its fractional part (i.e., factors of ten in its integer value)
jaroslav@1258
  2424
     * to allow for the rescaling without changing its value.
jaroslav@1258
  2425
     *
jaroslav@1258
  2426
     * <p>This method returns the same result as the two-argument
jaroslav@1258
  2427
     * versions of {@code setScale}, but saves the caller the trouble
jaroslav@1258
  2428
     * of specifying a rounding mode in cases where it is irrelevant.
jaroslav@1258
  2429
     *
jaroslav@1258
  2430
     * <p>Note that since {@code BigDecimal} objects are immutable,
jaroslav@1258
  2431
     * calls of this method do <i>not</i> result in the original
jaroslav@1258
  2432
     * object being modified, contrary to the usual convention of
jaroslav@1258
  2433
     * having methods named <tt>set<i>X</i></tt> mutate field
jaroslav@1258
  2434
     * <i>{@code X}</i>.  Instead, {@code setScale} returns an
jaroslav@1258
  2435
     * object with the proper scale; the returned object may or may
jaroslav@1258
  2436
     * not be newly allocated.
jaroslav@1258
  2437
     *
jaroslav@1258
  2438
     * @param  newScale scale of the {@code BigDecimal} value to be returned.
jaroslav@1258
  2439
     * @return a {@code BigDecimal} whose scale is the specified value, and
jaroslav@1258
  2440
     *         whose unscaled value is determined by multiplying or dividing
jaroslav@1258
  2441
     *         this {@code BigDecimal}'s unscaled value by the appropriate
jaroslav@1258
  2442
     *         power of ten to maintain its overall value.
jaroslav@1258
  2443
     * @throws ArithmeticException if the specified scaling operation would
jaroslav@1258
  2444
     *         require rounding.
jaroslav@1258
  2445
     * @see    #setScale(int, int)
jaroslav@1258
  2446
     * @see    #setScale(int, RoundingMode)
jaroslav@1258
  2447
     */
jaroslav@1258
  2448
    public BigDecimal setScale(int newScale) {
jaroslav@1258
  2449
        return setScale(newScale, ROUND_UNNECESSARY);
jaroslav@1258
  2450
    }
jaroslav@1258
  2451
jaroslav@1258
  2452
    // Decimal Point Motion Operations
jaroslav@1258
  2453
jaroslav@1258
  2454
    /**
jaroslav@1258
  2455
     * Returns a {@code BigDecimal} which is equivalent to this one
jaroslav@1258
  2456
     * with the decimal point moved {@code n} places to the left.  If
jaroslav@1258
  2457
     * {@code n} is non-negative, the call merely adds {@code n} to
jaroslav@1258
  2458
     * the scale.  If {@code n} is negative, the call is equivalent
jaroslav@1258
  2459
     * to {@code movePointRight(-n)}.  The {@code BigDecimal}
jaroslav@1258
  2460
     * returned by this call has value <tt>(this &times;
jaroslav@1258
  2461
     * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
jaroslav@1258
  2462
     * 0)}.
jaroslav@1258
  2463
     *
jaroslav@1258
  2464
     * @param  n number of places to move the decimal point to the left.
jaroslav@1258
  2465
     * @return a {@code BigDecimal} which is equivalent to this one with the
jaroslav@1258
  2466
     *         decimal point moved {@code n} places to the left.
jaroslav@1258
  2467
     * @throws ArithmeticException if scale overflows.
jaroslav@1258
  2468
     */
jaroslav@1258
  2469
    public BigDecimal movePointLeft(int n) {
jaroslav@1258
  2470
        // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
jaroslav@1258
  2471
        int newScale = checkScale((long)scale + n);
jaroslav@1258
  2472
        BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
jaroslav@1258
  2473
        return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
jaroslav@1258
  2474
    }
jaroslav@1258
  2475
jaroslav@1258
  2476
    /**
jaroslav@1258
  2477
     * Returns a {@code BigDecimal} which is equivalent to this one
jaroslav@1258
  2478
     * with the decimal point moved {@code n} places to the right.
jaroslav@1258
  2479
     * If {@code n} is non-negative, the call merely subtracts
jaroslav@1258
  2480
     * {@code n} from the scale.  If {@code n} is negative, the call
jaroslav@1258
  2481
     * is equivalent to {@code movePointLeft(-n)}.  The
jaroslav@1258
  2482
     * {@code BigDecimal} returned by this call has value <tt>(this
jaroslav@1258
  2483
     * &times; 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
jaroslav@1258
  2484
     * 0)}.
jaroslav@1258
  2485
     *
jaroslav@1258
  2486
     * @param  n number of places to move the decimal point to the right.
jaroslav@1258
  2487
     * @return a {@code BigDecimal} which is equivalent to this one
jaroslav@1258
  2488
     *         with the decimal point moved {@code n} places to the right.
jaroslav@1258
  2489
     * @throws ArithmeticException if scale overflows.
jaroslav@1258
  2490
     */
jaroslav@1258
  2491
    public BigDecimal movePointRight(int n) {
jaroslav@1258
  2492
        // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
jaroslav@1258
  2493
        int newScale = checkScale((long)scale - n);
jaroslav@1258
  2494
        BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
jaroslav@1258
  2495
        return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
jaroslav@1258
  2496
    }
jaroslav@1258
  2497
jaroslav@1258
  2498
    /**
jaroslav@1258
  2499
     * Returns a BigDecimal whose numerical value is equal to
jaroslav@1258
  2500
     * ({@code this} * 10<sup>n</sup>).  The scale of
jaroslav@1258
  2501
     * the result is {@code (this.scale() - n)}.
jaroslav@1258
  2502
     *
jaroslav@1258
  2503
     * @throws ArithmeticException if the scale would be
jaroslav@1258
  2504
     *         outside the range of a 32-bit integer.
jaroslav@1258
  2505
     *
jaroslav@1258
  2506
     * @since 1.5
jaroslav@1258
  2507
     */
jaroslav@1258
  2508
    public BigDecimal scaleByPowerOfTen(int n) {
jaroslav@1258
  2509
        return new BigDecimal(intVal, intCompact,
jaroslav@1258
  2510
                              checkScale((long)scale - n), precision);
jaroslav@1258
  2511
    }
jaroslav@1258
  2512
jaroslav@1258
  2513
    /**
jaroslav@1258
  2514
     * Returns a {@code BigDecimal} which is numerically equal to
jaroslav@1258
  2515
     * this one but with any trailing zeros removed from the
jaroslav@1258
  2516
     * representation.  For example, stripping the trailing zeros from
jaroslav@1258
  2517
     * the {@code BigDecimal} value {@code 600.0}, which has
jaroslav@1258
  2518
     * [{@code BigInteger}, {@code scale}] components equals to
jaroslav@1258
  2519
     * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
jaroslav@1258
  2520
     * {@code scale}] components equals to [6, -2]
jaroslav@1258
  2521
     *
jaroslav@1258
  2522
     * @return a numerically equal {@code BigDecimal} with any
jaroslav@1258
  2523
     * trailing zeros removed.
jaroslav@1258
  2524
     * @since 1.5
jaroslav@1258
  2525
     */
jaroslav@1258
  2526
    public BigDecimal stripTrailingZeros() {
jaroslav@1258
  2527
        this.inflate();
jaroslav@1258
  2528
        BigDecimal result = new BigDecimal(intVal, scale);
jaroslav@1258
  2529
        result.stripZerosToMatchScale(Long.MIN_VALUE);
jaroslav@1258
  2530
        return result;
jaroslav@1258
  2531
    }
jaroslav@1258
  2532
jaroslav@1258
  2533
    // Comparison Operations
jaroslav@1258
  2534
jaroslav@1258
  2535
    /**
jaroslav@1258
  2536
     * Compares this {@code BigDecimal} with the specified
jaroslav@1258
  2537
     * {@code BigDecimal}.  Two {@code BigDecimal} objects that are
jaroslav@1258
  2538
     * equal in value but have a different scale (like 2.0 and 2.00)
jaroslav@1258
  2539
     * are considered equal by this method.  This method is provided
jaroslav@1258
  2540
     * in preference to individual methods for each of the six boolean
jaroslav@1258
  2541
     * comparison operators ({@literal <}, ==,
jaroslav@1258
  2542
     * {@literal >}, {@literal >=}, !=, {@literal <=}).  The
jaroslav@1258
  2543
     * suggested idiom for performing these comparisons is:
jaroslav@1258
  2544
     * {@code (x.compareTo(y)} &lt;<i>op</i>&gt; {@code 0)}, where
jaroslav@1258
  2545
     * &lt;<i>op</i>&gt; is one of the six comparison operators.
jaroslav@1258
  2546
     *
jaroslav@1258
  2547
     * @param  val {@code BigDecimal} to which this {@code BigDecimal} is
jaroslav@1258
  2548
     *         to be compared.
jaroslav@1258
  2549
     * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
jaroslav@1258
  2550
     *          less than, equal to, or greater than {@code val}.
jaroslav@1258
  2551
     */
jaroslav@1258
  2552
    public int compareTo(BigDecimal val) {
jaroslav@1258
  2553
        // Quick path for equal scale and non-inflated case.
jaroslav@1258
  2554
        if (scale == val.scale) {
jaroslav@1258
  2555
            long xs = intCompact;
jaroslav@1258
  2556
            long ys = val.intCompact;
jaroslav@1258
  2557
            if (xs != INFLATED && ys != INFLATED)
jaroslav@1258
  2558
                return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
jaroslav@1258
  2559
        }
jaroslav@1258
  2560
        int xsign = this.signum();
jaroslav@1258
  2561
        int ysign = val.signum();
jaroslav@1258
  2562
        if (xsign != ysign)
jaroslav@1258
  2563
            return (xsign > ysign) ? 1 : -1;
jaroslav@1258
  2564
        if (xsign == 0)
jaroslav@1258
  2565
            return 0;
jaroslav@1258
  2566
        int cmp = compareMagnitude(val);
jaroslav@1258
  2567
        return (xsign > 0) ? cmp : -cmp;
jaroslav@1258
  2568
    }
jaroslav@1258
  2569
jaroslav@1258
  2570
    /**
jaroslav@1258
  2571
     * Version of compareTo that ignores sign.
jaroslav@1258
  2572
     */
jaroslav@1258
  2573
    private int compareMagnitude(BigDecimal val) {
jaroslav@1258
  2574
        // Match scales, avoid unnecessary inflation
jaroslav@1258
  2575
        long ys = val.intCompact;
jaroslav@1258
  2576
        long xs = this.intCompact;
jaroslav@1258
  2577
        if (xs == 0)
jaroslav@1258
  2578
            return (ys == 0) ? 0 : -1;
jaroslav@1258
  2579
        if (ys == 0)
jaroslav@1258
  2580
            return 1;
jaroslav@1258
  2581
jaroslav@1258
  2582
        int sdiff = this.scale - val.scale;
jaroslav@1258
  2583
        if (sdiff != 0) {
jaroslav@1258
  2584
            // Avoid matching scales if the (adjusted) exponents differ
jaroslav@1258
  2585
            int xae = this.precision() - this.scale;   // [-1]
jaroslav@1258
  2586
            int yae = val.precision() - val.scale;     // [-1]
jaroslav@1258
  2587
            if (xae < yae)
jaroslav@1258
  2588
                return -1;
jaroslav@1258
  2589
            if (xae > yae)
jaroslav@1258
  2590
                return 1;
jaroslav@1258
  2591
            BigInteger rb = null;
jaroslav@1258
  2592
            if (sdiff < 0) {
jaroslav@1258
  2593
                if ( (xs == INFLATED ||
jaroslav@1258
  2594
                      (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
jaroslav@1258
  2595
                     ys == INFLATED) {
jaroslav@1258
  2596
                    rb = bigMultiplyPowerTen(-sdiff);
jaroslav@1258
  2597
                    return rb.compareMagnitude(val.intVal);
jaroslav@1258
  2598
                }
jaroslav@1258
  2599
            } else { // sdiff > 0
jaroslav@1258
  2600
                if ( (ys == INFLATED ||
jaroslav@1258
  2601
                      (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
jaroslav@1258
  2602
                     xs == INFLATED) {
jaroslav@1258
  2603
                    rb = val.bigMultiplyPowerTen(sdiff);
jaroslav@1258
  2604
                    return this.intVal.compareMagnitude(rb);
jaroslav@1258
  2605
                }
jaroslav@1258
  2606
            }
jaroslav@1258
  2607
        }
jaroslav@1258
  2608
        if (xs != INFLATED)
jaroslav@1258
  2609
            return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
jaroslav@1258
  2610
        else if (ys != INFLATED)
jaroslav@1258
  2611
            return 1;
jaroslav@1258
  2612
        else
jaroslav@1258
  2613
            return this.intVal.compareMagnitude(val.intVal);
jaroslav@1258
  2614
    }
jaroslav@1258
  2615
jaroslav@1258
  2616
    /**
jaroslav@1258
  2617
     * Compares this {@code BigDecimal} with the specified
jaroslav@1258
  2618
     * {@code Object} for equality.  Unlike {@link
jaroslav@1258
  2619
     * #compareTo(BigDecimal) compareTo}, this method considers two
jaroslav@1258
  2620
     * {@code BigDecimal} objects equal only if they are equal in
jaroslav@1258
  2621
     * value and scale (thus 2.0 is not equal to 2.00 when compared by
jaroslav@1258
  2622
     * this method).
jaroslav@1258
  2623
     *
jaroslav@1258
  2624
     * @param  x {@code Object} to which this {@code BigDecimal} is
jaroslav@1258
  2625
     *         to be compared.
jaroslav@1258
  2626
     * @return {@code true} if and only if the specified {@code Object} is a
jaroslav@1258
  2627
     *         {@code BigDecimal} whose value and scale are equal to this
jaroslav@1258
  2628
     *         {@code BigDecimal}'s.
jaroslav@1258
  2629
     * @see    #compareTo(java.math.BigDecimal)
jaroslav@1258
  2630
     * @see    #hashCode
jaroslav@1258
  2631
     */
jaroslav@1258
  2632
    @Override
jaroslav@1258
  2633
    public boolean equals(Object x) {
jaroslav@1258
  2634
        if (!(x instanceof BigDecimal))
jaroslav@1258
  2635
            return false;
jaroslav@1258
  2636
        BigDecimal xDec = (BigDecimal) x;
jaroslav@1258
  2637
        if (x == this)
jaroslav@1258
  2638
            return true;
jaroslav@1258
  2639
        if (scale != xDec.scale)
jaroslav@1258
  2640
            return false;
jaroslav@1258
  2641
        long s = this.intCompact;
jaroslav@1258
  2642
        long xs = xDec.intCompact;
jaroslav@1258
  2643
        if (s != INFLATED) {
jaroslav@1258
  2644
            if (xs == INFLATED)
jaroslav@1258
  2645
                xs = compactValFor(xDec.intVal);
jaroslav@1258
  2646
            return xs == s;
jaroslav@1258
  2647
        } else if (xs != INFLATED)
jaroslav@1258
  2648
            return xs == compactValFor(this.intVal);
jaroslav@1258
  2649
jaroslav@1258
  2650
        return this.inflate().equals(xDec.inflate());
jaroslav@1258
  2651
    }
jaroslav@1258
  2652
jaroslav@1258
  2653
    /**
jaroslav@1258
  2654
     * Returns the minimum of this {@code BigDecimal} and
jaroslav@1258
  2655
     * {@code val}.
jaroslav@1258
  2656
     *
jaroslav@1258
  2657
     * @param  val value with which the minimum is to be computed.
jaroslav@1258
  2658
     * @return the {@code BigDecimal} whose value is the lesser of this
jaroslav@1258
  2659
     *         {@code BigDecimal} and {@code val}.  If they are equal,
jaroslav@1258
  2660
     *         as defined by the {@link #compareTo(BigDecimal) compareTo}
jaroslav@1258
  2661
     *         method, {@code this} is returned.
jaroslav@1258
  2662
     * @see    #compareTo(java.math.BigDecimal)
jaroslav@1258
  2663
     */
jaroslav@1258
  2664
    public BigDecimal min(BigDecimal val) {
jaroslav@1258
  2665
        return (compareTo(val) <= 0 ? this : val);
jaroslav@1258
  2666
    }
jaroslav@1258
  2667
jaroslav@1258
  2668
    /**
jaroslav@1258
  2669
     * Returns the maximum of this {@code BigDecimal} and {@code val}.
jaroslav@1258
  2670
     *
jaroslav@1258
  2671
     * @param  val value with which the maximum is to be computed.
jaroslav@1258
  2672
     * @return the {@code BigDecimal} whose value is the greater of this
jaroslav@1258
  2673
     *         {@code BigDecimal} and {@code val}.  If they are equal,
jaroslav@1258
  2674
     *         as defined by the {@link #compareTo(BigDecimal) compareTo}
jaroslav@1258
  2675
     *         method, {@code this} is returned.
jaroslav@1258
  2676
     * @see    #compareTo(java.math.BigDecimal)
jaroslav@1258
  2677
     */
jaroslav@1258
  2678
    public BigDecimal max(BigDecimal val) {
jaroslav@1258
  2679
        return (compareTo(val) >= 0 ? this : val);
jaroslav@1258
  2680
    }
jaroslav@1258
  2681
jaroslav@1258
  2682
    // Hash Function
jaroslav@1258
  2683
jaroslav@1258
  2684
    /**
jaroslav@1258
  2685
     * Returns the hash code for this {@code BigDecimal}.  Note that
jaroslav@1258
  2686
     * two {@code BigDecimal} objects that are numerically equal but
jaroslav@1258
  2687
     * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
jaroslav@1258
  2688
     * have the same hash code.
jaroslav@1258
  2689
     *
jaroslav@1258
  2690
     * @return hash code for this {@code BigDecimal}.
jaroslav@1258
  2691
     * @see #equals(Object)
jaroslav@1258
  2692
     */
jaroslav@1258
  2693
    @Override
jaroslav@1258
  2694
    public int hashCode() {
jaroslav@1258
  2695
        if (intCompact != INFLATED) {
jaroslav@1258
  2696
            long val2 = (intCompact < 0)? -intCompact : intCompact;
jaroslav@1258
  2697
            int temp = (int)( ((int)(val2 >>> 32)) * 31  +
jaroslav@1258
  2698
                              (val2 & LONG_MASK));
jaroslav@1258
  2699
            return 31*((intCompact < 0) ?-temp:temp) + scale;
jaroslav@1258
  2700
        } else
jaroslav@1258
  2701
            return 31*intVal.hashCode() + scale;
jaroslav@1258
  2702
    }
jaroslav@1258
  2703
jaroslav@1258
  2704
    // Format Converters
jaroslav@1258
  2705
jaroslav@1258
  2706
    /**
jaroslav@1258
  2707
     * Returns the string representation of this {@code BigDecimal},
jaroslav@1258
  2708
     * using scientific notation if an exponent is needed.
jaroslav@1258
  2709
     *
jaroslav@1258
  2710
     * <p>A standard canonical string form of the {@code BigDecimal}
jaroslav@1258
  2711
     * is created as though by the following steps: first, the
jaroslav@1258
  2712
     * absolute value of the unscaled value of the {@code BigDecimal}
jaroslav@1258
  2713
     * is converted to a string in base ten using the characters
jaroslav@1258
  2714
     * {@code '0'} through {@code '9'} with no leading zeros (except
jaroslav@1258
  2715
     * if its value is zero, in which case a single {@code '0'}
jaroslav@1258
  2716
     * character is used).
jaroslav@1258
  2717
     *
jaroslav@1258
  2718
     * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
jaroslav@1258
  2719
     * negated scale, plus the number of characters in the converted
jaroslav@1258
  2720
     * unscaled value, less one.  That is,
jaroslav@1258
  2721
     * {@code -scale+(ulength-1)}, where {@code ulength} is the
jaroslav@1258
  2722
     * length of the absolute value of the unscaled value in decimal
jaroslav@1258
  2723
     * digits (its <i>precision</i>).
jaroslav@1258
  2724
     *
jaroslav@1258
  2725
     * <p>If the scale is greater than or equal to zero and the
jaroslav@1258
  2726
     * adjusted exponent is greater than or equal to {@code -6}, the
jaroslav@1258
  2727
     * number will be converted to a character form without using
jaroslav@1258
  2728
     * exponential notation.  In this case, if the scale is zero then
jaroslav@1258
  2729
     * no decimal point is added and if the scale is positive a
jaroslav@1258
  2730
     * decimal point will be inserted with the scale specifying the
jaroslav@1258
  2731
     * number of characters to the right of the decimal point.
jaroslav@1258
  2732
     * {@code '0'} characters are added to the left of the converted
jaroslav@1258
  2733
     * unscaled value as necessary.  If no character precedes the
jaroslav@1258
  2734
     * decimal point after this insertion then a conventional
jaroslav@1258
  2735
     * {@code '0'} character is prefixed.
jaroslav@1258
  2736
     *
jaroslav@1258
  2737
     * <p>Otherwise (that is, if the scale is negative, or the
jaroslav@1258
  2738
     * adjusted exponent is less than {@code -6}), the number will be
jaroslav@1258
  2739
     * converted to a character form using exponential notation.  In
jaroslav@1258
  2740
     * this case, if the converted {@code BigInteger} has more than
jaroslav@1258
  2741
     * one digit a decimal point is inserted after the first digit.
jaroslav@1258
  2742
     * An exponent in character form is then suffixed to the converted
jaroslav@1258
  2743
     * unscaled value (perhaps with inserted decimal point); this
jaroslav@1258
  2744
     * comprises the letter {@code 'E'} followed immediately by the
jaroslav@1258
  2745
     * adjusted exponent converted to a character form.  The latter is
jaroslav@1258
  2746
     * in base ten, using the characters {@code '0'} through
jaroslav@1258
  2747
     * {@code '9'} with no leading zeros, and is always prefixed by a
jaroslav@1258
  2748
     * sign character {@code '-'} (<tt>'&#92;u002D'</tt>) if the
jaroslav@1258
  2749
     * adjusted exponent is negative, {@code '+'}
jaroslav@1258
  2750
     * (<tt>'&#92;u002B'</tt>) otherwise).
jaroslav@1258
  2751
     *
jaroslav@1258
  2752
     * <p>Finally, the entire string is prefixed by a minus sign
jaroslav@1258
  2753
     * character {@code '-'} (<tt>'&#92;u002D'</tt>) if the unscaled
jaroslav@1258
  2754
     * value is less than zero.  No sign character is prefixed if the
jaroslav@1258
  2755
     * unscaled value is zero or positive.
jaroslav@1258
  2756
     *
jaroslav@1258
  2757
     * <p><b>Examples:</b>
jaroslav@1258
  2758
     * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
jaroslav@1258
  2759
     * on the left, the resulting string is shown on the right.
jaroslav@1258
  2760
     * <pre>
jaroslav@1258
  2761
     * [123,0]      "123"
jaroslav@1258
  2762
     * [-123,0]     "-123"
jaroslav@1258
  2763
     * [123,-1]     "1.23E+3"
jaroslav@1258
  2764
     * [123,-3]     "1.23E+5"
jaroslav@1258
  2765
     * [123,1]      "12.3"
jaroslav@1258
  2766
     * [123,5]      "0.00123"
jaroslav@1258
  2767
     * [123,10]     "1.23E-8"
jaroslav@1258
  2768
     * [-123,12]    "-1.23E-10"
jaroslav@1258
  2769
     * </pre>
jaroslav@1258
  2770
     *
jaroslav@1258
  2771
     * <b>Notes:</b>
jaroslav@1258
  2772
     * <ol>
jaroslav@1258
  2773
     *
jaroslav@1258
  2774
     * <li>There is a one-to-one mapping between the distinguishable
jaroslav@1258
  2775
     * {@code BigDecimal} values and the result of this conversion.
jaroslav@1258
  2776
     * That is, every distinguishable {@code BigDecimal} value
jaroslav@1258
  2777
     * (unscaled value and scale) has a unique string representation
jaroslav@1258
  2778
     * as a result of using {@code toString}.  If that string
jaroslav@1258
  2779
     * representation is converted back to a {@code BigDecimal} using
jaroslav@1258
  2780
     * the {@link #BigDecimal(String)} constructor, then the original
jaroslav@1258
  2781
     * value will be recovered.
jaroslav@1258
  2782
     *
jaroslav@1258
  2783
     * <li>The string produced for a given number is always the same;
jaroslav@1258
  2784
     * it is not affected by locale.  This means that it can be used
jaroslav@1258
  2785
     * as a canonical string representation for exchanging decimal
jaroslav@1258
  2786
     * data, or as a key for a Hashtable, etc.  Locale-sensitive
jaroslav@1258
  2787
     * number formatting and parsing is handled by the {@link
jaroslav@1258
  2788
     * java.text.NumberFormat} class and its subclasses.
jaroslav@1258
  2789
     *
jaroslav@1258
  2790
     * <li>The {@link #toEngineeringString} method may be used for
jaroslav@1258
  2791
     * presenting numbers with exponents in engineering notation, and the
jaroslav@1258
  2792
     * {@link #setScale(int,RoundingMode) setScale} method may be used for
jaroslav@1258
  2793
     * rounding a {@code BigDecimal} so it has a known number of digits after
jaroslav@1258
  2794
     * the decimal point.
jaroslav@1258
  2795
     *
jaroslav@1258
  2796
     * <li>The digit-to-character mapping provided by
jaroslav@1258
  2797
     * {@code Character.forDigit} is used.
jaroslav@1258
  2798
     *
jaroslav@1258
  2799
     * </ol>
jaroslav@1258
  2800
     *
jaroslav@1258
  2801
     * @return string representation of this {@code BigDecimal}.
jaroslav@1258
  2802
     * @see    Character#forDigit
jaroslav@1258
  2803
     * @see    #BigDecimal(java.lang.String)
jaroslav@1258
  2804
     */
jaroslav@1258
  2805
    @Override
jaroslav@1258
  2806
    public String toString() {
jaroslav@1258
  2807
        String sc = stringCache;
jaroslav@1258
  2808
        if (sc == null)
jaroslav@1258
  2809
            stringCache = sc = layoutChars(true);
jaroslav@1258
  2810
        return sc;
jaroslav@1258
  2811
    }
jaroslav@1258
  2812
jaroslav@1258
  2813
    /**
jaroslav@1258
  2814
     * Returns a string representation of this {@code BigDecimal},
jaroslav@1258
  2815
     * using engineering notation if an exponent is needed.
jaroslav@1258
  2816
     *
jaroslav@1258
  2817
     * <p>Returns a string that represents the {@code BigDecimal} as
jaroslav@1258
  2818
     * described in the {@link #toString()} method, except that if
jaroslav@1258
  2819
     * exponential notation is used, the power of ten is adjusted to
jaroslav@1258
  2820
     * be a multiple of three (engineering notation) such that the
jaroslav@1258
  2821
     * integer part of nonzero values will be in the range 1 through
jaroslav@1258
  2822
     * 999.  If exponential notation is used for zero values, a
jaroslav@1258
  2823
     * decimal point and one or two fractional zero digits are used so
jaroslav@1258
  2824
     * that the scale of the zero value is preserved.  Note that
jaroslav@1258
  2825
     * unlike the output of {@link #toString()}, the output of this
jaroslav@1258
  2826
     * method is <em>not</em> guaranteed to recover the same [integer,
jaroslav@1258
  2827
     * scale] pair of this {@code BigDecimal} if the output string is
jaroslav@1258
  2828
     * converting back to a {@code BigDecimal} using the {@linkplain
jaroslav@1258
  2829
     * #BigDecimal(String) string constructor}.  The result of this method meets
jaroslav@1258
  2830
     * the weaker constraint of always producing a numerically equal
jaroslav@1258
  2831
     * result from applying the string constructor to the method's output.
jaroslav@1258
  2832
     *
jaroslav@1258
  2833
     * @return string representation of this {@code BigDecimal}, using
jaroslav@1258
  2834
     *         engineering notation if an exponent is needed.
jaroslav@1258
  2835
     * @since  1.5
jaroslav@1258
  2836
     */
jaroslav@1258
  2837
    public String toEngineeringString() {
jaroslav@1258
  2838
        return layoutChars(false);
jaroslav@1258
  2839
    }
jaroslav@1258
  2840
jaroslav@1258
  2841
    /**
jaroslav@1258
  2842
     * Returns a string representation of this {@code BigDecimal}
jaroslav@1258
  2843
     * without an exponent field.  For values with a positive scale,
jaroslav@1258
  2844
     * the number of digits to the right of the decimal point is used
jaroslav@1258
  2845
     * to indicate scale.  For values with a zero or negative scale,
jaroslav@1258
  2846
     * the resulting string is generated as if the value were
jaroslav@1258
  2847
     * converted to a numerically equal value with zero scale and as
jaroslav@1258
  2848
     * if all the trailing zeros of the zero scale value were present
jaroslav@1258
  2849
     * in the result.
jaroslav@1258
  2850
     *
jaroslav@1258
  2851
     * The entire string is prefixed by a minus sign character '-'
jaroslav@1258
  2852
     * (<tt>'&#92;u002D'</tt>) if the unscaled value is less than
jaroslav@1258
  2853
     * zero. No sign character is prefixed if the unscaled value is
jaroslav@1258
  2854
     * zero or positive.
jaroslav@1258
  2855
     *
jaroslav@1258
  2856
     * Note that if the result of this method is passed to the
jaroslav@1258
  2857
     * {@linkplain #BigDecimal(String) string constructor}, only the
jaroslav@1258
  2858
     * numerical value of this {@code BigDecimal} will necessarily be
jaroslav@1258
  2859
     * recovered; the representation of the new {@code BigDecimal}
jaroslav@1258
  2860
     * may have a different scale.  In particular, if this
jaroslav@1258
  2861
     * {@code BigDecimal} has a negative scale, the string resulting
jaroslav@1258
  2862
     * from this method will have a scale of zero when processed by
jaroslav@1258
  2863
     * the string constructor.
jaroslav@1258
  2864
     *
jaroslav@1258
  2865
     * (This method behaves analogously to the {@code toString}
jaroslav@1258
  2866
     * method in 1.4 and earlier releases.)
jaroslav@1258
  2867
     *
jaroslav@1258
  2868
     * @return a string representation of this {@code BigDecimal}
jaroslav@1258
  2869
     * without an exponent field.
jaroslav@1258
  2870
     * @since 1.5
jaroslav@1258
  2871
     * @see #toString()
jaroslav@1258
  2872
     * @see #toEngineeringString()
jaroslav@1258
  2873
     */
jaroslav@1258
  2874
    public String toPlainString() {
jaroslav@1258
  2875
        BigDecimal bd = this;
jaroslav@1258
  2876
        if (bd.scale < 0)
jaroslav@1258
  2877
            bd = bd.setScale(0);
jaroslav@1258
  2878
        bd.inflate();
jaroslav@1258
  2879
        if (bd.scale == 0)      // No decimal point
jaroslav@1258
  2880
            return bd.intVal.toString();
jaroslav@1258
  2881
        return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
jaroslav@1258
  2882
    }
jaroslav@1258
  2883
jaroslav@1258
  2884
    /* Returns a digit.digit string */
jaroslav@1258
  2885
    private String getValueString(int signum, String intString, int scale) {
jaroslav@1258
  2886
        /* Insert decimal point */
jaroslav@1258
  2887
        StringBuilder buf;
jaroslav@1258
  2888
        int insertionPoint = intString.length() - scale;
jaroslav@1258
  2889
        if (insertionPoint == 0) {  /* Point goes right before intVal */
jaroslav@1258
  2890
            return (signum<0 ? "-0." : "0.") + intString;
jaroslav@1258
  2891
        } else if (insertionPoint > 0) { /* Point goes inside intVal */
jaroslav@1258
  2892
            buf = new StringBuilder(intString);
jaroslav@1258
  2893
            buf.insert(insertionPoint, '.');
jaroslav@1258
  2894
            if (signum < 0)
jaroslav@1258
  2895
                buf.insert(0, '-');
jaroslav@1258
  2896
        } else { /* We must insert zeros between point and intVal */
jaroslav@1258
  2897
            buf = new StringBuilder(3-insertionPoint + intString.length());
jaroslav@1258
  2898
            buf.append(signum<0 ? "-0." : "0.");
jaroslav@1258
  2899
            for (int i=0; i<-insertionPoint; i++)
jaroslav@1258
  2900
                buf.append('0');
jaroslav@1258
  2901
            buf.append(intString);
jaroslav@1258
  2902
        }
jaroslav@1258
  2903
        return buf.toString();
jaroslav@1258
  2904
    }
jaroslav@1258
  2905
jaroslav@1258
  2906
    /**
jaroslav@1258
  2907
     * Converts this {@code BigDecimal} to a {@code BigInteger}.
jaroslav@1258
  2908
     * This conversion is analogous to the
jaroslav@1258
  2909
     * <i>narrowing primitive conversion</i> from {@code double} to
jaroslav@1258
  2910
     * {@code long} as defined in section 5.1.3 of
jaroslav@1258
  2911
     * <cite>The Java&trade; Language Specification</cite>:
jaroslav@1258
  2912
     * any fractional part of this
jaroslav@1258
  2913
     * {@code BigDecimal} will be discarded.  Note that this
jaroslav@1258
  2914
     * conversion can lose information about the precision of the
jaroslav@1258
  2915
     * {@code BigDecimal} value.
jaroslav@1258
  2916
     * <p>
jaroslav@1258
  2917
     * To have an exception thrown if the conversion is inexact (in
jaroslav@1258
  2918
     * other words if a nonzero fractional part is discarded), use the
jaroslav@1258
  2919
     * {@link #toBigIntegerExact()} method.
jaroslav@1258
  2920
     *
jaroslav@1258
  2921
     * @return this {@code BigDecimal} converted to a {@code BigInteger}.
jaroslav@1258
  2922
     */
jaroslav@1258
  2923
    public BigInteger toBigInteger() {
jaroslav@1258
  2924
        // force to an integer, quietly
jaroslav@1258
  2925
        return this.setScale(0, ROUND_DOWN).inflate();
jaroslav@1258
  2926
    }
jaroslav@1258
  2927
jaroslav@1258
  2928
    /**
jaroslav@1258
  2929
     * Converts this {@code BigDecimal} to a {@code BigInteger},
jaroslav@1258
  2930
     * checking for lost information.  An exception is thrown if this
jaroslav@1258
  2931
     * {@code BigDecimal} has a nonzero fractional part.
jaroslav@1258
  2932
     *
jaroslav@1258
  2933
     * @return this {@code BigDecimal} converted to a {@code BigInteger}.
jaroslav@1258
  2934
     * @throws ArithmeticException if {@code this} has a nonzero
jaroslav@1258
  2935
     *         fractional part.
jaroslav@1258
  2936
     * @since  1.5
jaroslav@1258
  2937
     */
jaroslav@1258
  2938
    public BigInteger toBigIntegerExact() {
jaroslav@1258
  2939
        // round to an integer, with Exception if decimal part non-0
jaroslav@1258
  2940
        return this.setScale(0, ROUND_UNNECESSARY).inflate();
jaroslav@1258
  2941
    }
jaroslav@1258
  2942
jaroslav@1258
  2943
    /**
jaroslav@1258
  2944
     * Converts this {@code BigDecimal} to a {@code long}.
jaroslav@1258
  2945
     * This conversion is analogous to the
jaroslav@1258
  2946
     * <i>narrowing primitive conversion</i> from {@code double} to
jaroslav@1258
  2947
     * {@code short} as defined in section 5.1.3 of
jaroslav@1258
  2948
     * <cite>The Java&trade; Language Specification</cite>:
jaroslav@1258
  2949
     * any fractional part of this
jaroslav@1258
  2950
     * {@code BigDecimal} will be discarded, and if the resulting
jaroslav@1258
  2951
     * "{@code BigInteger}" is too big to fit in a
jaroslav@1258
  2952
     * {@code long}, only the low-order 64 bits are returned.
jaroslav@1258
  2953
     * Note that this conversion can lose information about the
jaroslav@1258
  2954
     * overall magnitude and precision of this {@code BigDecimal} value as well
jaroslav@1258
  2955
     * as return a result with the opposite sign.
jaroslav@1258
  2956
     *
jaroslav@1258
  2957
     * @return this {@code BigDecimal} converted to a {@code long}.
jaroslav@1258
  2958
     */
jaroslav@1258
  2959
    public long longValue(){
jaroslav@1258
  2960
        return (intCompact != INFLATED && scale == 0) ?
jaroslav@1258
  2961
            intCompact:
jaroslav@1258
  2962
            toBigInteger().longValue();
jaroslav@1258
  2963
    }
jaroslav@1258
  2964
jaroslav@1258
  2965
    /**
jaroslav@1258
  2966
     * Converts this {@code BigDecimal} to a {@code long}, checking
jaroslav@1258
  2967
     * for lost information.  If this {@code BigDecimal} has a
jaroslav@1258
  2968
     * nonzero fractional part or is out of the possible range for a
jaroslav@1258
  2969
     * {@code long} result then an {@code ArithmeticException} is
jaroslav@1258
  2970
     * thrown.
jaroslav@1258
  2971
     *
jaroslav@1258
  2972
     * @return this {@code BigDecimal} converted to a {@code long}.
jaroslav@1258
  2973
     * @throws ArithmeticException if {@code this} has a nonzero
jaroslav@1258
  2974
     *         fractional part, or will not fit in a {@code long}.
jaroslav@1258
  2975
     * @since  1.5
jaroslav@1258
  2976
     */
jaroslav@1258
  2977
    public long longValueExact() {
jaroslav@1258
  2978
        if (intCompact != INFLATED && scale == 0)
jaroslav@1258
  2979
            return intCompact;
jaroslav@1258
  2980
        // If more than 19 digits in integer part it cannot possibly fit
jaroslav@1258
  2981
        if ((precision() - scale) > 19) // [OK for negative scale too]
jaroslav@1258
  2982
            throw new java.lang.ArithmeticException("Overflow");
jaroslav@1258
  2983
        // Fastpath zero and < 1.0 numbers (the latter can be very slow
jaroslav@1258
  2984
        // to round if very small)
jaroslav@1258
  2985
        if (this.signum() == 0)
jaroslav@1258
  2986
            return 0;
jaroslav@1258
  2987
        if ((this.precision() - this.scale) <= 0)
jaroslav@1258
  2988
            throw new ArithmeticException("Rounding necessary");
jaroslav@1258
  2989
        // round to an integer, with Exception if decimal part non-0
jaroslav@1258
  2990
        BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
jaroslav@1258
  2991
        if (num.precision() >= 19) // need to check carefully
jaroslav@1258
  2992
            LongOverflow.check(num);
jaroslav@1258
  2993
        return num.inflate().longValue();
jaroslav@1258
  2994
    }
jaroslav@1258
  2995
jaroslav@1258
  2996
    private static class LongOverflow {
jaroslav@1258
  2997
        /** BigInteger equal to Long.MIN_VALUE. */
jaroslav@1258
  2998
        private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
jaroslav@1258
  2999
jaroslav@1258
  3000
        /** BigInteger equal to Long.MAX_VALUE. */
jaroslav@1258
  3001
        private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
jaroslav@1258
  3002
jaroslav@1258
  3003
        public static void check(BigDecimal num) {
jaroslav@1258
  3004
            num.inflate();
jaroslav@1258
  3005
            if ((num.intVal.compareTo(LONGMIN) < 0) ||
jaroslav@1258
  3006
                (num.intVal.compareTo(LONGMAX) > 0))
jaroslav@1258
  3007
                throw new java.lang.ArithmeticException("Overflow");
jaroslav@1258
  3008
        }
jaroslav@1258
  3009
    }
jaroslav@1258
  3010
jaroslav@1258
  3011
    /**
jaroslav@1258
  3012
     * Converts this {@code BigDecimal} to an {@code int}.
jaroslav@1258
  3013
     * This conversion is analogous to the
jaroslav@1258
  3014
     * <i>narrowing primitive conversion</i> from {@code double} to
jaroslav@1258
  3015
     * {@code short} as defined in section 5.1.3 of
jaroslav@1258
  3016
     * <cite>The Java&trade; Language Specification</cite>:
jaroslav@1258
  3017
     * any fractional part of this
jaroslav@1258
  3018
     * {@code BigDecimal} will be discarded, and if the resulting
jaroslav@1258
  3019
     * "{@code BigInteger}" is too big to fit in an
jaroslav@1258
  3020
     * {@code int}, only the low-order 32 bits are returned.
jaroslav@1258
  3021
     * Note that this conversion can lose information about the
jaroslav@1258
  3022
     * overall magnitude and precision of this {@code BigDecimal}
jaroslav@1258
  3023
     * value as well as return a result with the opposite sign.
jaroslav@1258
  3024
     *
jaroslav@1258
  3025
     * @return this {@code BigDecimal} converted to an {@code int}.
jaroslav@1258
  3026
     */
jaroslav@1258
  3027
    public int intValue() {
jaroslav@1258
  3028
        return  (intCompact != INFLATED && scale == 0) ?
jaroslav@1258
  3029
            (int)intCompact :
jaroslav@1258
  3030
            toBigInteger().intValue();
jaroslav@1258
  3031
    }
jaroslav@1258
  3032
jaroslav@1258
  3033
    /**
jaroslav@1258
  3034
     * Converts this {@code BigDecimal} to an {@code int}, checking
jaroslav@1258
  3035
     * for lost information.  If this {@code BigDecimal} has a
jaroslav@1258
  3036
     * nonzero fractional part or is out of the possible range for an
jaroslav@1258
  3037
     * {@code int} result then an {@code ArithmeticException} is
jaroslav@1258
  3038
     * thrown.
jaroslav@1258
  3039
     *
jaroslav@1258
  3040
     * @return this {@code BigDecimal} converted to an {@code int}.
jaroslav@1258
  3041
     * @throws ArithmeticException if {@code this} has a nonzero
jaroslav@1258
  3042
     *         fractional part, or will not fit in an {@code int}.
jaroslav@1258
  3043
     * @since  1.5
jaroslav@1258
  3044
     */
jaroslav@1258
  3045
    public int intValueExact() {
jaroslav@1258
  3046
       long num;
jaroslav@1258
  3047
       num = this.longValueExact();     // will check decimal part
jaroslav@1258
  3048
       if ((int)num != num)
jaroslav@1258
  3049
           throw new java.lang.ArithmeticException("Overflow");
jaroslav@1258
  3050
       return (int)num;
jaroslav@1258
  3051
    }
jaroslav@1258
  3052
jaroslav@1258
  3053
    /**
jaroslav@1258
  3054
     * Converts this {@code BigDecimal} to a {@code short}, checking
jaroslav@1258
  3055
     * for lost information.  If this {@code BigDecimal} has a
jaroslav@1258
  3056
     * nonzero fractional part or is out of the possible range for a
jaroslav@1258
  3057
     * {@code short} result then an {@code ArithmeticException} is
jaroslav@1258
  3058
     * thrown.
jaroslav@1258
  3059
     *
jaroslav@1258
  3060
     * @return this {@code BigDecimal} converted to a {@code short}.
jaroslav@1258
  3061
     * @throws ArithmeticException if {@code this} has a nonzero
jaroslav@1258
  3062
     *         fractional part, or will not fit in a {@code short}.
jaroslav@1258
  3063
     * @since  1.5
jaroslav@1258
  3064
     */
jaroslav@1258
  3065
    public short shortValueExact() {
jaroslav@1258
  3066
       long num;
jaroslav@1258
  3067
       num = this.longValueExact();     // will check decimal part
jaroslav@1258
  3068
       if ((short)num != num)
jaroslav@1258
  3069
           throw new java.lang.ArithmeticException("Overflow");
jaroslav@1258
  3070
       return (short)num;
jaroslav@1258
  3071
    }
jaroslav@1258
  3072
jaroslav@1258
  3073
    /**
jaroslav@1258
  3074
     * Converts this {@code BigDecimal} to a {@code byte}, checking
jaroslav@1258
  3075
     * for lost information.  If this {@code BigDecimal} has a
jaroslav@1258
  3076
     * nonzero fractional part or is out of the possible range for a
jaroslav@1258
  3077
     * {@code byte} result then an {@code ArithmeticException} is
jaroslav@1258
  3078
     * thrown.
jaroslav@1258
  3079
     *
jaroslav@1258
  3080
     * @return this {@code BigDecimal} converted to a {@code byte}.
jaroslav@1258
  3081
     * @throws ArithmeticException if {@code this} has a nonzero
jaroslav@1258
  3082
     *         fractional part, or will not fit in a {@code byte}.
jaroslav@1258
  3083
     * @since  1.5
jaroslav@1258
  3084
     */
jaroslav@1258
  3085
    public byte byteValueExact() {
jaroslav@1258
  3086
       long num;
jaroslav@1258
  3087
       num = this.longValueExact();     // will check decimal part
jaroslav@1258
  3088
       if ((byte)num != num)
jaroslav@1258
  3089
           throw new java.lang.ArithmeticException("Overflow");
jaroslav@1258
  3090
       return (byte)num;
jaroslav@1258
  3091
    }
jaroslav@1258
  3092
jaroslav@1258
  3093
    /**
jaroslav@1258
  3094
     * Converts this {@code BigDecimal} to a {@code float}.
jaroslav@1258
  3095
     * This conversion is similar to the
jaroslav@1258
  3096
     * <i>narrowing primitive conversion</i> from {@code double} to
jaroslav@1258
  3097
     * {@code float} as defined in section 5.1.3 of
jaroslav@1258
  3098
     * <cite>The Java&trade; Language Specification</cite>:
jaroslav@1258
  3099
     * if this {@code BigDecimal} has too great a
jaroslav@1258
  3100
     * magnitude to represent as a {@code float}, it will be
jaroslav@1258
  3101
     * converted to {@link Float#NEGATIVE_INFINITY} or {@link
jaroslav@1258
  3102
     * Float#POSITIVE_INFINITY} as appropriate.  Note that even when
jaroslav@1258
  3103
     * the return value is finite, this conversion can lose
jaroslav@1258
  3104
     * information about the precision of the {@code BigDecimal}
jaroslav@1258
  3105
     * value.
jaroslav@1258
  3106
     *
jaroslav@1258
  3107
     * @return this {@code BigDecimal} converted to a {@code float}.
jaroslav@1258
  3108
     */
jaroslav@1258
  3109
    public float floatValue(){
jaroslav@1258
  3110
        if (scale == 0 && intCompact != INFLATED)
jaroslav@1258
  3111
                return (float)intCompact;
jaroslav@1258
  3112
        // Somewhat inefficient, but guaranteed to work.
jaroslav@1258
  3113
        return Float.parseFloat(this.toString());
jaroslav@1258
  3114
    }
jaroslav@1258
  3115
jaroslav@1258
  3116
    /**
jaroslav@1258
  3117
     * Converts this {@code BigDecimal} to a {@code double}.
jaroslav@1258
  3118
     * This conversion is similar to the
jaroslav@1258
  3119
     * <i>narrowing primitive conversion</i> from {@code double} to
jaroslav@1258
  3120
     * {@code float} as defined in section 5.1.3 of
jaroslav@1258
  3121
     * <cite>The Java&trade; Language Specification</cite>:
jaroslav@1258
  3122
     * if this {@code BigDecimal} has too great a
jaroslav@1258
  3123
     * magnitude represent as a {@code double}, it will be
jaroslav@1258
  3124
     * converted to {@link Double#NEGATIVE_INFINITY} or {@link
jaroslav@1258
  3125
     * Double#POSITIVE_INFINITY} as appropriate.  Note that even when
jaroslav@1258
  3126
     * the return value is finite, this conversion can lose
jaroslav@1258
  3127
     * information about the precision of the {@code BigDecimal}
jaroslav@1258
  3128
     * value.
jaroslav@1258
  3129
     *
jaroslav@1258
  3130
     * @return this {@code BigDecimal} converted to a {@code double}.
jaroslav@1258
  3131
     */
jaroslav@1258
  3132
    public double doubleValue(){
jaroslav@1258
  3133
        if (scale == 0 && intCompact != INFLATED)
jaroslav@1258
  3134
            return (double)intCompact;
jaroslav@1258
  3135
        // Somewhat inefficient, but guaranteed to work.
jaroslav@1258
  3136
        return Double.parseDouble(this.toString());
jaroslav@1258
  3137
    }
jaroslav@1258
  3138
jaroslav@1258
  3139
    /**
jaroslav@1258
  3140
     * Returns the size of an ulp, a unit in the last place, of this
jaroslav@1258
  3141
     * {@code BigDecimal}.  An ulp of a nonzero {@code BigDecimal}
jaroslav@1258
  3142
     * value is the positive distance between this value and the
jaroslav@1258
  3143
     * {@code BigDecimal} value next larger in magnitude with the
jaroslav@1258
  3144
     * same number of digits.  An ulp of a zero value is numerically
jaroslav@1258
  3145
     * equal to 1 with the scale of {@code this}.  The result is
jaroslav@1258
  3146
     * stored with the same scale as {@code this} so the result
jaroslav@1258
  3147
     * for zero and nonzero values is equal to {@code [1,
jaroslav@1258
  3148
     * this.scale()]}.
jaroslav@1258
  3149
     *
jaroslav@1258
  3150
     * @return the size of an ulp of {@code this}
jaroslav@1258
  3151
     * @since 1.5
jaroslav@1258
  3152
     */
jaroslav@1258
  3153
    public BigDecimal ulp() {
jaroslav@1258
  3154
        return BigDecimal.valueOf(1, this.scale());
jaroslav@1258
  3155
    }
jaroslav@1258
  3156
jaroslav@1258
  3157
jaroslav@1258
  3158
    // Private class to build a string representation for BigDecimal object.
jaroslav@1258
  3159
    // "StringBuilderHelper" is constructed as a thread local variable so it is
jaroslav@1258
  3160
    // thread safe. The StringBuilder field acts as a buffer to hold the temporary
jaroslav@1258
  3161
    // representation of BigDecimal. The cmpCharArray holds all the characters for
jaroslav@1258
  3162
    // the compact representation of BigDecimal (except for '-' sign' if it is
jaroslav@1258
  3163
    // negative) if its intCompact field is not INFLATED. It is shared by all
jaroslav@1258
  3164
    // calls to toString() and its variants in that particular thread.
jaroslav@1258
  3165
    static class StringBuilderHelper {
jaroslav@1258
  3166
        final StringBuilder sb;    // Placeholder for BigDecimal string
jaroslav@1258
  3167
        final char[] cmpCharArray; // character array to place the intCompact
jaroslav@1258
  3168
jaroslav@1258
  3169
        StringBuilderHelper() {
jaroslav@1258
  3170
            sb = new StringBuilder();
jaroslav@1258
  3171
            // All non negative longs can be made to fit into 19 character array.
jaroslav@1258
  3172
            cmpCharArray = new char[19];
jaroslav@1258
  3173
        }
jaroslav@1258
  3174
jaroslav@1258
  3175
        // Accessors.
jaroslav@1258
  3176
        StringBuilder getStringBuilder() {
jaroslav@1258
  3177
            sb.setLength(0);
jaroslav@1258
  3178
            return sb;
jaroslav@1258
  3179
        }
jaroslav@1258
  3180
jaroslav@1258
  3181
        char[] getCompactCharArray() {
jaroslav@1258
  3182
            return cmpCharArray;
jaroslav@1258
  3183
        }
jaroslav@1258
  3184
jaroslav@1258
  3185
        /**
jaroslav@1258
  3186
         * Places characters representing the intCompact in {@code long} into
jaroslav@1258
  3187
         * cmpCharArray and returns the offset to the array where the
jaroslav@1258
  3188
         * representation starts.
jaroslav@1258
  3189
         *
jaroslav@1258
  3190
         * @param intCompact the number to put into the cmpCharArray.
jaroslav@1258
  3191
         * @return offset to the array where the representation starts.
jaroslav@1258
  3192
         * Note: intCompact must be greater or equal to zero.
jaroslav@1258
  3193
         */
jaroslav@1258
  3194
        int putIntCompact(long intCompact) {
jaroslav@1258
  3195
            assert intCompact >= 0;
jaroslav@1258
  3196
jaroslav@1258
  3197
            long q;
jaroslav@1258
  3198
            int r;
jaroslav@1258
  3199
            // since we start from the least significant digit, charPos points to
jaroslav@1258
  3200
            // the last character in cmpCharArray.
jaroslav@1258
  3201
            int charPos = cmpCharArray.length;
jaroslav@1258
  3202
jaroslav@1258
  3203
            // Get 2 digits/iteration using longs until quotient fits into an int
jaroslav@1258
  3204
            while (intCompact > Integer.MAX_VALUE) {
jaroslav@1258
  3205
                q = intCompact / 100;
jaroslav@1258
  3206
                r = (int)(intCompact - q * 100);
jaroslav@1258
  3207
                intCompact = q;
jaroslav@1258
  3208
                cmpCharArray[--charPos] = DIGIT_ONES[r];
jaroslav@1258
  3209
                cmpCharArray[--charPos] = DIGIT_TENS[r];
jaroslav@1258
  3210
            }
jaroslav@1258
  3211
jaroslav@1258
  3212
            // Get 2 digits/iteration using ints when i2 >= 100
jaroslav@1258
  3213
            int q2;
jaroslav@1258
  3214
            int i2 = (int)intCompact;
jaroslav@1258
  3215
            while (i2 >= 100) {
jaroslav@1258
  3216
                q2 = i2 / 100;
jaroslav@1258
  3217
                r  = i2 - q2 * 100;
jaroslav@1258
  3218
                i2 = q2;
jaroslav@1258
  3219
                cmpCharArray[--charPos] = DIGIT_ONES[r];
jaroslav@1258
  3220
                cmpCharArray[--charPos] = DIGIT_TENS[r];
jaroslav@1258
  3221
            }
jaroslav@1258
  3222
jaroslav@1258
  3223
            cmpCharArray[--charPos] = DIGIT_ONES[i2];
jaroslav@1258
  3224
            if (i2 >= 10)
jaroslav@1258
  3225
                cmpCharArray[--charPos] = DIGIT_TENS[i2];
jaroslav@1258
  3226
jaroslav@1258
  3227
            return charPos;
jaroslav@1258
  3228
        }
jaroslav@1258
  3229
jaroslav@1258
  3230
        final static char[] DIGIT_TENS = {
jaroslav@1258
  3231
            '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
jaroslav@1258
  3232
            '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
jaroslav@1258
  3233
            '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
jaroslav@1258
  3234
            '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
jaroslav@1258
  3235
            '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
jaroslav@1258
  3236
            '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
jaroslav@1258
  3237
            '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
jaroslav@1258
  3238
            '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
jaroslav@1258
  3239
            '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
jaroslav@1258
  3240
            '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
jaroslav@1258
  3241
        };
jaroslav@1258
  3242
jaroslav@1258
  3243
        final static char[] DIGIT_ONES = {
jaroslav@1258
  3244
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3245
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3246
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3247
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3248
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3249
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3250
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3251
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3252
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3253
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
jaroslav@1258
  3254
        };
jaroslav@1258
  3255
    }
jaroslav@1258
  3256
jaroslav@1258
  3257
    /**
jaroslav@1258
  3258
     * Lay out this {@code BigDecimal} into a {@code char[]} array.
jaroslav@1258
  3259
     * The Java 1.2 equivalent to this was called {@code getValueString}.
jaroslav@1258
  3260
     *
jaroslav@1258
  3261
     * @param  sci {@code true} for Scientific exponential notation;
jaroslav@1258
  3262
     *          {@code false} for Engineering
jaroslav@1258
  3263
     * @return string with canonical string representation of this
jaroslav@1258
  3264
     *         {@code BigDecimal}
jaroslav@1258
  3265
     */
jaroslav@1258
  3266
    private String layoutChars(boolean sci) {
jaroslav@1258
  3267
        if (scale == 0)                      // zero scale is trivial
jaroslav@1258
  3268
            return (intCompact != INFLATED) ?
jaroslav@1258
  3269
                Long.toString(intCompact):
jaroslav@1258
  3270
                intVal.toString();
jaroslav@1258
  3271
jaroslav@1258
  3272
        StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get();
jaroslav@1258
  3273
        char[] coeff;
jaroslav@1258
  3274
        int offset;  // offset is the starting index for coeff array
jaroslav@1258
  3275
        // Get the significand as an absolute value
jaroslav@1258
  3276
        if (intCompact != INFLATED) {
jaroslav@1258
  3277
            offset = sbHelper.putIntCompact(Math.abs(intCompact));
jaroslav@1258
  3278
            coeff  = sbHelper.getCompactCharArray();
jaroslav@1258
  3279
        } else {
jaroslav@1258
  3280
            offset = 0;
jaroslav@1258
  3281
            coeff  = intVal.abs().toString().toCharArray();
jaroslav@1258
  3282
        }
jaroslav@1258
  3283
jaroslav@1258
  3284
        // Construct a buffer, with sufficient capacity for all cases.
jaroslav@1258
  3285
        // If E-notation is needed, length will be: +1 if negative, +1
jaroslav@1258
  3286
        // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
jaroslav@1258
  3287
        // Otherwise it could have +1 if negative, plus leading "0.00000"
jaroslav@1258
  3288
        StringBuilder buf = sbHelper.getStringBuilder();
jaroslav@1258
  3289
        if (signum() < 0)             // prefix '-' if negative
jaroslav@1258
  3290
            buf.append('-');
jaroslav@1258
  3291
        int coeffLen = coeff.length - offset;
jaroslav@1258
  3292
        long adjusted = -(long)scale + (coeffLen -1);
jaroslav@1258
  3293
        if ((scale >= 0) && (adjusted >= -6)) { // plain number
jaroslav@1258
  3294
            int pad = scale - coeffLen;         // count of padding zeros
jaroslav@1258
  3295
            if (pad >= 0) {                     // 0.xxx form
jaroslav@1258
  3296
                buf.append('0');
jaroslav@1258
  3297
                buf.append('.');
jaroslav@1258
  3298
                for (; pad>0; pad--) {
jaroslav@1258
  3299
                    buf.append('0');
jaroslav@1258
  3300
                }
jaroslav@1258
  3301
                buf.append(coeff, offset, coeffLen);
jaroslav@1258
  3302
            } else {                         // xx.xx form
jaroslav@1258
  3303
                buf.append(coeff, offset, -pad);
jaroslav@1258
  3304
                buf.append('.');
jaroslav@1258
  3305
                buf.append(coeff, -pad + offset, scale);
jaroslav@1258
  3306
            }
jaroslav@1258
  3307
        } else { // E-notation is needed
jaroslav@1258
  3308
            if (sci) {                       // Scientific notation
jaroslav@1258
  3309
                buf.append(coeff[offset]);   // first character
jaroslav@1258
  3310
                if (coeffLen > 1) {          // more to come
jaroslav@1258
  3311
                    buf.append('.');
jaroslav@1258
  3312
                    buf.append(coeff, offset + 1, coeffLen - 1);
jaroslav@1258
  3313
                }
jaroslav@1258
  3314
            } else {                         // Engineering notation
jaroslav@1258
  3315
                int sig = (int)(adjusted % 3);
jaroslav@1258
  3316
                if (sig < 0)
jaroslav@1258
  3317
                    sig += 3;                // [adjusted was negative]
jaroslav@1258
  3318
                adjusted -= sig;             // now a multiple of 3
jaroslav@1258
  3319
                sig++;
jaroslav@1258
  3320
                if (signum() == 0) {
jaroslav@1258
  3321
                    switch (sig) {
jaroslav@1258
  3322
                    case 1:
jaroslav@1258
  3323
                        buf.append('0'); // exponent is a multiple of three
jaroslav@1258
  3324
                        break;
jaroslav@1258
  3325
                    case 2:
jaroslav@1258
  3326
                        buf.append("0.00");
jaroslav@1258
  3327
                        adjusted += 3;
jaroslav@1258
  3328
                        break;
jaroslav@1258
  3329
                    case 3:
jaroslav@1258
  3330
                        buf.append("0.0");
jaroslav@1258
  3331
                        adjusted += 3;
jaroslav@1258
  3332
                        break;
jaroslav@1258
  3333
                    default:
jaroslav@1258
  3334
                        throw new AssertionError("Unexpected sig value " + sig);
jaroslav@1258
  3335
                    }
jaroslav@1258
  3336
                } else if (sig >= coeffLen) {   // significand all in integer
jaroslav@1258
  3337
                    buf.append(coeff, offset, coeffLen);
jaroslav@1258
  3338
                    // may need some zeros, too
jaroslav@1258
  3339
                    for (int i = sig - coeffLen; i > 0; i--)
jaroslav@1258
  3340
                        buf.append('0');
jaroslav@1258
  3341
                } else {                     // xx.xxE form
jaroslav@1258
  3342
                    buf.append(coeff, offset, sig);
jaroslav@1258
  3343
                    buf.append('.');
jaroslav@1258
  3344
                    buf.append(coeff, offset + sig, coeffLen - sig);
jaroslav@1258
  3345
                }
jaroslav@1258
  3346
            }
jaroslav@1258
  3347
            if (adjusted != 0) {             // [!sci could have made 0]
jaroslav@1258
  3348
                buf.append('E');
jaroslav@1258
  3349
                if (adjusted > 0)            // force sign for positive
jaroslav@1258
  3350
                    buf.append('+');
jaroslav@1258
  3351
                buf.append(adjusted);
jaroslav@1258
  3352
            }
jaroslav@1258
  3353
        }
jaroslav@1258
  3354
        return buf.toString();
jaroslav@1258
  3355
    }
jaroslav@1258
  3356
jaroslav@1258
  3357
    /**
jaroslav@1258
  3358
     * Return 10 to the power n, as a {@code BigInteger}.
jaroslav@1258
  3359
     *
jaroslav@1258
  3360
     * @param  n the power of ten to be returned (>=0)
jaroslav@1258
  3361
     * @return a {@code BigInteger} with the value (10<sup>n</sup>)
jaroslav@1258
  3362
     */
jaroslav@1258
  3363
    private static BigInteger bigTenToThe(int n) {
jaroslav@1258
  3364
        if (n < 0)
jaroslav@1258
  3365
            return BigInteger.ZERO;
jaroslav@1258
  3366
jaroslav@1258
  3367
        if (n < BIG_TEN_POWERS_TABLE_MAX) {
jaroslav@1258
  3368
            BigInteger[] pows = BIG_TEN_POWERS_TABLE;
jaroslav@1258
  3369
            if (n < pows.length)
jaroslav@1258
  3370
                return pows[n];
jaroslav@1258
  3371
            else
jaroslav@1258
  3372
                return expandBigIntegerTenPowers(n);
jaroslav@1258
  3373
        }
jaroslav@1258
  3374
        // BigInteger.pow is slow, so make 10**n by constructing a
jaroslav@1258
  3375
        // BigInteger from a character string (still not very fast)
jaroslav@1258
  3376
        char tenpow[] = new char[n + 1];
jaroslav@1258
  3377
        tenpow[0] = '1';
jaroslav@1258
  3378
        for (int i = 1; i <= n; i++)
jaroslav@1258
  3379
            tenpow[i] = '0';
jaroslav@1258
  3380
        return new BigInteger(tenpow);
jaroslav@1258
  3381
    }
jaroslav@1258
  3382
jaroslav@1258
  3383
    /**
jaroslav@1258
  3384
     * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
jaroslav@1258
  3385
     *
jaroslav@1258
  3386
     * @param n the power of ten to be returned (>=0)
jaroslav@1258
  3387
     * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
jaroslav@1258
  3388
     *         in the meantime, the BIG_TEN_POWERS_TABLE array gets
jaroslav@1258
  3389
     *         expanded to the size greater than n.
jaroslav@1258
  3390
     */
jaroslav@1258
  3391
    private static BigInteger expandBigIntegerTenPowers(int n) {
jaroslav@1258
  3392
        synchronized(BigDecimal.class) {
jaroslav@1258
  3393
            BigInteger[] pows = BIG_TEN_POWERS_TABLE;
jaroslav@1258
  3394
            int curLen = pows.length;
jaroslav@1258
  3395
            // The following comparison and the above synchronized statement is
jaroslav@1258
  3396
            // to prevent multiple threads from expanding the same array.
jaroslav@1258
  3397
            if (curLen <= n) {
jaroslav@1258
  3398
                int newLen = curLen << 1;
jaroslav@1258
  3399
                while (newLen <= n)
jaroslav@1258
  3400
                    newLen <<= 1;
jaroslav@1258
  3401
                pows = Arrays.copyOf(pows, newLen);
jaroslav@1258
  3402
                for (int i = curLen; i < newLen; i++)
jaroslav@1258
  3403
                    pows[i] = pows[i - 1].multiply(BigInteger.TEN);
jaroslav@1258
  3404
                // Based on the following facts:
jaroslav@1258
  3405
                // 1. pows is a private local varible;
jaroslav@1258
  3406
                // 2. the following store is a volatile store.
jaroslav@1258
  3407
                // the newly created array elements can be safely published.
jaroslav@1258
  3408
                BIG_TEN_POWERS_TABLE = pows;
jaroslav@1258
  3409
            }
jaroslav@1258
  3410
            return pows[n];
jaroslav@1258
  3411
        }
jaroslav@1258
  3412
    }
jaroslav@1258
  3413
jaroslav@1258
  3414
    private static final long[] LONG_TEN_POWERS_TABLE = {
jaroslav@1258
  3415
        1,                     // 0 / 10^0
jaroslav@1258
  3416
        10,                    // 1 / 10^1
jaroslav@1258
  3417
        100,                   // 2 / 10^2
jaroslav@1258
  3418
        1000,                  // 3 / 10^3
jaroslav@1258
  3419
        10000,                 // 4 / 10^4
jaroslav@1258
  3420
        100000,                // 5 / 10^5
jaroslav@1258
  3421
        1000000,               // 6 / 10^6
jaroslav@1258
  3422
        10000000,              // 7 / 10^7
jaroslav@1258
  3423
        100000000,             // 8 / 10^8
jaroslav@1258
  3424
        1000000000,            // 9 / 10^9
jaroslav@1258
  3425
        10000000000L,          // 10 / 10^10
jaroslav@1258
  3426
        100000000000L,         // 11 / 10^11
jaroslav@1258
  3427
        1000000000000L,        // 12 / 10^12
jaroslav@1258
  3428
        10000000000000L,       // 13 / 10^13
jaroslav@1258
  3429
        100000000000000L,      // 14 / 10^14
jaroslav@1258
  3430
        1000000000000000L,     // 15 / 10^15
jaroslav@1258
  3431
        10000000000000000L,    // 16 / 10^16
jaroslav@1258
  3432
        100000000000000000L,   // 17 / 10^17
jaroslav@1258
  3433
        1000000000000000000L   // 18 / 10^18
jaroslav@1258
  3434
    };
jaroslav@1258
  3435
jaroslav@1258
  3436
    private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
jaroslav@1258
  3437
        BigInteger.valueOf(10),       BigInteger.valueOf(100),
jaroslav@1258
  3438
        BigInteger.valueOf(1000),     BigInteger.valueOf(10000),
jaroslav@1258
  3439
        BigInteger.valueOf(100000),   BigInteger.valueOf(1000000),
jaroslav@1258
  3440
        BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
jaroslav@1258
  3441
        BigInteger.valueOf(1000000000),
jaroslav@1258
  3442
        BigInteger.valueOf(10000000000L),
jaroslav@1258
  3443
        BigInteger.valueOf(100000000000L),
jaroslav@1258
  3444
        BigInteger.valueOf(1000000000000L),
jaroslav@1258
  3445
        BigInteger.valueOf(10000000000000L),
jaroslav@1258
  3446
        BigInteger.valueOf(100000000000000L),
jaroslav@1258
  3447
        BigInteger.valueOf(1000000000000000L),
jaroslav@1258
  3448
        BigInteger.valueOf(10000000000000000L),
jaroslav@1258
  3449
        BigInteger.valueOf(100000000000000000L),
jaroslav@1258
  3450
        BigInteger.valueOf(1000000000000000000L)
jaroslav@1258
  3451
    };
jaroslav@1258
  3452
jaroslav@1258
  3453
    private static final int BIG_TEN_POWERS_TABLE_INITLEN =
jaroslav@1258
  3454
        BIG_TEN_POWERS_TABLE.length;
jaroslav@1258
  3455
    private static final int BIG_TEN_POWERS_TABLE_MAX =
jaroslav@1258
  3456
        16 * BIG_TEN_POWERS_TABLE_INITLEN;
jaroslav@1258
  3457
jaroslav@1258
  3458
    private static final long THRESHOLDS_TABLE[] = {
jaroslav@1258
  3459
        Long.MAX_VALUE,                     // 0
jaroslav@1258
  3460
        Long.MAX_VALUE/10L,                 // 1
jaroslav@1258
  3461
        Long.MAX_VALUE/100L,                // 2
jaroslav@1258
  3462
        Long.MAX_VALUE/1000L,               // 3
jaroslav@1258
  3463
        Long.MAX_VALUE/10000L,              // 4
jaroslav@1258
  3464
        Long.MAX_VALUE/100000L,             // 5
jaroslav@1258
  3465
        Long.MAX_VALUE/1000000L,            // 6
jaroslav@1258
  3466
        Long.MAX_VALUE/10000000L,           // 7
jaroslav@1258
  3467
        Long.MAX_VALUE/100000000L,          // 8
jaroslav@1258
  3468
        Long.MAX_VALUE/1000000000L,         // 9
jaroslav@1258
  3469
        Long.MAX_VALUE/10000000000L,        // 10
jaroslav@1258
  3470
        Long.MAX_VALUE/100000000000L,       // 11
jaroslav@1258
  3471
        Long.MAX_VALUE/1000000000000L,      // 12
jaroslav@1258
  3472
        Long.MAX_VALUE/10000000000000L,     // 13
jaroslav@1258
  3473
        Long.MAX_VALUE/100000000000000L,    // 14
jaroslav@1258
  3474
        Long.MAX_VALUE/1000000000000000L,   // 15
jaroslav@1258
  3475
        Long.MAX_VALUE/10000000000000000L,  // 16
jaroslav@1258
  3476
        Long.MAX_VALUE/100000000000000000L, // 17
jaroslav@1258
  3477
        Long.MAX_VALUE/1000000000000000000L // 18
jaroslav@1258
  3478
    };
jaroslav@1258
  3479
jaroslav@1258
  3480
    /**
jaroslav@1258
  3481
     * Compute val * 10 ^ n; return this product if it is
jaroslav@1258
  3482
     * representable as a long, INFLATED otherwise.
jaroslav@1258
  3483
     */
jaroslav@1258
  3484
    private static long longMultiplyPowerTen(long val, int n) {
jaroslav@1258
  3485
        if (val == 0 || n <= 0)
jaroslav@1258
  3486
            return val;
jaroslav@1258
  3487
        long[] tab = LONG_TEN_POWERS_TABLE;
jaroslav@1258
  3488
        long[] bounds = THRESHOLDS_TABLE;
jaroslav@1258
  3489
        if (n < tab.length && n < bounds.length) {
jaroslav@1258
  3490
            long tenpower = tab[n];
jaroslav@1258
  3491
            if (val == 1)
jaroslav@1258
  3492
                return tenpower;
jaroslav@1258
  3493
            if (Math.abs(val) <= bounds[n])
jaroslav@1258
  3494
                return val * tenpower;
jaroslav@1258
  3495
        }
jaroslav@1258
  3496
        return INFLATED;
jaroslav@1258
  3497
    }
jaroslav@1258
  3498
jaroslav@1258
  3499
    /**
jaroslav@1258
  3500
     * Compute this * 10 ^ n.
jaroslav@1258
  3501
     * Needed mainly to allow special casing to trap zero value
jaroslav@1258
  3502
     */
jaroslav@1258
  3503
    private BigInteger bigMultiplyPowerTen(int n) {
jaroslav@1258
  3504
        if (n <= 0)
jaroslav@1258
  3505
            return this.inflate();
jaroslav@1258
  3506
jaroslav@1258
  3507
        if (intCompact != INFLATED)
jaroslav@1258
  3508
            return bigTenToThe(n).multiply(intCompact);
jaroslav@1258
  3509
        else
jaroslav@1258
  3510
            return intVal.multiply(bigTenToThe(n));
jaroslav@1258
  3511
    }
jaroslav@1258
  3512
jaroslav@1258
  3513
    /**
jaroslav@1258
  3514
     * Assign appropriate BigInteger to intVal field if intVal is
jaroslav@1258
  3515
     * null, i.e. the compact representation is in use.
jaroslav@1258
  3516
     */
jaroslav@1258
  3517
    private BigInteger inflate() {
jaroslav@1258
  3518
        if (intVal == null)
jaroslav@1258
  3519
            intVal = BigInteger.valueOf(intCompact);
jaroslav@1258
  3520
        return intVal;
jaroslav@1258
  3521
    }
jaroslav@1258
  3522
jaroslav@1258
  3523
    /**
jaroslav@1258
  3524
     * Match the scales of two {@code BigDecimal}s to align their
jaroslav@1258
  3525
     * least significant digits.
jaroslav@1258
  3526
     *
jaroslav@1258
  3527
     * <p>If the scales of val[0] and val[1] differ, rescale
jaroslav@1258
  3528
     * (non-destructively) the lower-scaled {@code BigDecimal} so
jaroslav@1258
  3529
     * they match.  That is, the lower-scaled reference will be
jaroslav@1258
  3530
     * replaced by a reference to a new object with the same scale as
jaroslav@1258
  3531
     * the other {@code BigDecimal}.
jaroslav@1258
  3532
     *
jaroslav@1258
  3533
     * @param  val array of two elements referring to the two
jaroslav@1258
  3534
     *         {@code BigDecimal}s to be aligned.
jaroslav@1258
  3535
     */
jaroslav@1258
  3536
    private static void matchScale(BigDecimal[] val) {
jaroslav@1258
  3537
        if (val[0].scale == val[1].scale) {
jaroslav@1258
  3538
            return;
jaroslav@1258
  3539
        } else if (val[0].scale < val[1].scale) {
jaroslav@1258
  3540
            val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
jaroslav@1258
  3541
        } else if (val[1].scale < val[0].scale) {
jaroslav@1258
  3542
            val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
jaroslav@1258
  3543
        }
jaroslav@1258
  3544
    }
jaroslav@1258
  3545
jaroslav@1258
  3546
    /**
jaroslav@1258
  3547
     * Reconstitute the {@code BigDecimal} instance from a stream (that is,
jaroslav@1258
  3548
     * deserialize it).
jaroslav@1258
  3549
     *
jaroslav@1258
  3550
     * @param s the stream being read.
jaroslav@1258
  3551
     */
jaroslav@1258
  3552
    private void readObject(java.io.ObjectInputStream s)
jaroslav@1258
  3553
        throws java.io.IOException, ClassNotFoundException {
jaroslav@1258
  3554
        // Read in all fields
jaroslav@1258
  3555
        s.defaultReadObject();
jaroslav@1258
  3556
        // validate possibly bad fields
jaroslav@1258
  3557
        if (intVal == null) {
jaroslav@1258
  3558
            String message = "BigDecimal: null intVal in stream";
jaroslav@1258
  3559
            throw new java.io.StreamCorruptedException(message);
jaroslav@1258
  3560
        // [all values of scale are now allowed]
jaroslav@1258
  3561
        }
jaroslav@1258
  3562
        intCompact = compactValFor(intVal);
jaroslav@1258
  3563
    }
jaroslav@1258
  3564
jaroslav@1258
  3565
   /**
jaroslav@1258
  3566
    * Serialize this {@code BigDecimal} to the stream in question
jaroslav@1258
  3567
    *
jaroslav@1258
  3568
    * @param s the stream to serialize to.
jaroslav@1258
  3569
    */
jaroslav@1258
  3570
   private void writeObject(java.io.ObjectOutputStream s)
jaroslav@1258
  3571
       throws java.io.IOException {
jaroslav@1258
  3572
       // Must inflate to maintain compatible serial form.
jaroslav@1258
  3573
       this.inflate();
jaroslav@1258
  3574
jaroslav@1258
  3575
       // Write proper fields
jaroslav@1258
  3576
       s.defaultWriteObject();
jaroslav@1258
  3577
   }
jaroslav@1258
  3578
jaroslav@1258
  3579
jaroslav@1258
  3580
    /**
jaroslav@1258
  3581
     * Returns the length of the absolute value of a {@code long}, in decimal
jaroslav@1258
  3582
     * digits.
jaroslav@1258
  3583
     *
jaroslav@1258
  3584
     * @param x the {@code long}
jaroslav@1258
  3585
     * @return the length of the unscaled value, in deciaml digits.
jaroslav@1258
  3586
     */
jaroslav@1258
  3587
    private static int longDigitLength(long x) {
jaroslav@1258
  3588
        /*
jaroslav@1258
  3589
         * As described in "Bit Twiddling Hacks" by Sean Anderson,
jaroslav@1258
  3590
         * (http://graphics.stanford.edu/~seander/bithacks.html)
jaroslav@1258
  3591
         * integer log 10 of x is within 1 of
jaroslav@1258
  3592
         * (1233/4096)* (1 + integer log 2 of x).
jaroslav@1258
  3593
         * The fraction 1233/4096 approximates log10(2). So we first
jaroslav@1258
  3594
         * do a version of log2 (a variant of Long class with
jaroslav@1258
  3595
         * pre-checks and opposite directionality) and then scale and
jaroslav@1258
  3596
         * check against powers table. This is a little simpler in
jaroslav@1258
  3597
         * present context than the version in Hacker's Delight sec
jaroslav@1258
  3598
         * 11-4.  Adding one to bit length allows comparing downward
jaroslav@1258
  3599
         * from the LONG_TEN_POWERS_TABLE that we need anyway.
jaroslav@1258
  3600
         */
jaroslav@1258
  3601
        assert x != INFLATED;
jaroslav@1258
  3602
        if (x < 0)
jaroslav@1258
  3603
            x = -x;
jaroslav@1258
  3604
        if (x < 10) // must screen for 0, might as well 10
jaroslav@1258
  3605
            return 1;
jaroslav@1258
  3606
        int n = 64; // not 63, to avoid needing to add 1 later
jaroslav@1258
  3607
        int y = (int)(x >>> 32);
jaroslav@1258
  3608
        if (y == 0) { n -= 32; y = (int)x; }
jaroslav@1258
  3609
        if (y >>> 16 == 0) { n -= 16; y <<= 16; }
jaroslav@1258
  3610
        if (y >>> 24 == 0) { n -=  8; y <<=  8; }
jaroslav@1258
  3611
        if (y >>> 28 == 0) { n -=  4; y <<=  4; }
jaroslav@1258
  3612
        if (y >>> 30 == 0) { n -=  2; y <<=  2; }
jaroslav@1258
  3613
        int r = (((y >>> 31) + n) * 1233) >>> 12;
jaroslav@1258
  3614
        long[] tab = LONG_TEN_POWERS_TABLE;
jaroslav@1258
  3615
        // if r >= length, must have max possible digits for long
jaroslav@1258
  3616
        return (r >= tab.length || x < tab[r])? r : r+1;
jaroslav@1258
  3617
    }
jaroslav@1258
  3618
jaroslav@1258
  3619
    /**
jaroslav@1258
  3620
     * Returns the length of the absolute value of a BigInteger, in
jaroslav@1258
  3621
     * decimal digits.
jaroslav@1258
  3622
     *
jaroslav@1258
  3623
     * @param b the BigInteger
jaroslav@1258
  3624
     * @return the length of the unscaled value, in decimal digits
jaroslav@1258
  3625
     */
jaroslav@1258
  3626
    private static int bigDigitLength(BigInteger b) {
jaroslav@1258
  3627
        /*
jaroslav@1258
  3628
         * Same idea as the long version, but we need a better
jaroslav@1258
  3629
         * approximation of log10(2). Using 646456993/2^31
jaroslav@1258
  3630
         * is accurate up to max possible reported bitLength.
jaroslav@1258
  3631
         */
jaroslav@1258
  3632
        if (b.signum == 0)
jaroslav@1258
  3633
            return 1;
jaroslav@1258
  3634
        int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
jaroslav@1258
  3635
        return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
jaroslav@1258
  3636
    }
jaroslav@1258
  3637
jaroslav@1258
  3638
jaroslav@1258
  3639
    /**
jaroslav@1258
  3640
     * Remove insignificant trailing zeros from this
jaroslav@1258
  3641
     * {@code BigDecimal} until the preferred scale is reached or no
jaroslav@1258
  3642
     * more zeros can be removed.  If the preferred scale is less than
jaroslav@1258
  3643
     * Integer.MIN_VALUE, all the trailing zeros will be removed.
jaroslav@1258
  3644
     *
jaroslav@1258
  3645
     * {@code BigInteger} assistance could help, here?
jaroslav@1258
  3646
     *
jaroslav@1258
  3647
     * <p>WARNING: This method should only be called on new objects as
jaroslav@1258
  3648
     * it mutates the value fields.
jaroslav@1258
  3649
     *
jaroslav@1258
  3650
     * @return this {@code BigDecimal} with a scale possibly reduced
jaroslav@1258
  3651
     * to be closed to the preferred scale.
jaroslav@1258
  3652
     */
jaroslav@1258
  3653
    private BigDecimal stripZerosToMatchScale(long preferredScale) {
jaroslav@1258
  3654
        this.inflate();
jaroslav@1258
  3655
        BigInteger qr[];                // quotient-remainder pair
jaroslav@1258
  3656
        while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
jaroslav@1258
  3657
                scale > preferredScale) {
jaroslav@1258
  3658
            if (intVal.testBit(0))
jaroslav@1258
  3659
                break;                  // odd number cannot end in 0
jaroslav@1258
  3660
            qr = intVal.divideAndRemainder(BigInteger.TEN);
jaroslav@1258
  3661
            if (qr[1].signum() != 0)
jaroslav@1258
  3662
                break;                  // non-0 remainder
jaroslav@1258
  3663
            intVal=qr[0];
jaroslav@1258
  3664
            scale = checkScale((long)scale-1);  // could Overflow
jaroslav@1258
  3665
            if (precision > 0)          // adjust precision if known
jaroslav@1258
  3666
              precision--;
jaroslav@1258
  3667
        }
jaroslav@1258
  3668
        if (intVal != null)
jaroslav@1258
  3669
            intCompact = compactValFor(intVal);
jaroslav@1258
  3670
        return this;
jaroslav@1258
  3671
    }
jaroslav@1258
  3672
jaroslav@1258
  3673
    /**
jaroslav@1258
  3674
     * Check a scale for Underflow or Overflow.  If this BigDecimal is
jaroslav@1258
  3675
     * nonzero, throw an exception if the scale is outof range. If this
jaroslav@1258
  3676
     * is zero, saturate the scale to the extreme value of the right
jaroslav@1258
  3677
     * sign if the scale is out of range.
jaroslav@1258
  3678
     *
jaroslav@1258
  3679
     * @param val The new scale.
jaroslav@1258
  3680
     * @throws ArithmeticException (overflow or underflow) if the new
jaroslav@1258
  3681
     *         scale is out of range.
jaroslav@1258
  3682
     * @return validated scale as an int.
jaroslav@1258
  3683
     */
jaroslav@1258
  3684
    private int checkScale(long val) {
jaroslav@1258
  3685
        int asInt = (int)val;
jaroslav@1258
  3686
        if (asInt != val) {
jaroslav@1258
  3687
            asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
jaroslav@1258
  3688
            BigInteger b;
jaroslav@1258
  3689
            if (intCompact != 0 &&
jaroslav@1258
  3690
                ((b = intVal) == null || b.signum() != 0))
jaroslav@1258
  3691
                throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
jaroslav@1258
  3692
        }
jaroslav@1258
  3693
        return asInt;
jaroslav@1258
  3694
    }
jaroslav@1258
  3695
jaroslav@1258
  3696
    /**
jaroslav@1258
  3697
     * Round an operand; used only if digits &gt; 0.  Does not change
jaroslav@1258
  3698
     * {@code this}; if rounding is needed a new {@code BigDecimal}
jaroslav@1258
  3699
     * is created and returned.
jaroslav@1258
  3700
     *
jaroslav@1258
  3701
     * @param mc the context to use.
jaroslav@1258
  3702
     * @throws ArithmeticException if the result is inexact but the
jaroslav@1258
  3703
     *         rounding mode is {@code UNNECESSARY}.
jaroslav@1258
  3704
     */
jaroslav@1258
  3705
    private BigDecimal roundOp(MathContext mc) {
jaroslav@1258
  3706
        BigDecimal rounded = doRound(this, mc);
jaroslav@1258
  3707
        return rounded;
jaroslav@1258
  3708
    }
jaroslav@1258
  3709
jaroslav@1258
  3710
    /** Round this BigDecimal according to the MathContext settings;
jaroslav@1258
  3711
     *  used only if precision {@literal >} 0.
jaroslav@1258
  3712
     *
jaroslav@1258
  3713
     * <p>WARNING: This method should only be called on new objects as
jaroslav@1258
  3714
     * it mutates the value fields.
jaroslav@1258
  3715
     *
jaroslav@1258
  3716
     * @param mc the context to use.
jaroslav@1258
  3717
     * @throws ArithmeticException if the rounding mode is
jaroslav@1258
  3718
     *         {@code RoundingMode.UNNECESSARY} and the
jaroslav@1258
  3719
     *         {@code BigDecimal} operation would require rounding.
jaroslav@1258
  3720
     */
jaroslav@1258
  3721
    private void roundThis(MathContext mc) {
jaroslav@1258
  3722
        BigDecimal rounded = doRound(this, mc);
jaroslav@1258
  3723
        if (rounded == this)                 // wasn't rounded
jaroslav@1258
  3724
            return;
jaroslav@1258
  3725
        this.intVal     = rounded.intVal;
jaroslav@1258
  3726
        this.intCompact = rounded.intCompact;
jaroslav@1258
  3727
        this.scale      = rounded.scale;
jaroslav@1258
  3728
        this.precision  = rounded.precision;
jaroslav@1258
  3729
    }
jaroslav@1258
  3730
jaroslav@1258
  3731
    /**
jaroslav@1258
  3732
     * Returns a {@code BigDecimal} rounded according to the
jaroslav@1258
  3733
     * MathContext settings; used only if {@code mc.precision > 0}.
jaroslav@1258
  3734
     * Does not change {@code this}; if rounding is needed a new
jaroslav@1258
  3735
     * {@code BigDecimal} is created and returned.
jaroslav@1258
  3736
     *
jaroslav@1258
  3737
     * @param mc the context to use.
jaroslav@1258
  3738
     * @return a {@code BigDecimal} rounded according to the MathContext
jaroslav@1258
  3739
     *         settings.  May return this, if no rounding needed.
jaroslav@1258
  3740
     * @throws ArithmeticException if the rounding mode is
jaroslav@1258
  3741
     *         {@code RoundingMode.UNNECESSARY} and the
jaroslav@1258
  3742
     *         result is inexact.
jaroslav@1258
  3743
     */
jaroslav@1258
  3744
    private static BigDecimal doRound(BigDecimal d, MathContext mc) {
jaroslav@1258
  3745
        int mcp = mc.precision;
jaroslav@1258
  3746
        int drop;
jaroslav@1258
  3747
        // This might (rarely) iterate to cover the 999=>1000 case
jaroslav@1258
  3748
        while ((drop = d.precision() - mcp) > 0) {
jaroslav@1258
  3749
            int newScale = d.checkScale((long)d.scale - drop);
jaroslav@1258
  3750
            int mode = mc.roundingMode.oldMode;
jaroslav@1258
  3751
            if (drop < LONG_TEN_POWERS_TABLE.length)
jaroslav@1258
  3752
                d = divideAndRound(d.intCompact, d.intVal,
jaroslav@1258
  3753
                                   LONG_TEN_POWERS_TABLE[drop], null,
jaroslav@1258
  3754
                                   newScale, mode, newScale);
jaroslav@1258
  3755
            else
jaroslav@1258
  3756
                d = divideAndRound(d.intCompact, d.intVal,
jaroslav@1258
  3757
                                   INFLATED, bigTenToThe(drop),
jaroslav@1258
  3758
                                   newScale, mode, newScale);
jaroslav@1258
  3759
        }
jaroslav@1258
  3760
        return d;
jaroslav@1258
  3761
    }
jaroslav@1258
  3762
jaroslav@1258
  3763
    /**
jaroslav@1258
  3764
     * Returns the compact value for given {@code BigInteger}, or
jaroslav@1258
  3765
     * INFLATED if too big. Relies on internal representation of
jaroslav@1258
  3766
     * {@code BigInteger}.
jaroslav@1258
  3767
     */
jaroslav@1258
  3768
    private static long compactValFor(BigInteger b) {
jaroslav@1258
  3769
        int[] m = b.mag;
jaroslav@1258
  3770
        int len = m.length;
jaroslav@1258
  3771
        if (len == 0)
jaroslav@1258
  3772
            return 0;
jaroslav@1258
  3773
        int d = m[0];
jaroslav@1258
  3774
        if (len > 2 || (len == 2 && d < 0))
jaroslav@1258
  3775
            return INFLATED;
jaroslav@1258
  3776
jaroslav@1258
  3777
        long u = (len == 2)?
jaroslav@1258
  3778
            (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
jaroslav@1258
  3779
            (((long)d)   & LONG_MASK);
jaroslav@1258
  3780
        return (b.signum < 0)? -u : u;
jaroslav@1258
  3781
    }
jaroslav@1258
  3782
jaroslav@1258
  3783
    private static int longCompareMagnitude(long x, long y) {
jaroslav@1258
  3784
        if (x < 0)
jaroslav@1258
  3785
            x = -x;
jaroslav@1258
  3786
        if (y < 0)
jaroslav@1258
  3787
            y = -y;
jaroslav@1258
  3788
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
jaroslav@1258
  3789
    }
jaroslav@1258
  3790
jaroslav@1258
  3791
    private static int saturateLong(long s) {
jaroslav@1258
  3792
        int i = (int)s;
jaroslav@1258
  3793
        return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
jaroslav@1258
  3794
    }
jaroslav@1258
  3795
jaroslav@1258
  3796
    /*
jaroslav@1258
  3797
     * Internal printing routine
jaroslav@1258
  3798
     */
jaroslav@1258
  3799
    private static void print(String name, BigDecimal bd) {
jaroslav@1258
  3800
        System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n",
jaroslav@1258
  3801
                          name,
jaroslav@1258
  3802
                          bd.intCompact,
jaroslav@1258
  3803
                          bd.intVal,
jaroslav@1258
  3804
                          bd.scale,
jaroslav@1258
  3805
                          bd.precision);
jaroslav@1258
  3806
    }
jaroslav@1258
  3807
jaroslav@1258
  3808
    /**
jaroslav@1258
  3809
     * Check internal invariants of this BigDecimal.  These invariants
jaroslav@1258
  3810
     * include:
jaroslav@1258
  3811
     *
jaroslav@1258
  3812
     * <ul>
jaroslav@1258
  3813
     *
jaroslav@1258
  3814
     * <li>The object must be initialized; either intCompact must not be
jaroslav@1258
  3815
     * INFLATED or intVal is non-null.  Both of these conditions may
jaroslav@1258
  3816
     * be true.
jaroslav@1258
  3817
     *
jaroslav@1258
  3818
     * <li>If both intCompact and intVal and set, their values must be
jaroslav@1258
  3819
     * consistent.
jaroslav@1258
  3820
     *
jaroslav@1258
  3821
     * <li>If precision is nonzero, it must have the right value.
jaroslav@1258
  3822
     * </ul>
jaroslav@1258
  3823
     *
jaroslav@1258
  3824
     * Note: Since this is an audit method, we are not supposed to change the
jaroslav@1258
  3825
     * state of this BigDecimal object.
jaroslav@1258
  3826
     */
jaroslav@1258
  3827
    private BigDecimal audit() {
jaroslav@1258
  3828
        if (intCompact == INFLATED) {
jaroslav@1258
  3829
            if (intVal == null) {
jaroslav@1258
  3830
                print("audit", this);
jaroslav@1258
  3831
                throw new AssertionError("null intVal");
jaroslav@1258
  3832
            }
jaroslav@1258
  3833
            // Check precision
jaroslav@1258
  3834
            if (precision > 0 && precision != bigDigitLength(intVal)) {
jaroslav@1258
  3835
                print("audit", this);
jaroslav@1258
  3836
                throw new AssertionError("precision mismatch");
jaroslav@1258
  3837
            }
jaroslav@1258
  3838
        } else {
jaroslav@1258
  3839
            if (intVal != null) {
jaroslav@1258
  3840
                long val = intVal.longValue();
jaroslav@1258
  3841
                if (val != intCompact) {
jaroslav@1258
  3842
                    print("audit", this);
jaroslav@1258
  3843
                    throw new AssertionError("Inconsistent state, intCompact=" +
jaroslav@1258
  3844
                                             intCompact + "\t intVal=" + val);
jaroslav@1258
  3845
                }
jaroslav@1258
  3846
            }
jaroslav@1258
  3847
            // Check precision
jaroslav@1258
  3848
            if (precision > 0 && precision != longDigitLength(intCompact)) {
jaroslav@1258
  3849
                print("audit", this);
jaroslav@1258
  3850
                throw new AssertionError("precision mismatch");
jaroslav@1258
  3851
            }
jaroslav@1258
  3852
        }
jaroslav@1258
  3853
        return this;
jaroslav@1258
  3854
    }
jaroslav@1258
  3855
}