Home | History | Annotate | Download | only in math
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 package java.math;
     19 
     20 import java.io.IOException;
     21 import java.io.ObjectInputStream;
     22 import java.io.ObjectOutputStream;
     23 import java.io.Serializable;
     24 import java.util.Arrays;
     25 import libcore.math.MathUtils;
     26 
     27 /**
     28  * An immutable arbitrary-precision signed decimal.
     29  *
     30  * <p>A value is represented by an arbitrary-precision "unscaled value" and a signed 32-bit "scale",
     31  * combined thus: {@code unscaled * 10<sup>-scale</sup>}. See {@link #unscaledValue} and {@link #scale}.
     32  *
     33  * <p>Most operations allow you to supply a {@link MathContext} to specify a desired rounding mode.
     34  */
     35 public class BigDecimal extends Number implements Comparable<BigDecimal>, Serializable {
     36 
     37     /**
     38      * Rounding mode where positive values are rounded towards positive infinity
     39      * and negative values towards negative infinity.
     40      *
     41      * @see RoundingMode#UP
     42      */
     43     public static final int ROUND_UP = 0;
     44 
     45     /**
     46      * Rounding mode where the values are rounded towards zero.
     47      *
     48      * @see RoundingMode#DOWN
     49      */
     50     public static final int ROUND_DOWN = 1;
     51 
     52     /**
     53      * Rounding mode to round towards positive infinity. For positive values
     54      * this rounding mode behaves as {@link #ROUND_UP}, for negative values as
     55      * {@link #ROUND_DOWN}.
     56      *
     57      * @see RoundingMode#CEILING
     58      */
     59     public static final int ROUND_CEILING = 2;
     60 
     61     /**
     62      * Rounding mode to round towards negative infinity. For positive values
     63      * this rounding mode behaves as {@link #ROUND_DOWN}, for negative values as
     64      * {@link #ROUND_UP}.
     65      *
     66      * @see RoundingMode#FLOOR
     67      */
     68     public static final int ROUND_FLOOR = 3;
     69 
     70     /**
     71      * Rounding mode where values are rounded towards the nearest neighbor.
     72      * Ties are broken by rounding up.
     73      *
     74      * @see RoundingMode#HALF_UP
     75      */
     76     public static final int ROUND_HALF_UP = 4;
     77 
     78     /**
     79      * Rounding mode where values are rounded towards the nearest neighbor.
     80      * Ties are broken by rounding down.
     81      *
     82      * @see RoundingMode#HALF_DOWN
     83      */
     84     public static final int ROUND_HALF_DOWN = 5;
     85 
     86     /**
     87      * Rounding mode where values are rounded towards the nearest neighbor.
     88      * Ties are broken by rounding to the even neighbor.
     89      *
     90      * @see RoundingMode#HALF_EVEN
     91      */
     92     public static final int ROUND_HALF_EVEN = 6;
     93 
     94     /**
     95      * Rounding mode where the rounding operations throws an {@code
     96      * ArithmeticException} for the case that rounding is necessary, i.e. for
     97      * the case that the value cannot be represented exactly.
     98      *
     99      * @see RoundingMode#UNNECESSARY
    100      */
    101     public static final int ROUND_UNNECESSARY = 7;
    102 
    103     /** This is the serialVersionUID used by the sun implementation. */
    104     private static final long serialVersionUID = 6108874887143696463L;
    105 
    106     /** The double closest to {@code Log10(2)}. */
    107     private static final double LOG10_2 = 0.3010299956639812;
    108 
    109     /** The <code>String</code> representation is cached. */
    110     private transient String toStringImage = null;
    111 
    112     /** Cache for the hash code. */
    113     private transient int hashCode = 0;
    114 
    115     /**
    116      * An array with powers of five that fit in the type <code>long</code>
    117      * (<code>5^0,5^1,...,5^27</code>).
    118      */
    119     private static final BigInteger[] FIVE_POW;
    120 
    121     /**
    122      * An array with powers of ten that fit in the type <code>long</code>
    123      * (<code>10^0,10^1,...,10^18</code>).
    124      */
    125     private static final BigInteger[] TEN_POW;
    126 
    127     private static final long[] LONG_FIVE_POW = new long[]
    128     {   1L,
    129         5L,
    130         25L,
    131         125L,
    132         625L,
    133         3125L,
    134         15625L,
    135         78125L,
    136         390625L,
    137         1953125L,
    138         9765625L,
    139         48828125L,
    140         244140625L,
    141         1220703125L,
    142         6103515625L,
    143         30517578125L,
    144         152587890625L,
    145         762939453125L,
    146         3814697265625L,
    147         19073486328125L,
    148         95367431640625L,
    149         476837158203125L,
    150         2384185791015625L,
    151         11920928955078125L,
    152         59604644775390625L,
    153         298023223876953125L,
    154         1490116119384765625L,
    155         7450580596923828125L, };
    156 
    157     private static final int[] LONG_FIVE_POW_BIT_LENGTH = new int[LONG_FIVE_POW.length];
    158     private static final int[] LONG_POWERS_OF_TEN_BIT_LENGTH = new int[MathUtils.LONG_POWERS_OF_TEN.length];
    159 
    160     private static final int BI_SCALED_BY_ZERO_LENGTH = 11;
    161 
    162     /**
    163      * An array with the first <code>BigInteger</code> scaled by zero.
    164      * (<code>[0,0],[1,0],...,[10,0]</code>).
    165      */
    166     private static final BigDecimal[] BI_SCALED_BY_ZERO = new BigDecimal[BI_SCALED_BY_ZERO_LENGTH];
    167 
    168     /**
    169      * An array with the zero number scaled by the first positive scales.
    170      * (<code>0*10^0, 0*10^1, ..., 0*10^10</code>).
    171      */
    172     private static final BigDecimal[] ZERO_SCALED_BY = new BigDecimal[11];
    173 
    174     /** An array filled with characters <code>'0'</code>. */
    175     private static final char[] CH_ZEROS = new char[100];
    176 
    177     static {
    178         Arrays.fill(CH_ZEROS, '0');
    179 
    180         for (int i = 0; i < ZERO_SCALED_BY.length; ++i) {
    181             BI_SCALED_BY_ZERO[i] = new BigDecimal(i, 0);
    182             ZERO_SCALED_BY[i] = new BigDecimal(0, i);
    183         }
    184         for (int i = 0; i < LONG_FIVE_POW_BIT_LENGTH.length; ++i) {
    185             LONG_FIVE_POW_BIT_LENGTH[i] = bitLength(LONG_FIVE_POW[i]);
    186         }
    187         for (int i = 0; i < LONG_POWERS_OF_TEN_BIT_LENGTH.length; ++i) {
    188             LONG_POWERS_OF_TEN_BIT_LENGTH[i] = bitLength(MathUtils.LONG_POWERS_OF_TEN[i]);
    189         }
    190 
    191         // Taking the references of useful powers.
    192         TEN_POW = Multiplication.bigTenPows;
    193         FIVE_POW = Multiplication.bigFivePows;
    194     }
    195 
    196     /**
    197      * The constant zero as a {@code BigDecimal}.
    198      */
    199     public static final BigDecimal ZERO = new BigDecimal(0, 0);
    200 
    201     /**
    202      * The constant one as a {@code BigDecimal}.
    203      */
    204     public static final BigDecimal ONE = new BigDecimal(1, 0);
    205 
    206     /**
    207      * The constant ten as a {@code BigDecimal}.
    208      */
    209     public static final BigDecimal TEN = new BigDecimal(10, 0);
    210 
    211     /**
    212      * The arbitrary precision integer (unscaled value) in the internal
    213      * representation of {@code BigDecimal}.
    214      */
    215     private BigInteger intVal;
    216 
    217     private transient int bitLength;
    218 
    219     private transient long smallValue;
    220 
    221     /**
    222      * The 32-bit integer scale in the internal representation of {@code BigDecimal}.
    223      */
    224     private int scale;
    225 
    226     /**
    227      * Represent the number of decimal digits in the unscaled value. This
    228      * precision is calculated the first time, and used in the following calls
    229      * of method <code>precision()</code>. Note that some call to the private
    230      * method <code>inplaceRound()</code> could update this field.
    231      *
    232      * @see #precision()
    233      * @see #inplaceRound(MathContext)
    234      */
    235     private transient int precision = 0;
    236 
    237     private BigDecimal(long smallValue, int scale){
    238         this.smallValue = smallValue;
    239         this.scale = scale;
    240         this.bitLength = bitLength(smallValue);
    241     }
    242 
    243     private BigDecimal(int smallValue, int scale){
    244         this.smallValue = smallValue;
    245         this.scale = scale;
    246         this.bitLength = bitLength(smallValue);
    247     }
    248 
    249     /**
    250      * Constructs a new {@code BigDecimal} instance from a string representation
    251      * given as a character array.
    252      *
    253      * @param in
    254      *            array of characters containing the string representation of
    255      *            this {@code BigDecimal}.
    256      * @param offset
    257      *            first index to be copied.
    258      * @param len
    259      *            number of characters to be used.
    260      * @throws NumberFormatException
    261      *             if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
    262      *             offset+len-1 >= in.length}, or if {@code in} does not
    263      *             contain a valid string representation of a big decimal.
    264      */
    265     public BigDecimal(char[] in, int offset, int len) {
    266         int begin = offset; // first index to be copied
    267         int last = offset + (len - 1); // last index to be copied
    268         String scaleString; // buffer for scale
    269         StringBuilder unscaledBuffer; // buffer for unscaled value
    270         long newScale; // the new scale
    271 
    272         if (in == null) {
    273             throw new NullPointerException("in == null");
    274         }
    275         if ((last >= in.length) || (offset < 0) || (len <= 0) || (last < 0)) {
    276             throw new NumberFormatException("Bad offset/length: offset=" + offset +
    277                     " len=" + len + " in.length=" + in.length);
    278         }
    279         unscaledBuffer = new StringBuilder(len);
    280         int bufLength = 0;
    281         // To skip a possible '+' symbol
    282         if ((offset <= last) && (in[offset] == '+')) {
    283             offset++;
    284             begin++;
    285         }
    286         int counter = 0;
    287         boolean wasNonZero = false;
    288         // Accumulating all digits until a possible decimal point
    289         for (; (offset <= last) && (in[offset] != '.') && (in[offset] != 'e') && (in[offset] != 'E'); offset++) {
    290             if (!wasNonZero) {
    291                 if (in[offset] == '0') {
    292                     counter++;
    293                 } else {
    294                     wasNonZero = true;
    295                 }
    296             }
    297 
    298         }
    299         unscaledBuffer.append(in, begin, offset - begin);
    300         bufLength += offset - begin;
    301         // A decimal point was found
    302         if ((offset <= last) && (in[offset] == '.')) {
    303             offset++;
    304             // Accumulating all digits until a possible exponent
    305             begin = offset;
    306             for (; (offset <= last) && (in[offset] != 'e')
    307             && (in[offset] != 'E'); offset++) {
    308                 if (!wasNonZero) {
    309                     if (in[offset] == '0') {
    310                         counter++;
    311                     } else {
    312                         wasNonZero = true;
    313                     }
    314                 }
    315             }
    316             scale = offset - begin;
    317             bufLength +=scale;
    318             unscaledBuffer.append(in, begin, scale);
    319         } else {
    320             scale = 0;
    321         }
    322         // An exponent was found
    323         if ((offset <= last) && ((in[offset] == 'e') || (in[offset] == 'E'))) {
    324             offset++;
    325             // Checking for a possible sign of scale
    326             begin = offset;
    327             if ((offset <= last) && (in[offset] == '+')) {
    328                 offset++;
    329                 if ((offset <= last) && (in[offset] != '-')) {
    330                     begin++;
    331                 }
    332             }
    333             // Accumulating all remaining digits
    334             scaleString = String.valueOf(in, begin, last + 1 - begin);
    335             // Checking if the scale is defined
    336             newScale = (long)scale - Integer.parseInt(scaleString);
    337             scale = (int)newScale;
    338             if (newScale != scale) {
    339                 throw new NumberFormatException("Scale out of range");
    340             }
    341         }
    342         // Parsing the unscaled value
    343         if (bufLength < 19) {
    344             smallValue = Long.parseLong(unscaledBuffer.toString());
    345             bitLength = bitLength(smallValue);
    346         } else {
    347             setUnscaledValue(new BigInteger(unscaledBuffer.toString()));
    348         }
    349     }
    350 
    351     /**
    352      * Constructs a new {@code BigDecimal} instance from a string representation
    353      * given as a character array.
    354      *
    355      * @param in
    356      *            array of characters containing the string representation of
    357      *            this {@code BigDecimal}.
    358      * @param offset
    359      *            first index to be copied.
    360      * @param len
    361      *            number of characters to be used.
    362      * @param mc
    363      *            rounding mode and precision for the result of this operation.
    364      * @throws NumberFormatException
    365      *             if {@code offset < 0 || len <= 0 || offset+len-1 < 0 ||
    366      *             offset+len-1 >= in.length}, or if {@code in} does not
    367      *             contain a valid string representation of a big decimal.
    368      * @throws ArithmeticException
    369      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    370      *             UNNECESSARY} and the new big decimal cannot be represented
    371      *             within the given precision without rounding.
    372      */
    373     public BigDecimal(char[] in, int offset, int len, MathContext mc) {
    374         this(in, offset, len);
    375         inplaceRound(mc);
    376     }
    377 
    378     /**
    379      * Constructs a new {@code BigDecimal} instance from a string representation
    380      * given as a character array.
    381      *
    382      * @param in
    383      *            array of characters containing the string representation of
    384      *            this {@code BigDecimal}.
    385      * @throws NumberFormatException
    386      *             if {@code in} does not contain a valid string representation
    387      *             of a big decimal.
    388      */
    389     public BigDecimal(char[] in) {
    390         this(in, 0, in.length);
    391     }
    392 
    393     /**
    394      * Constructs a new {@code BigDecimal} instance from a string representation
    395      * given as a character array. The result is rounded according to the
    396      * specified math context.
    397      *
    398      * @param in
    399      *            array of characters containing the string representation of
    400      *            this {@code BigDecimal}.
    401      * @param mc
    402      *            rounding mode and precision for the result of this operation.
    403      * @throws NumberFormatException
    404      *             if {@code in} does not contain a valid string representation
    405      *             of a big decimal.
    406      * @throws ArithmeticException
    407      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    408      *             UNNECESSARY} and the new big decimal cannot be represented
    409      *             within the given precision without rounding.
    410      */
    411     public BigDecimal(char[] in, MathContext mc) {
    412         this(in, 0, in.length);
    413         inplaceRound(mc);
    414     }
    415 
    416     /**
    417      * Constructs a new {@code BigDecimal} instance from a string
    418      * representation.
    419      *
    420      * @throws NumberFormatException
    421      *             if {@code val} does not contain a valid string representation
    422      *             of a big decimal.
    423      */
    424     public BigDecimal(String val) {
    425         this(val.toCharArray(), 0, val.length());
    426     }
    427 
    428     /**
    429      * Constructs a new {@code BigDecimal} instance from a string
    430      * representation. The result is rounded according to the specified math
    431      * context.
    432      *
    433      * @param mc
    434      *            rounding mode and precision for the result of this operation.
    435      * @throws NumberFormatException
    436      *             if {@code val} does not contain a valid string representation
    437      *             of a big decimal.
    438      * @throws ArithmeticException
    439      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    440      *             UNNECESSARY} and the new big decimal cannot be represented
    441      *             within the given precision without rounding.
    442      */
    443     public BigDecimal(String val, MathContext mc) {
    444         this(val.toCharArray(), 0, val.length());
    445         inplaceRound(mc);
    446     }
    447 
    448     /**
    449      * Constructs a new {@code BigDecimal} instance from the 64bit double
    450      * {@code val}. The constructed big decimal is equivalent to the given
    451      * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
    452      * 0.1000000000000000055511151231257827021181583404541015625}. This happens
    453      * as {@code 0.1} cannot be represented exactly in binary.
    454      * <p>
    455      * To generate a big decimal instance which is equivalent to {@code 0.1} use
    456      * the {@code BigDecimal(String)} constructor.
    457      *
    458      * @param val
    459      *            double value to be converted to a {@code BigDecimal} instance.
    460      * @throws NumberFormatException
    461      *             if {@code val} is infinity or not a number.
    462      */
    463     public BigDecimal(double val) {
    464         if (Double.isInfinite(val) || Double.isNaN(val)) {
    465             throw new NumberFormatException("Infinity or NaN: " + val);
    466         }
    467         long bits = Double.doubleToLongBits(val); // IEEE-754
    468         long mantissa;
    469         int trailingZeros;
    470         // Extracting the exponent, note that the bias is 1023
    471         scale = 1075 - (int)((bits >> 52) & 0x7FFL);
    472         // Extracting the 52 bits of the mantissa.
    473         mantissa = (scale == 1075) ? (bits & 0xFFFFFFFFFFFFFL) << 1
    474                 : (bits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L;
    475         if (mantissa == 0) {
    476             scale = 0;
    477             precision = 1;
    478         }
    479         // To simplify all factors '2' in the mantissa
    480         if (scale > 0) {
    481             trailingZeros = Math.min(scale, Long.numberOfTrailingZeros(mantissa));
    482             mantissa >>>= trailingZeros;
    483             scale -= trailingZeros;
    484         }
    485         // Calculating the new unscaled value and the new scale
    486         if((bits >> 63) != 0) {
    487             mantissa = -mantissa;
    488         }
    489         int mantissaBits = bitLength(mantissa);
    490         if (scale < 0) {
    491             bitLength = mantissaBits == 0 ? 0 : mantissaBits - scale;
    492             if(bitLength < 64) {
    493                 smallValue = mantissa << (-scale);
    494             } else {
    495                 BigInt bi = new BigInt();
    496                 bi.putLongInt(mantissa);
    497                 bi.shift(-scale);
    498                 intVal = new BigInteger(bi);
    499             }
    500             scale = 0;
    501         } else if (scale > 0) {
    502             // m * 2^e =  (m * 5^(-e)) * 10^e
    503             if(scale < LONG_FIVE_POW.length
    504                     && mantissaBits+LONG_FIVE_POW_BIT_LENGTH[scale] < 64) {
    505                 smallValue = mantissa * LONG_FIVE_POW[scale];
    506                 bitLength = bitLength(smallValue);
    507             } else {
    508                 setUnscaledValue(Multiplication.multiplyByFivePow(BigInteger.valueOf(mantissa), scale));
    509             }
    510         } else { // scale == 0
    511             smallValue = mantissa;
    512             bitLength = mantissaBits;
    513         }
    514     }
    515 
    516     /**
    517      * Constructs a new {@code BigDecimal} instance from the 64bit double
    518      * {@code val}. The constructed big decimal is equivalent to the given
    519      * double. For example, {@code new BigDecimal(0.1)} is equal to {@code
    520      * 0.1000000000000000055511151231257827021181583404541015625}. This happens
    521      * as {@code 0.1} cannot be represented exactly in binary.
    522      * <p>
    523      * To generate a big decimal instance which is equivalent to {@code 0.1} use
    524      * the {@code BigDecimal(String)} constructor.
    525      *
    526      * @param val
    527      *            double value to be converted to a {@code BigDecimal} instance.
    528      * @param mc
    529      *            rounding mode and precision for the result of this operation.
    530      * @throws NumberFormatException
    531      *             if {@code val} is infinity or not a number.
    532      * @throws ArithmeticException
    533      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    534      *             UNNECESSARY} and the new big decimal cannot be represented
    535      *             within the given precision without rounding.
    536      */
    537     public BigDecimal(double val, MathContext mc) {
    538         this(val);
    539         inplaceRound(mc);
    540     }
    541 
    542     /**
    543      * Constructs a new {@code BigDecimal} instance from the given big integer
    544      * {@code val}. The scale of the result is {@code 0}.
    545      */
    546     public BigDecimal(BigInteger val) {
    547         this(val, 0);
    548     }
    549 
    550     /**
    551      * Constructs a new {@code BigDecimal} instance from the given big integer
    552      * {@code val}. The scale of the result is {@code 0}.
    553      *
    554      * @param mc
    555      *            rounding mode and precision for the result of this operation.
    556      * @throws ArithmeticException
    557      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    558      *             UNNECESSARY} and the new big decimal cannot be represented
    559      *             within the given precision without rounding.
    560      */
    561     public BigDecimal(BigInteger val, MathContext mc) {
    562         this(val);
    563         inplaceRound(mc);
    564     }
    565 
    566     /**
    567      * Constructs a new {@code BigDecimal} instance from a given unscaled value
    568      * {@code unscaledVal} and a given scale. The value of this instance is
    569      * {@code unscaledVal * 10<sup>-scale</sup>}).
    570      *
    571      * @throws NullPointerException
    572      *             if {@code unscaledVal == null}.
    573      */
    574     public BigDecimal(BigInteger unscaledVal, int scale) {
    575         if (unscaledVal == null) {
    576             throw new NullPointerException("unscaledVal == null");
    577         }
    578         this.scale = scale;
    579         setUnscaledValue(unscaledVal);
    580     }
    581 
    582     /**
    583      * Constructs a new {@code BigDecimal} instance from a given unscaled value
    584      * {@code unscaledVal} and a given scale. The value of this instance is
    585      * {@code unscaledVal * 10<sup>-scale</sup>). The result is rounded according
    586      * to the specified math context.
    587      *
    588      * @param mc
    589      *            rounding mode and precision for the result of this operation.
    590      * @throws ArithmeticException
    591      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    592      *             UNNECESSARY} and the new big decimal cannot be represented
    593      *             within the given precision without rounding.
    594      * @throws NullPointerException
    595      *             if {@code unscaledVal == null}.
    596      */
    597     public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
    598         this(unscaledVal, scale);
    599         inplaceRound(mc);
    600     }
    601 
    602     /**
    603      * Constructs a new {@code BigDecimal} instance from the given int
    604      * {@code val}. The scale of the result is 0.
    605      *
    606      * @param val
    607      *            int value to be converted to a {@code BigDecimal} instance.
    608      */
    609     public BigDecimal(int val) {
    610         this(val,0);
    611     }
    612 
    613     /**
    614      * Constructs a new {@code BigDecimal} instance from the given int {@code
    615      * val}. The scale of the result is {@code 0}. The result is rounded
    616      * according to the specified math context.
    617      *
    618      * @param val
    619      *            int value to be converted to a {@code BigDecimal} instance.
    620      * @param mc
    621      *            rounding mode and precision for the result of this operation.
    622      * @throws ArithmeticException
    623      *             if {@code mc.precision > 0} and {@code c.roundingMode ==
    624      *             UNNECESSARY} and the new big decimal cannot be represented
    625      *             within the given precision without rounding.
    626      */
    627     public BigDecimal(int val, MathContext mc) {
    628         this(val,0);
    629         inplaceRound(mc);
    630     }
    631 
    632     /**
    633      * Constructs a new {@code BigDecimal} instance from the given long {@code
    634      * val}. The scale of the result is {@code 0}.
    635      *
    636      * @param val
    637      *            long value to be converted to a {@code BigDecimal} instance.
    638      */
    639     public BigDecimal(long val) {
    640         this(val,0);
    641     }
    642 
    643     /**
    644      * Constructs a new {@code BigDecimal} instance from the given long {@code
    645      * val}. The scale of the result is {@code 0}. The result is rounded
    646      * according to the specified math context.
    647      *
    648      * @param val
    649      *            long value to be converted to a {@code BigDecimal} instance.
    650      * @param mc
    651      *            rounding mode and precision for the result of this operation.
    652      * @throws ArithmeticException
    653      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
    654      *             UNNECESSARY} and the new big decimal cannot be represented
    655      *             within the given precision without rounding.
    656      */
    657     public BigDecimal(long val, MathContext mc) {
    658         this(val);
    659         inplaceRound(mc);
    660     }
    661 
    662     /* Public Methods */
    663 
    664     /**
    665      * Returns a new {@code BigDecimal} instance whose value is equal to {@code
    666      * unscaledVal * 10<sup>-scale</sup>}). The scale of the result is {@code
    667      * scale}, and its unscaled value is {@code unscaledVal}.
    668      */
    669     public static BigDecimal valueOf(long unscaledVal, int scale) {
    670         if (scale == 0) {
    671             return valueOf(unscaledVal);
    672         }
    673         if ((unscaledVal == 0) && (scale >= 0)
    674                 && (scale < ZERO_SCALED_BY.length)) {
    675             return ZERO_SCALED_BY[scale];
    676         }
    677         return new BigDecimal(unscaledVal, scale);
    678     }
    679 
    680     /**
    681      * Returns a new {@code BigDecimal} instance whose value is equal to {@code
    682      * unscaledVal}. The scale of the result is {@code 0}, and its unscaled
    683      * value is {@code unscaledVal}.
    684      *
    685      * @param unscaledVal
    686      *            value to be converted to a {@code BigDecimal}.
    687      * @return {@code BigDecimal} instance with the value {@code unscaledVal}.
    688      */
    689     public static BigDecimal valueOf(long unscaledVal) {
    690         if ((unscaledVal >= 0) && (unscaledVal < BI_SCALED_BY_ZERO_LENGTH)) {
    691             return BI_SCALED_BY_ZERO[(int)unscaledVal];
    692         }
    693         return new BigDecimal(unscaledVal,0);
    694     }
    695 
    696     /**
    697      * Returns a new {@code BigDecimal} instance whose value is equal to {@code
    698      * val}. The new decimal is constructed as if the {@code BigDecimal(String)}
    699      * constructor is called with an argument which is equal to {@code
    700      * Double.toString(val)}. For example, {@code valueOf("0.1")} is converted to
    701      * (unscaled=1, scale=1), although the double {@code 0.1} cannot be
    702      * represented exactly as a double value. In contrast to that, a new {@code
    703      * BigDecimal(0.1)} instance has the value {@code
    704      * 0.1000000000000000055511151231257827021181583404541015625} with an
    705      * unscaled value {@code 1000000000000000055511151231257827021181583404541015625}
    706      * and the scale {@code 55}.
    707      *
    708      * @param val
    709      *            double value to be converted to a {@code BigDecimal}.
    710      * @return {@code BigDecimal} instance with the value {@code val}.
    711      * @throws NumberFormatException
    712      *             if {@code val} is infinite or {@code val} is not a number
    713      */
    714     public static BigDecimal valueOf(double val) {
    715         if (Double.isInfinite(val) || Double.isNaN(val)) {
    716             throw new NumberFormatException("Infinity or NaN: " + val);
    717         }
    718         return new BigDecimal(Double.toString(val));
    719     }
    720 
    721     /**
    722      * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
    723      * The scale of the result is the maximum of the scales of the two
    724      * arguments.
    725      *
    726      * @param augend
    727      *            value to be added to {@code this}.
    728      * @return {@code this + augend}.
    729      * @throws NullPointerException
    730      *             if {@code augend == null}.
    731      */
    732     public BigDecimal add(BigDecimal augend) {
    733         int diffScale = this.scale - augend.scale;
    734         // Fast return when some operand is zero
    735         if (this.isZero()) {
    736             if (diffScale <= 0) {
    737                 return augend;
    738             }
    739             if (augend.isZero()) {
    740                 return this;
    741             }
    742         } else if (augend.isZero()) {
    743             if (diffScale >= 0) {
    744                 return this;
    745             }
    746         }
    747         // Let be:  this = [u1,s1]  and  augend = [u2,s2]
    748         if (diffScale == 0) {
    749             // case s1 == s2: [u1 + u2 , s1]
    750             if (Math.max(this.bitLength, augend.bitLength) + 1 < 64) {
    751                 return valueOf(this.smallValue + augend.smallValue, this.scale);
    752             }
    753             return new BigDecimal(this.getUnscaledValue().add(augend.getUnscaledValue()), this.scale);
    754         } else if (diffScale > 0) {
    755             // case s1 > s2 : [(u1 + u2) * 10 ^ (s1 - s2) , s1]
    756             return addAndMult10(this, augend, diffScale);
    757         } else {// case s2 > s1 : [(u2 + u1) * 10 ^ (s2 - s1) , s2]
    758             return addAndMult10(augend, this, -diffScale);
    759         }
    760     }
    761 
    762     private static BigDecimal addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale) {
    763         if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
    764                 Math.max(thisValue.bitLength,augend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) {
    765             return valueOf(thisValue.smallValue+augend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],thisValue.scale);
    766         } else {
    767             BigInt bi = Multiplication.multiplyByTenPow(augend.getUnscaledValue(),diffScale).getBigInt();
    768             bi.add(thisValue.getUnscaledValue().getBigInt());
    769             return new BigDecimal(new BigInteger(bi), thisValue.scale);
    770         }
    771     }
    772 
    773     /**
    774      * Returns a new {@code BigDecimal} whose value is {@code this + augend}.
    775      * The result is rounded according to the passed context {@code mc}.
    776      *
    777      * @param augend
    778      *            value to be added to {@code this}.
    779      * @param mc
    780      *            rounding mode and precision for the result of this operation.
    781      * @return {@code this + augend}.
    782      * @throws NullPointerException
    783      *             if {@code augend == null} or {@code mc == null}.
    784      */
    785     public BigDecimal add(BigDecimal augend, MathContext mc) {
    786         BigDecimal larger; // operand with the largest unscaled value
    787         BigDecimal smaller; // operand with the smallest unscaled value
    788         BigInteger tempBI;
    789         long diffScale = (long)this.scale - augend.scale;
    790         int largerSignum;
    791         // Some operand is zero or the precision is infinity
    792         if ((augend.isZero()) || (this.isZero())
    793                 || (mc.getPrecision() == 0)) {
    794             return add(augend).round(mc);
    795         }
    796         // Cases where there is room for optimizations
    797         if (this.approxPrecision() < diffScale - 1) {
    798             larger = augend;
    799             smaller = this;
    800         } else if (augend.approxPrecision() < -diffScale - 1) {
    801             larger = this;
    802             smaller = augend;
    803         } else {// No optimization is done
    804             return add(augend).round(mc);
    805         }
    806         if (mc.getPrecision() >= larger.approxPrecision()) {
    807             // No optimization is done
    808             return add(augend).round(mc);
    809         }
    810         // Cases where it's unnecessary to add two numbers with very different scales
    811         largerSignum = larger.signum();
    812         if (largerSignum == smaller.signum()) {
    813             tempBI = Multiplication.multiplyByPositiveInt(larger.getUnscaledValue(),10)
    814             .add(BigInteger.valueOf(largerSignum));
    815         } else {
    816             tempBI = larger.getUnscaledValue().subtract(
    817                     BigInteger.valueOf(largerSignum));
    818             tempBI = Multiplication.multiplyByPositiveInt(tempBI,10)
    819             .add(BigInteger.valueOf(largerSignum * 9));
    820         }
    821         // Rounding the improved adding
    822         larger = new BigDecimal(tempBI, larger.scale + 1);
    823         return larger.round(mc);
    824     }
    825 
    826     /**
    827      * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
    828      * The scale of the result is the maximum of the scales of the two arguments.
    829      *
    830      * @param subtrahend
    831      *            value to be subtracted from {@code this}.
    832      * @return {@code this - subtrahend}.
    833      * @throws NullPointerException
    834      *             if {@code subtrahend == null}.
    835      */
    836     public BigDecimal subtract(BigDecimal subtrahend) {
    837         int diffScale = this.scale - subtrahend.scale;
    838         // Fast return when some operand is zero
    839         if (this.isZero()) {
    840             if (diffScale <= 0) {
    841                 return subtrahend.negate();
    842             }
    843             if (subtrahend.isZero()) {
    844                 return this;
    845             }
    846         } else if (subtrahend.isZero()) {
    847             if (diffScale >= 0) {
    848                 return this;
    849             }
    850         }
    851         // Let be: this = [u1,s1] and subtrahend = [u2,s2] so:
    852         if (diffScale == 0) {
    853             // case s1 = s2 : [u1 - u2 , s1]
    854             if (Math.max(this.bitLength, subtrahend.bitLength) + 1 < 64) {
    855                 return valueOf(this.smallValue - subtrahend.smallValue,this.scale);
    856             }
    857             return new BigDecimal(this.getUnscaledValue().subtract(subtrahend.getUnscaledValue()), this.scale);
    858         } else if (diffScale > 0) {
    859             // case s1 > s2 : [ u1 - u2 * 10 ^ (s1 - s2) , s1 ]
    860             if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
    861                     Math.max(this.bitLength,subtrahend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) {
    862                 return valueOf(this.smallValue-subtrahend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],this.scale);
    863             }
    864             return new BigDecimal(this.getUnscaledValue().subtract(
    865                     Multiplication.multiplyByTenPow(subtrahend.getUnscaledValue(),diffScale)), this.scale);
    866         } else {// case s2 > s1 : [ u1 * 10 ^ (s2 - s1) - u2 , s2 ]
    867             diffScale = -diffScale;
    868             if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
    869                     Math.max(this.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale],subtrahend.bitLength)+1<64) {
    870                 return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale]-subtrahend.smallValue,subtrahend.scale);
    871             }
    872             return new BigDecimal(Multiplication.multiplyByTenPow(this.getUnscaledValue(),diffScale)
    873             .subtract(subtrahend.getUnscaledValue()), subtrahend.scale);
    874         }
    875     }
    876 
    877     /**
    878      * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}.
    879      * The result is rounded according to the passed context {@code mc}.
    880      *
    881      * @param subtrahend
    882      *            value to be subtracted from {@code this}.
    883      * @param mc
    884      *            rounding mode and precision for the result of this operation.
    885      * @return {@code this - subtrahend}.
    886      * @throws NullPointerException
    887      *             if {@code subtrahend == null} or {@code mc == null}.
    888      */
    889     public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
    890         long diffScale = subtrahend.scale - (long)this.scale;
    891         int thisSignum;
    892         BigDecimal leftOperand; // it will be only the left operand (this)
    893         BigInteger tempBI;
    894         // Some operand is zero or the precision is infinity
    895         if ((subtrahend.isZero()) || (this.isZero())
    896                 || (mc.getPrecision() == 0)) {
    897             return subtract(subtrahend).round(mc);
    898         }
    899         // Now:   this != 0   and   subtrahend != 0
    900         if (subtrahend.approxPrecision() < diffScale - 1) {
    901             // Cases where it is unnecessary to subtract two numbers with very different scales
    902             if (mc.getPrecision() < this.approxPrecision()) {
    903                 thisSignum = this.signum();
    904                 if (thisSignum != subtrahend.signum()) {
    905                     tempBI = Multiplication.multiplyByPositiveInt(this.getUnscaledValue(), 10)
    906                     .add(BigInteger.valueOf(thisSignum));
    907                 } else {
    908                     tempBI = this.getUnscaledValue().subtract(BigInteger.valueOf(thisSignum));
    909                     tempBI = Multiplication.multiplyByPositiveInt(tempBI, 10)
    910                     .add(BigInteger.valueOf(thisSignum * 9));
    911                 }
    912                 // Rounding the improved subtracting
    913                 leftOperand = new BigDecimal(tempBI, this.scale + 1);
    914                 return leftOperand.round(mc);
    915             }
    916         }
    917         // No optimization is done
    918         return subtract(subtrahend).round(mc);
    919     }
    920 
    921     /**
    922      * Returns a new {@code BigDecimal} whose value is {@code this *
    923      * multiplicand}. The scale of the result is the sum of the scales of the
    924      * two arguments.
    925      *
    926      * @param multiplicand
    927      *            value to be multiplied with {@code this}.
    928      * @return {@code this * multiplicand}.
    929      * @throws NullPointerException
    930      *             if {@code multiplicand == null}.
    931      */
    932     public BigDecimal multiply(BigDecimal multiplicand) {
    933         long newScale = (long)this.scale + multiplicand.scale;
    934 
    935         if ((this.isZero()) || (multiplicand.isZero())) {
    936             return zeroScaledBy(newScale);
    937         }
    938         /* Let be: this = [u1,s1] and multiplicand = [u2,s2] so:
    939          * this x multiplicand = [ s1 * s2 , s1 + s2 ] */
    940         if(this.bitLength + multiplicand.bitLength < 64) {
    941             return valueOf(this.smallValue*multiplicand.smallValue, safeLongToInt(newScale));
    942         }
    943         return new BigDecimal(this.getUnscaledValue().multiply(
    944                 multiplicand.getUnscaledValue()), safeLongToInt(newScale));
    945     }
    946 
    947     /**
    948      * Returns a new {@code BigDecimal} whose value is {@code this *
    949      * multiplicand}. The result is rounded according to the passed context
    950      * {@code mc}.
    951      *
    952      * @param multiplicand
    953      *            value to be multiplied with {@code this}.
    954      * @param mc
    955      *            rounding mode and precision for the result of this operation.
    956      * @return {@code this * multiplicand}.
    957      * @throws NullPointerException
    958      *             if {@code multiplicand == null} or {@code mc == null}.
    959      */
    960     public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
    961         BigDecimal result = multiply(multiplicand);
    962 
    963         result.inplaceRound(mc);
    964         return result;
    965     }
    966 
    967     /**
    968      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
    969      * As scale of the result the parameter {@code scale} is used. If rounding
    970      * is required to meet the specified scale, then the specified rounding mode
    971      * {@code roundingMode} is applied.
    972      *
    973      * @param divisor
    974      *            value by which {@code this} is divided.
    975      * @param scale
    976      *            the scale of the result returned.
    977      * @param roundingMode
    978      *            rounding mode to be used to round the result.
    979      * @return {@code this / divisor} rounded according to the given rounding
    980      *         mode.
    981      * @throws NullPointerException
    982      *             if {@code divisor == null}.
    983      * @throws IllegalArgumentException
    984      *             if {@code roundingMode} is not a valid rounding mode.
    985      * @throws ArithmeticException
    986      *             if {@code divisor == 0}.
    987      * @throws ArithmeticException
    988      *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
    989      *             necessary according to the given scale.
    990      */
    991     public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
    992         return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
    993     }
    994 
    995     /**
    996      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
    997      * As scale of the result the parameter {@code scale} is used. If rounding
    998      * is required to meet the specified scale, then the specified rounding mode
    999      * {@code roundingMode} is applied.
   1000      *
   1001      * @param divisor
   1002      *            value by which {@code this} is divided.
   1003      * @param scale
   1004      *            the scale of the result returned.
   1005      * @param roundingMode
   1006      *            rounding mode to be used to round the result.
   1007      * @return {@code this / divisor} rounded according to the given rounding
   1008      *         mode.
   1009      * @throws NullPointerException
   1010      *             if {@code divisor == null} or {@code roundingMode == null}.
   1011      * @throws ArithmeticException
   1012      *             if {@code divisor == 0}.
   1013      * @throws ArithmeticException
   1014      *             if {@code roundingMode == RoundingMode.UNNECESSAR}Y and
   1015      *             rounding is necessary according to the given scale and given
   1016      *             precision.
   1017      */
   1018     public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
   1019         // Let be: this = [u1,s1]  and  divisor = [u2,s2]
   1020         if (roundingMode == null) {
   1021             throw new NullPointerException("roundingMode == null");
   1022         }
   1023         if (divisor.isZero()) {
   1024             throw new ArithmeticException("Division by zero");
   1025         }
   1026 
   1027         long diffScale = ((long)this.scale - divisor.scale) - scale;
   1028         if(this.bitLength < 64 && divisor.bitLength < 64 ) {
   1029             if(diffScale == 0) {
   1030                 return dividePrimitiveLongs(this.smallValue,
   1031                         divisor.smallValue,
   1032                         scale,
   1033                         roundingMode );
   1034             } else if(diffScale > 0) {
   1035                 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
   1036                         divisor.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale] < 64) {
   1037                     return dividePrimitiveLongs(this.smallValue,
   1038                             divisor.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],
   1039                             scale,
   1040                             roundingMode);
   1041                 }
   1042             } else { // diffScale < 0
   1043                 if(-diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
   1044                         this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-diffScale] < 64) {
   1045                     return dividePrimitiveLongs(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale],
   1046                             divisor.smallValue,
   1047                             scale,
   1048                             roundingMode);
   1049                 }
   1050 
   1051             }
   1052         }
   1053         BigInteger scaledDividend = this.getUnscaledValue();
   1054         BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2'
   1055 
   1056         if (diffScale > 0) {
   1057             // Multiply 'u2'  by:  10^((s1 - s2) - scale)
   1058             scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale);
   1059         } else if (diffScale < 0) {
   1060             // Multiply 'u1'  by:  10^(scale - (s1 - s2))
   1061             scaledDividend  = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale);
   1062         }
   1063         return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode);
   1064         }
   1065 
   1066     private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) {
   1067 
   1068         BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor);  // quotient and remainder
   1069         // If after division there is a remainder...
   1070         BigInteger quotient = quotAndRem[0];
   1071         BigInteger remainder = quotAndRem[1];
   1072         if (remainder.signum() == 0) {
   1073             return new BigDecimal(quotient, scale);
   1074         }
   1075         int sign = scaledDividend.signum() * scaledDivisor.signum();
   1076         int compRem;                                      // 'compare to remainder'
   1077         if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2
   1078             long rem = remainder.longValue();
   1079             long divisor = scaledDivisor.longValue();
   1080             compRem = longCompareTo(Math.abs(rem) * 2,Math.abs(divisor));
   1081             // To look if there is a carry
   1082             compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
   1083                     sign * (5 + compRem), roundingMode);
   1084 
   1085         } else {
   1086             // Checking if:  remainder * 2 >= scaledDivisor
   1087             compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs());
   1088             compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
   1089                     sign * (5 + compRem), roundingMode);
   1090         }
   1091             if (compRem != 0) {
   1092             if(quotient.bitLength() < 63) {
   1093                 return valueOf(quotient.longValue() + compRem,scale);
   1094             }
   1095             quotient = quotient.add(BigInteger.valueOf(compRem));
   1096             return new BigDecimal(quotient, scale);
   1097         }
   1098         // Constructing the result with the appropriate unscaled value
   1099         return new BigDecimal(quotient, scale);
   1100     }
   1101 
   1102     private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) {
   1103         long quotient = scaledDividend / scaledDivisor;
   1104         long remainder = scaledDividend % scaledDivisor;
   1105         int sign = Long.signum( scaledDividend ) * Long.signum( scaledDivisor );
   1106         if (remainder != 0) {
   1107             // Checking if:  remainder * 2 >= scaledDivisor
   1108             int compRem;                                      // 'compare to remainder'
   1109             compRem = longCompareTo(Math.abs(remainder) * 2,Math.abs(scaledDivisor));
   1110             // To look if there is a carry
   1111             quotient += roundingBehavior(((int)quotient) & 1,
   1112                     sign * (5 + compRem),
   1113                     roundingMode);
   1114         }
   1115         // Constructing the result with the appropriate unscaled value
   1116         return valueOf(quotient, scale);
   1117     }
   1118 
   1119     /**
   1120      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
   1121      * The scale of the result is the scale of {@code this}. If rounding is
   1122      * required to meet the specified scale, then the specified rounding mode
   1123      * {@code roundingMode} is applied.
   1124      *
   1125      * @param divisor
   1126      *            value by which {@code this} is divided.
   1127      * @param roundingMode
   1128      *            rounding mode to be used to round the result.
   1129      * @return {@code this / divisor} rounded according to the given rounding
   1130      *         mode.
   1131      * @throws NullPointerException
   1132      *             if {@code divisor == null}.
   1133      * @throws IllegalArgumentException
   1134      *             if {@code roundingMode} is not a valid rounding mode.
   1135      * @throws ArithmeticException
   1136      *             if {@code divisor == 0}.
   1137      * @throws ArithmeticException
   1138      *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
   1139      *             necessary according to the scale of this.
   1140      */
   1141     public BigDecimal divide(BigDecimal divisor, int roundingMode) {
   1142         return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
   1143     }
   1144 
   1145     /**
   1146      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
   1147      * The scale of the result is the scale of {@code this}. If rounding is
   1148      * required to meet the specified scale, then the specified rounding mode
   1149      * {@code roundingMode} is applied.
   1150      *
   1151      * @param divisor
   1152      *            value by which {@code this} is divided.
   1153      * @param roundingMode
   1154      *            rounding mode to be used to round the result.
   1155      * @return {@code this / divisor} rounded according to the given rounding
   1156      *         mode.
   1157      * @throws NullPointerException
   1158      *             if {@code divisor == null} or {@code roundingMode == null}.
   1159      * @throws ArithmeticException
   1160      *             if {@code divisor == 0}.
   1161      * @throws ArithmeticException
   1162      *             if {@code roundingMode == RoundingMode.UNNECESSARY} and
   1163      *             rounding is necessary according to the scale of this.
   1164      */
   1165     public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
   1166         return divide(divisor, scale, roundingMode);
   1167     }
   1168 
   1169     /**
   1170      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
   1171      * The scale of the result is the difference of the scales of {@code this}
   1172      * and {@code divisor}. If the exact result requires more digits, then the
   1173      * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125}
   1174      * which has a scale of {@code 7} and precision {@code 5}.
   1175      *
   1176      * @param divisor
   1177      *            value by which {@code this} is divided.
   1178      * @return {@code this / divisor}.
   1179      * @throws NullPointerException
   1180      *             if {@code divisor == null}.
   1181      * @throws ArithmeticException
   1182      *             if {@code divisor == 0}.
   1183      * @throws ArithmeticException
   1184      *             if the result cannot be represented exactly.
   1185      */
   1186     public BigDecimal divide(BigDecimal divisor) {
   1187         BigInteger p = this.getUnscaledValue();
   1188         BigInteger q = divisor.getUnscaledValue();
   1189         BigInteger gcd; // greatest common divisor between 'p' and 'q'
   1190         BigInteger quotAndRem[];
   1191         long diffScale = (long)scale - divisor.scale;
   1192         int newScale; // the new scale for final quotient
   1193         int k; // number of factors "2" in 'q'
   1194         int l = 0; // number of factors "5" in 'q'
   1195         int i = 1;
   1196         int lastPow = FIVE_POW.length - 1;
   1197 
   1198         if (divisor.isZero()) {
   1199             throw new ArithmeticException("Division by zero");
   1200         }
   1201         if (p.signum() == 0) {
   1202             return zeroScaledBy(diffScale);
   1203         }
   1204         // To divide both by the GCD
   1205         gcd = p.gcd(q);
   1206         p = p.divide(gcd);
   1207         q = q.divide(gcd);
   1208         // To simplify all "2" factors of q, dividing by 2^k
   1209         k = q.getLowestSetBit();
   1210         q = q.shiftRight(k);
   1211         // To simplify all "5" factors of q, dividing by 5^l
   1212         do {
   1213             quotAndRem = q.divideAndRemainder(FIVE_POW[i]);
   1214             if (quotAndRem[1].signum() == 0) {
   1215                 l += i;
   1216                 if (i < lastPow) {
   1217                     i++;
   1218                 }
   1219                 q = quotAndRem[0];
   1220             } else {
   1221                 if (i == 1) {
   1222                     break;
   1223                 }
   1224                 i = 1;
   1225             }
   1226         } while (true);
   1227         // If  abs(q) != 1  then the quotient is periodic
   1228         if (!q.abs().equals(BigInteger.ONE)) {
   1229             throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result");
   1230         }
   1231         // The sign of the is fixed and the quotient will be saved in 'p'
   1232         if (q.signum() < 0) {
   1233             p = p.negate();
   1234         }
   1235         // Checking if the new scale is out of range
   1236         newScale = safeLongToInt(diffScale + Math.max(k, l));
   1237         // k >= 0  and  l >= 0  implies that  k - l  is in the 32-bit range
   1238         i = k - l;
   1239 
   1240         p = (i > 0) ? Multiplication.multiplyByFivePow(p, i)
   1241         : p.shiftLeft(-i);
   1242         return new BigDecimal(p, newScale);
   1243     }
   1244 
   1245     /**
   1246      * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
   1247      * The result is rounded according to the passed context {@code mc}. If the
   1248      * passed math context specifies precision {@code 0}, then this call is
   1249      * equivalent to {@code this.divide(divisor)}.
   1250      *
   1251      * @param divisor
   1252      *            value by which {@code this} is divided.
   1253      * @param mc
   1254      *            rounding mode and precision for the result of this operation.
   1255      * @return {@code this / divisor}.
   1256      * @throws NullPointerException
   1257      *             if {@code divisor == null} or {@code mc == null}.
   1258      * @throws ArithmeticException
   1259      *             if {@code divisor == 0}.
   1260      * @throws ArithmeticException
   1261      *             if {@code mc.getRoundingMode() == UNNECESSARY} and rounding
   1262      *             is necessary according {@code mc.getPrecision()}.
   1263      */
   1264     public BigDecimal divide(BigDecimal divisor, MathContext mc) {
   1265         /* Calculating how many zeros must be append to 'dividend'
   1266          * to obtain a  quotient with at least 'mc.precision()' digits */
   1267         long trailingZeros = mc.getPrecision() + 2L
   1268                 + divisor.approxPrecision() - approxPrecision();
   1269         long diffScale = (long)scale - divisor.scale;
   1270         long newScale = diffScale; // scale of the final quotient
   1271         int compRem; // to compare the remainder
   1272         int i = 1; // index
   1273         int lastPow = TEN_POW.length - 1; // last power of ten
   1274         BigInteger integerQuot; // for temporal results
   1275         BigInteger quotAndRem[] = {getUnscaledValue()};
   1276         // In special cases it reduces the problem to call the dual method
   1277         if ((mc.getPrecision() == 0) || (this.isZero())
   1278         || (divisor.isZero())) {
   1279             return this.divide(divisor);
   1280         }
   1281         if (trailingZeros > 0) {
   1282             // To append trailing zeros at end of dividend
   1283             quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(trailingZeros) );
   1284             newScale += trailingZeros;
   1285         }
   1286         quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() );
   1287         integerQuot = quotAndRem[0];
   1288         // Calculating the exact quotient with at least 'mc.precision()' digits
   1289         if (quotAndRem[1].signum() != 0) {
   1290             // Checking if:   2 * remainder >= divisor ?
   1291             compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() );
   1292             // quot := quot * 10 + r;     with 'r' in {-6,-5,-4, 0,+4,+5,+6}
   1293             integerQuot = integerQuot.multiply(BigInteger.TEN)
   1294             .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem)));
   1295             newScale++;
   1296         } else {
   1297             // To strip trailing zeros until the preferred scale is reached
   1298             while (!integerQuot.testBit(0)) {
   1299                 quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]);
   1300                 if ((quotAndRem[1].signum() == 0)
   1301                         && (newScale - i >= diffScale)) {
   1302                     newScale -= i;
   1303                     if (i < lastPow) {
   1304                         i++;
   1305                     }
   1306                     integerQuot = quotAndRem[0];
   1307                 } else {
   1308                     if (i == 1) {
   1309                         break;
   1310                     }
   1311                     i = 1;
   1312                 }
   1313             }
   1314         }
   1315         // To perform rounding
   1316         return new BigDecimal(integerQuot, safeLongToInt(newScale), mc);
   1317     }
   1318 
   1319     /**
   1320      * Returns a new {@code BigDecimal} whose value is the integral part of
   1321      * {@code this / divisor}. The quotient is rounded down towards zero to the
   1322      * next integer. For example, {@code 0.5/0.2 = 2}.
   1323      *
   1324      * @param divisor
   1325      *            value by which {@code this} is divided.
   1326      * @return integral part of {@code this / divisor}.
   1327      * @throws NullPointerException
   1328      *             if {@code divisor == null}.
   1329      * @throws ArithmeticException
   1330      *             if {@code divisor == 0}.
   1331      */
   1332     public BigDecimal divideToIntegralValue(BigDecimal divisor) {
   1333         BigInteger integralValue; // the integer of result
   1334         BigInteger powerOfTen; // some power of ten
   1335         BigInteger quotAndRem[] = {getUnscaledValue()};
   1336         long newScale = (long)this.scale - divisor.scale;
   1337         long tempScale = 0;
   1338         int i = 1;
   1339         int lastPow = TEN_POW.length - 1;
   1340 
   1341         if (divisor.isZero()) {
   1342             throw new ArithmeticException("Division by zero");
   1343         }
   1344         if ((divisor.approxPrecision() + newScale > this.approxPrecision() + 1L)
   1345         || (this.isZero())) {
   1346             /* If the divisor's integer part is greater than this's integer part,
   1347              * the result must be zero with the appropriate scale */
   1348             integralValue = BigInteger.ZERO;
   1349         } else if (newScale == 0) {
   1350             integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() );
   1351         } else if (newScale > 0) {
   1352             powerOfTen = Multiplication.powerOf10(newScale);
   1353             integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) );
   1354             integralValue = integralValue.multiply(powerOfTen);
   1355         } else {// (newScale < 0)
   1356             powerOfTen = Multiplication.powerOf10(-newScale);
   1357             integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() );
   1358             // To strip trailing zeros approximating to the preferred scale
   1359             while (!integralValue.testBit(0)) {
   1360                 quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]);
   1361                 if ((quotAndRem[1].signum() == 0)
   1362                         && (tempScale - i >= newScale)) {
   1363                     tempScale -= i;
   1364                     if (i < lastPow) {
   1365                         i++;
   1366                     }
   1367                     integralValue = quotAndRem[0];
   1368                 } else {
   1369                     if (i == 1) {
   1370                         break;
   1371                     }
   1372                     i = 1;
   1373                 }
   1374             }
   1375             newScale = tempScale;
   1376         }
   1377         return ((integralValue.signum() == 0)
   1378         ? zeroScaledBy(newScale)
   1379                 : new BigDecimal(integralValue, safeLongToInt(newScale)));
   1380     }
   1381 
   1382     /**
   1383      * Returns a new {@code BigDecimal} whose value is the integral part of
   1384      * {@code this / divisor}. The quotient is rounded down towards zero to the
   1385      * next integer. The rounding mode passed with the parameter {@code mc} is
   1386      * not considered. But if the precision of {@code mc > 0} and the integral
   1387      * part requires more digits, then an {@code ArithmeticException} is thrown.
   1388      *
   1389      * @param divisor
   1390      *            value by which {@code this} is divided.
   1391      * @param mc
   1392      *            math context which determines the maximal precision of the
   1393      *            result.
   1394      * @return integral part of {@code this / divisor}.
   1395      * @throws NullPointerException
   1396      *             if {@code divisor == null} or {@code mc == null}.
   1397      * @throws ArithmeticException
   1398      *             if {@code divisor == 0}.
   1399      * @throws ArithmeticException
   1400      *             if {@code mc.getPrecision() > 0} and the result requires more
   1401      *             digits to be represented.
   1402      */
   1403     public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
   1404         int mcPrecision = mc.getPrecision();
   1405         int diffPrecision = this.precision() - divisor.precision();
   1406         int lastPow = TEN_POW.length - 1;
   1407         long diffScale = (long)this.scale - divisor.scale;
   1408         long newScale = diffScale;
   1409         long quotPrecision = diffPrecision - diffScale + 1;
   1410         BigInteger quotAndRem[] = new BigInteger[2];
   1411         // In special cases it call the dual method
   1412         if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) {
   1413             return this.divideToIntegralValue(divisor);
   1414         }
   1415         // Let be:   this = [u1,s1]   and   divisor = [u2,s2]
   1416         if (quotPrecision <= 0) {
   1417             quotAndRem[0] = BigInteger.ZERO;
   1418         } else if (diffScale == 0) {
   1419             // CASE s1 == s2:  to calculate   u1 / u2
   1420             quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() );
   1421         } else if (diffScale > 0) {
   1422             // CASE s1 >= s2:  to calculate   u1 / (u2 * 10^(s1-s2)
   1423             quotAndRem[0] = this.getUnscaledValue().divide(
   1424                     divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) );
   1425             // To chose  10^newScale  to get a quotient with at least 'mc.precision()' digits
   1426             newScale = Math.min(diffScale, Math.max(mcPrecision - quotPrecision + 1, 0));
   1427             // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale
   1428             quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale));
   1429         } else {// CASE s2 > s1:
   1430             /* To calculate the minimum power of ten, such that the quotient
   1431              *   (u1 * 10^exp) / u2   has at least 'mc.precision()' digits. */
   1432             long exp = Math.min(-diffScale, Math.max((long)mcPrecision - diffPrecision, 0));
   1433             long compRemDiv;
   1434             // Let be:   (u1 * 10^exp) / u2 = [q,r]
   1435             quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)).
   1436                     divideAndRemainder(divisor.getUnscaledValue());
   1437             newScale += exp; // To fix the scale
   1438             exp = -newScale; // The remaining power of ten
   1439             // If after division there is a remainder...
   1440             if ((quotAndRem[1].signum() != 0) && (exp > 0)) {
   1441                 // Log10(r) + ((s2 - s1) - exp) > mc.precision ?
   1442                 compRemDiv = (new BigDecimal(quotAndRem[1])).precision()
   1443                 + exp - divisor.precision();
   1444                 if (compRemDiv == 0) {
   1445                     // To calculate:  (r * 10^exp2) / u2
   1446                     quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)).
   1447                             divide(divisor.getUnscaledValue());
   1448                     compRemDiv = Math.abs(quotAndRem[1].signum());
   1449                 }
   1450                 if (compRemDiv > 0) {
   1451                     throw new ArithmeticException("Division impossible");
   1452                 }
   1453             }
   1454         }
   1455         // Fast return if the quotient is zero
   1456         if (quotAndRem[0].signum() == 0) {
   1457             return zeroScaledBy(diffScale);
   1458         }
   1459         BigInteger strippedBI = quotAndRem[0];
   1460         BigDecimal integralValue = new BigDecimal(quotAndRem[0]);
   1461         long resultPrecision = integralValue.precision();
   1462         int i = 1;
   1463         // To strip trailing zeros until the specified precision is reached
   1464         while (!strippedBI.testBit(0)) {
   1465             quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
   1466             if ((quotAndRem[1].signum() == 0) &&
   1467                     ((resultPrecision - i >= mcPrecision)
   1468                     || (newScale - i >= diffScale)) ) {
   1469                 resultPrecision -= i;
   1470                 newScale -= i;
   1471                 if (i < lastPow) {
   1472                     i++;
   1473                 }
   1474                 strippedBI = quotAndRem[0];
   1475             } else {
   1476                 if (i == 1) {
   1477                     break;
   1478                 }
   1479                 i = 1;
   1480             }
   1481         }
   1482         // To check if the result fit in 'mc.precision()' digits
   1483         if (resultPrecision > mcPrecision) {
   1484             throw new ArithmeticException("Division impossible");
   1485         }
   1486         integralValue.scale = safeLongToInt(newScale);
   1487         integralValue.setUnscaledValue(strippedBI);
   1488         return integralValue;
   1489     }
   1490 
   1491     /**
   1492      * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
   1493      * <p>
   1494      * The remainder is defined as {@code this -
   1495      * this.divideToIntegralValue(divisor) * divisor}.
   1496      *
   1497      * @param divisor
   1498      *            value by which {@code this} is divided.
   1499      * @return {@code this % divisor}.
   1500      * @throws NullPointerException
   1501      *             if {@code divisor == null}.
   1502      * @throws ArithmeticException
   1503      *             if {@code divisor == 0}.
   1504      */
   1505     public BigDecimal remainder(BigDecimal divisor) {
   1506         return divideAndRemainder(divisor)[1];
   1507     }
   1508 
   1509     /**
   1510      * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
   1511      * <p>
   1512      * The remainder is defined as {@code this -
   1513      * this.divideToIntegralValue(divisor) * divisor}.
   1514      * <p>
   1515      * The specified rounding mode {@code mc} is used for the division only.
   1516      *
   1517      * @param divisor
   1518      *            value by which {@code this} is divided.
   1519      * @param mc
   1520      *            rounding mode and precision to be used.
   1521      * @return {@code this % divisor}.
   1522      * @throws NullPointerException
   1523      *             if {@code divisor == null}.
   1524      * @throws ArithmeticException
   1525      *             if {@code divisor == 0}.
   1526      * @throws ArithmeticException
   1527      *             if {@code mc.getPrecision() > 0} and the result of {@code
   1528      *             this.divideToIntegralValue(divisor, mc)} requires more digits
   1529      *             to be represented.
   1530      */
   1531     public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
   1532         return divideAndRemainder(divisor, mc)[1];
   1533     }
   1534 
   1535     /**
   1536      * Returns a {@code BigDecimal} array which contains the integral part of
   1537      * {@code this / divisor} at index 0 and the remainder {@code this %
   1538      * divisor} at index 1. The quotient is rounded down towards zero to the
   1539      * next integer.
   1540      *
   1541      * @param divisor
   1542      *            value by which {@code this} is divided.
   1543      * @return {@code [this.divideToIntegralValue(divisor),
   1544      *         this.remainder(divisor)]}.
   1545      * @throws NullPointerException
   1546      *             if {@code divisor == null}.
   1547      * @throws ArithmeticException
   1548      *             if {@code divisor == 0}.
   1549      * @see #divideToIntegralValue
   1550      * @see #remainder
   1551      */
   1552     public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
   1553         BigDecimal quotAndRem[] = new BigDecimal[2];
   1554 
   1555         quotAndRem[0] = this.divideToIntegralValue(divisor);
   1556         quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
   1557         return quotAndRem;
   1558     }
   1559 
   1560     /**
   1561      * Returns a {@code BigDecimal} array which contains the integral part of
   1562      * {@code this / divisor} at index 0 and the remainder {@code this %
   1563      * divisor} at index 1. The quotient is rounded down towards zero to the
   1564      * next integer. The rounding mode passed with the parameter {@code mc} is
   1565      * not considered. But if the precision of {@code mc > 0} and the integral
   1566      * part requires more digits, then an {@code ArithmeticException} is thrown.
   1567      *
   1568      * @param divisor
   1569      *            value by which {@code this} is divided.
   1570      * @param mc
   1571      *            math context which determines the maximal precision of the
   1572      *            result.
   1573      * @return {@code [this.divideToIntegralValue(divisor),
   1574      *         this.remainder(divisor)]}.
   1575      * @throws NullPointerException
   1576      *             if {@code divisor == null}.
   1577      * @throws ArithmeticException
   1578      *             if {@code divisor == 0}.
   1579      * @see #divideToIntegralValue
   1580      * @see #remainder
   1581      */
   1582     public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
   1583         BigDecimal quotAndRem[] = new BigDecimal[2];
   1584 
   1585         quotAndRem[0] = this.divideToIntegralValue(divisor, mc);
   1586         quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
   1587         return quotAndRem;
   1588     }
   1589 
   1590     /**
   1591      * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The
   1592      * scale of the result is {@code n * this.scale()}.
   1593      *
   1594      * <p>{@code x.pow(0)} returns {@code 1}, even if {@code x == 0}.
   1595      *
   1596      * <p>Implementation Note: The implementation is based on the ANSI standard
   1597      * X3.274-1996 algorithm.
   1598      *
   1599      * @throws ArithmeticException
   1600      *             if {@code n < 0} or {@code n > 999999999}.
   1601      */
   1602     public BigDecimal pow(int n) {
   1603         if (n == 0) {
   1604             return ONE;
   1605         }
   1606         if ((n < 0) || (n > 999999999)) {
   1607             throw new ArithmeticException("Invalid operation");
   1608         }
   1609         long newScale = scale * (long)n;
   1610         // Let be: this = [u,s]   so:  this^n = [u^n, s*n]
   1611         return isZero() ? zeroScaledBy(newScale)
   1612                 : new BigDecimal(getUnscaledValue().pow(n), safeLongToInt(newScale));
   1613     }
   1614 
   1615     /**
   1616      * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The
   1617      * result is rounded according to the passed context {@code mc}.
   1618      *
   1619      * <p>Implementation Note: The implementation is based on the ANSI standard
   1620      * X3.274-1996 algorithm.
   1621      *
   1622      * @param mc
   1623      *            rounding mode and precision for the result of this operation.
   1624      * @throws ArithmeticException
   1625      *             if {@code n < 0} or {@code n > 999999999}.
   1626      */
   1627     public BigDecimal pow(int n, MathContext mc) {
   1628         // The ANSI standard X3.274-1996 algorithm
   1629         int m = Math.abs(n);
   1630         int mcPrecision = mc.getPrecision();
   1631         int elength = (int)Math.log10(m) + 1;   // decimal digits in 'n'
   1632         int oneBitMask; // mask of bits
   1633         BigDecimal accum; // the single accumulator
   1634         MathContext newPrecision = mc; // MathContext by default
   1635 
   1636         // In particular cases, it reduces the problem to call the other 'pow()'
   1637         if ((n == 0) || ((isZero()) && (n > 0))) {
   1638             return pow(n);
   1639         }
   1640         if ((m > 999999999) || ((mcPrecision == 0) && (n < 0))
   1641                 || ((mcPrecision > 0) && (elength > mcPrecision))) {
   1642             throw new ArithmeticException("Invalid operation");
   1643         }
   1644         if (mcPrecision > 0) {
   1645             newPrecision = new MathContext( mcPrecision + elength + 1,
   1646                     mc.getRoundingMode());
   1647         }
   1648         // The result is calculated as if 'n' were positive
   1649         accum = round(newPrecision);
   1650         oneBitMask = Integer.highestOneBit(m) >> 1;
   1651 
   1652         while (oneBitMask > 0) {
   1653             accum = accum.multiply(accum, newPrecision);
   1654             if ((m & oneBitMask) == oneBitMask) {
   1655                 accum = accum.multiply(this, newPrecision);
   1656             }
   1657             oneBitMask >>= 1;
   1658         }
   1659         // If 'n' is negative, the value is divided into 'ONE'
   1660         if (n < 0) {
   1661             accum = ONE.divide(accum, newPrecision);
   1662         }
   1663         // The final value is rounded to the destination precision
   1664         accum.inplaceRound(mc);
   1665         return accum;
   1666     }
   1667 
   1668     /**
   1669      * Returns a new {@code BigDecimal} whose value is the absolute value of
   1670      * {@code this}. The scale of the result is the same as the scale of this.
   1671      *
   1672      * @return {@code abs(this)}
   1673      */
   1674     public BigDecimal abs() {
   1675         return ((signum() < 0) ? negate() : this);
   1676     }
   1677 
   1678     /**
   1679      * Returns a new {@code BigDecimal} whose value is the absolute value of
   1680      * {@code this}. The result is rounded according to the passed context
   1681      * {@code mc}.
   1682      *
   1683      * @param mc
   1684      *            rounding mode and precision for the result of this operation.
   1685      * @return {@code abs(this)}
   1686      */
   1687     public BigDecimal abs(MathContext mc) {
   1688         BigDecimal result = abs();
   1689         result.inplaceRound(mc);
   1690         return result;
   1691     }
   1692 
   1693     /**
   1694      * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
   1695      * scale of the result is the same as the scale of this.
   1696      *
   1697      * @return {@code -this}
   1698      */
   1699     public BigDecimal negate() {
   1700         if(bitLength < 63 || (bitLength == 63 && smallValue!=Long.MIN_VALUE)) {
   1701             return valueOf(-smallValue,scale);
   1702         }
   1703         return new BigDecimal(getUnscaledValue().negate(), scale);
   1704     }
   1705 
   1706     /**
   1707      * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
   1708      * result is rounded according to the passed context {@code mc}.
   1709      *
   1710      * @param mc
   1711      *            rounding mode and precision for the result of this operation.
   1712      * @return {@code -this}
   1713      */
   1714     public BigDecimal negate(MathContext mc) {
   1715         BigDecimal result = negate();
   1716         result.inplaceRound(mc);
   1717         return result;
   1718     }
   1719 
   1720     /**
   1721      * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale
   1722      * of the result is the same as the scale of this.
   1723      *
   1724      * @return {@code this}
   1725      */
   1726     public BigDecimal plus() {
   1727         return this;
   1728     }
   1729 
   1730     /**
   1731      * Returns a new {@code BigDecimal} whose value is {@code +this}. The result
   1732      * is rounded according to the passed context {@code mc}.
   1733      *
   1734      * @param mc
   1735      *            rounding mode and precision for the result of this operation.
   1736      * @return {@code this}, rounded
   1737      */
   1738     public BigDecimal plus(MathContext mc) {
   1739         return round(mc);
   1740     }
   1741 
   1742     /**
   1743      * Returns the sign of this {@code BigDecimal}.
   1744      *
   1745      * @return {@code -1} if {@code this < 0},
   1746      *         {@code 0} if {@code this == 0},
   1747      *         {@code 1} if {@code this > 0}.
   1748      */
   1749     public int signum() {
   1750         if( bitLength < 64) {
   1751             return Long.signum( this.smallValue );
   1752         }
   1753         return getUnscaledValue().signum();
   1754     }
   1755 
   1756     private boolean isZero() {
   1757         //Watch out: -1 has a bitLength=0
   1758         return bitLength == 0 && this.smallValue != -1;
   1759     }
   1760 
   1761     /**
   1762      * Returns the scale of this {@code BigDecimal}. The scale is the number of
   1763      * digits behind the decimal point. The value of this {@code BigDecimal} is
   1764      * the {@code unsignedValue * 10<sup>-scale</sup>}. If the scale is negative,
   1765      * then this {@code BigDecimal} represents a big integer.
   1766      *
   1767      * @return the scale of this {@code BigDecimal}.
   1768      */
   1769     public int scale() {
   1770         return scale;
   1771     }
   1772 
   1773     /**
   1774      * Returns the precision of this {@code BigDecimal}. The precision is the
   1775      * number of decimal digits used to represent this decimal. It is equivalent
   1776      * to the number of digits of the unscaled value. The precision of {@code 0}
   1777      * is {@code 1} (independent of the scale).
   1778      *
   1779      * @return the precision of this {@code BigDecimal}.
   1780      */
   1781     public int precision() {
   1782         // Return the cached value if we have one.
   1783         if (precision != 0) {
   1784             return precision;
   1785         }
   1786 
   1787         if (bitLength == 0) {
   1788             precision = 1;
   1789         } else if (bitLength < 64) {
   1790             precision = decimalDigitsInLong(smallValue);
   1791         } else {
   1792             int decimalDigits = 1 + (int) ((bitLength - 1) * LOG10_2);
   1793             // If after division the number isn't zero, there exists an additional digit
   1794             if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) {
   1795                 decimalDigits++;
   1796             }
   1797             precision = decimalDigits;
   1798         }
   1799         return precision;
   1800     }
   1801 
   1802     private int decimalDigitsInLong(long value) {
   1803         if (value == Long.MIN_VALUE) {
   1804             return 19; // special case required because abs(MIN_VALUE) == MIN_VALUE
   1805         } else {
   1806             int index = Arrays.binarySearch(MathUtils.LONG_POWERS_OF_TEN, Math.abs(value));
   1807             return (index < 0) ? (-index - 1) : (index + 1);
   1808         }
   1809     }
   1810 
   1811     /**
   1812      * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance
   1813      * as a {@code BigInteger}. The unscaled value can be computed as
   1814      * {@code this * 10<sup>scale</sup>}.
   1815      */
   1816     public BigInteger unscaledValue() {
   1817         return getUnscaledValue();
   1818     }
   1819 
   1820     /**
   1821      * Returns a new {@code BigDecimal} whose value is {@code this}, rounded
   1822      * according to the passed context {@code mc}.
   1823      * <p>
   1824      * If {@code mc.precision = 0}, then no rounding is performed.
   1825      * <p>
   1826      * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY},
   1827      * then an {@code ArithmeticException} is thrown if the result cannot be
   1828      * represented exactly within the given precision.
   1829      *
   1830      * @param mc
   1831      *            rounding mode and precision for the result of this operation.
   1832      * @return {@code this} rounded according to the passed context.
   1833      * @throws ArithmeticException
   1834      *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
   1835      *             UNNECESSARY} and this cannot be represented within the given
   1836      *             precision.
   1837      */
   1838     public BigDecimal round(MathContext mc) {
   1839         BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scale);
   1840 
   1841         thisBD.inplaceRound(mc);
   1842         return thisBD;
   1843     }
   1844 
   1845     /**
   1846      * Returns a new {@code BigDecimal} instance with the specified scale.
   1847      * <p>
   1848      * If the new scale is greater than the old scale, then additional zeros are
   1849      * added to the unscaled value. In this case no rounding is necessary.
   1850      * <p>
   1851      * If the new scale is smaller than the old scale, then trailing digits are
   1852      * removed. If these trailing digits are not zero, then the remaining
   1853      * unscaled value has to be rounded. For this rounding operation the
   1854      * specified rounding mode is used.
   1855      *
   1856      * @param newScale
   1857      *            scale of the result returned.
   1858      * @param roundingMode
   1859      *            rounding mode to be used to round the result.
   1860      * @return a new {@code BigDecimal} instance with the specified scale.
   1861      * @throws NullPointerException
   1862      *             if {@code roundingMode == null}.
   1863      * @throws ArithmeticException
   1864      *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
   1865      *             necessary according to the given scale.
   1866      */
   1867     public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
   1868         if (roundingMode == null) {
   1869             throw new NullPointerException("roundingMode == null");
   1870         }
   1871         long diffScale = newScale - (long)scale;
   1872         // Let be:  'this' = [u,s]
   1873         if(diffScale == 0) {
   1874             return this;
   1875         }
   1876         if(diffScale > 0) {
   1877         // return  [u * 10^(s2 - s), newScale]
   1878             if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
   1879                     (this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale]) < 64 ) {
   1880                 return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],newScale);
   1881             }
   1882             return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale);
   1883         }
   1884         // diffScale < 0
   1885         // return  [u,s] / [1,newScale]  with the appropriate scale and rounding
   1886         if(this.bitLength < 64 && -diffScale < MathUtils.LONG_POWERS_OF_TEN.length) {
   1887             return dividePrimitiveLongs(this.smallValue, MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], newScale,roundingMode);
   1888         }
   1889         return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode);
   1890     }
   1891 
   1892     /**
   1893      * Returns a new {@code BigDecimal} instance with the specified scale.
   1894      * <p>
   1895      * If the new scale is greater than the old scale, then additional zeros are
   1896      * added to the unscaled value. In this case no rounding is necessary.
   1897      * <p>
   1898      * If the new scale is smaller than the old scale, then trailing digits are
   1899      * removed. If these trailing digits are not zero, then the remaining
   1900      * unscaled value has to be rounded. For this rounding operation the
   1901      * specified rounding mode is used.
   1902      *
   1903      * @param newScale
   1904      *            scale of the result returned.
   1905      * @param roundingMode
   1906      *            rounding mode to be used to round the result.
   1907      * @return a new {@code BigDecimal} instance with the specified scale.
   1908      * @throws IllegalArgumentException
   1909      *             if {@code roundingMode} is not a valid rounding mode.
   1910      * @throws ArithmeticException
   1911      *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
   1912      *             necessary according to the given scale.
   1913      */
   1914     public BigDecimal setScale(int newScale, int roundingMode) {
   1915         return setScale(newScale, RoundingMode.valueOf(roundingMode));
   1916     }
   1917 
   1918     /**
   1919      * Returns a new {@code BigDecimal} instance with the specified scale. If
   1920      * the new scale is greater than the old scale, then additional zeros are
   1921      * added to the unscaled value. If the new scale is smaller than the old
   1922      * scale, then trailing zeros are removed. If the trailing digits are not
   1923      * zeros then an ArithmeticException is thrown.
   1924      * <p>
   1925      * If no exception is thrown, then the following equation holds: {@code
   1926      * x.setScale(s).compareTo(x) == 0}.
   1927      *
   1928      * @param newScale
   1929      *            scale of the result returned.
   1930      * @return a new {@code BigDecimal} instance with the specified scale.
   1931      * @throws ArithmeticException
   1932      *             if rounding would be necessary.
   1933      */
   1934     public BigDecimal setScale(int newScale) {
   1935         return setScale(newScale, RoundingMode.UNNECESSARY);
   1936     }
   1937 
   1938     /**
   1939      * Returns a new {@code BigDecimal} instance where the decimal point has
   1940      * been moved {@code n} places to the left. If {@code n < 0} then the
   1941      * decimal point is moved {@code -n} places to the right.
   1942      *
   1943      * <p>The result is obtained by changing its scale. If the scale of the result
   1944      * becomes negative, then its precision is increased such that the scale is
   1945      * zero.
   1946      *
   1947      * <p>Note, that {@code movePointLeft(0)} returns a result which is
   1948      * mathematically equivalent, but which has {@code scale >= 0}.
   1949      */
   1950     public BigDecimal movePointLeft(int n) {
   1951         return movePoint(scale + (long)n);
   1952     }
   1953 
   1954     private BigDecimal movePoint(long newScale) {
   1955         if (isZero()) {
   1956             return zeroScaledBy(Math.max(newScale, 0));
   1957         }
   1958         /*
   1959          * When: 'n'== Integer.MIN_VALUE isn't possible to call to
   1960          * movePointRight(-n) since -Integer.MIN_VALUE == Integer.MIN_VALUE
   1961          */
   1962         if(newScale >= 0) {
   1963             if(bitLength < 64) {
   1964                 return valueOf(smallValue, safeLongToInt(newScale));
   1965             }
   1966             return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
   1967         }
   1968         if(-newScale < MathUtils.LONG_POWERS_OF_TEN.length &&
   1969                 bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-newScale] < 64 ) {
   1970             return valueOf(smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-newScale],0);
   1971         }
   1972         return new BigDecimal(Multiplication.multiplyByTenPow(
   1973                 getUnscaledValue(), safeLongToInt(-newScale)), 0);
   1974     }
   1975 
   1976     /**
   1977      * Returns a new {@code BigDecimal} instance where the decimal point has
   1978      * been moved {@code n} places to the right. If {@code n < 0} then the
   1979      * decimal point is moved {@code -n} places to the left.
   1980      *
   1981      * <p>The result is obtained by changing its scale. If the scale of the result
   1982      * becomes negative, then its precision is increased such that the scale is
   1983      * zero.
   1984      *
   1985      * <p>Note, that {@code movePointRight(0)} returns a result which is
   1986      * mathematically equivalent, but which has scale >= 0.
   1987      */
   1988     public BigDecimal movePointRight(int n) {
   1989         return movePoint(scale - (long)n);
   1990     }
   1991 
   1992     /**
   1993      * Returns a new {@code BigDecimal} whose value is {@code this * 10<sup>n</sup>}.
   1994      * The scale of the result is {@code this.scale()} - {@code n}.
   1995      * The precision of the result is the precision of {@code this}.
   1996      *
   1997      * <p>This method has the same effect as {@link #movePointRight}, except that
   1998      * the precision is not changed.
   1999      */
   2000     public BigDecimal scaleByPowerOfTen(int n) {
   2001         long newScale = scale - (long)n;
   2002         if(bitLength < 64) {
   2003             //Taking care when a 0 is to be scaled
   2004             if( smallValue==0  ){
   2005                 return zeroScaledBy( newScale );
   2006             }
   2007             return valueOf(smallValue, safeLongToInt(newScale));
   2008         }
   2009         return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
   2010     }
   2011 
   2012     /**
   2013      * Returns a new {@code BigDecimal} instance with the same value as {@code
   2014      * this} but with a unscaled value where the trailing zeros have been
   2015      * removed. If the unscaled value of {@code this} has n trailing zeros, then
   2016      * the scale and the precision of the result has been reduced by n.
   2017      *
   2018      * @return a new {@code BigDecimal} instance equivalent to this where the
   2019      *         trailing zeros of the unscaled value have been removed.
   2020      */
   2021     public BigDecimal stripTrailingZeros() {
   2022         int i = 1; // 1 <= i <= 18
   2023         int lastPow = TEN_POW.length - 1;
   2024         long newScale = scale;
   2025 
   2026         if (isZero()) {
   2027             // Preserve RI compatibility, so BigDecimal.equals (which checks
   2028             // value *and* scale) continues to work.
   2029             return this;
   2030         }
   2031         BigInteger strippedBI = getUnscaledValue();
   2032         BigInteger[] quotAndRem;
   2033 
   2034         // while the number is even...
   2035         while (!strippedBI.testBit(0)) {
   2036             // To divide by 10^i
   2037             quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
   2038             // To look the remainder
   2039             if (quotAndRem[1].signum() == 0) {
   2040                 // To adjust the scale
   2041                 newScale -= i;
   2042                 if (i < lastPow) {
   2043                     // To set to the next power
   2044                     i++;
   2045                 }
   2046                 strippedBI = quotAndRem[0];
   2047             } else {
   2048                 if (i == 1) {
   2049                     // 'this' has no more trailing zeros
   2050                     break;
   2051                 }
   2052                 // To set to the smallest power of ten
   2053                 i = 1;
   2054             }
   2055         }
   2056         return new BigDecimal(strippedBI, safeLongToInt(newScale));
   2057     }
   2058 
   2059     /**
   2060      * Compares this {@code BigDecimal} with {@code val}. Returns one of the
   2061      * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as
   2062      * if {@code this.subtract(val)} is computed. If this difference is > 0 then
   2063      * 1 is returned, if the difference is < 0 then -1 is returned, and if the
   2064      * difference is 0 then 0 is returned. This means, that if two decimal
   2065      * instances are compared which are equal in value but differ in scale, then
   2066      * these two instances are considered as equal.
   2067      *
   2068      * @param val
   2069      *            value to be compared with {@code this}.
   2070      * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val},
   2071      *         {@code 0} if {@code this == val}.
   2072      * @throws NullPointerException
   2073      *             if {@code val == null}.
   2074      */
   2075     public int compareTo(BigDecimal val) {
   2076         int thisSign = signum();
   2077         int valueSign = val.signum();
   2078 
   2079         if( thisSign == valueSign) {
   2080             if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) {
   2081                 return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0;
   2082             }
   2083             long diffScale = (long)this.scale - val.scale;
   2084             int diffPrecision = this.approxPrecision() - val.approxPrecision();
   2085             if (diffPrecision > diffScale + 1) {
   2086                 return thisSign;
   2087             } else if (diffPrecision < diffScale - 1) {
   2088                 return -thisSign;
   2089             } else {// thisSign == val.signum()  and  diffPrecision is aprox. diffScale
   2090                 BigInteger thisUnscaled = this.getUnscaledValue();
   2091                 BigInteger valUnscaled = val.getUnscaledValue();
   2092                 // If any of both precision is bigger, append zeros to the shorter one
   2093                 if (diffScale < 0) {
   2094                     thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale));
   2095                 } else if (diffScale > 0) {
   2096                     valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale));
   2097                 }
   2098                 return thisUnscaled.compareTo(valUnscaled);
   2099             }
   2100         } else if (thisSign < valueSign) {
   2101             return -1;
   2102         } else  {
   2103             return 1;
   2104         }
   2105     }
   2106 
   2107     /**
   2108      * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if
   2109      * this instance is equal to this big decimal. Two big decimals are equal if
   2110      * their unscaled value and their scale is equal. For example, 1.0
   2111      * (10*10<sup>-1</sup>) is not equal to 1.00 (100*10<sup>-2</sup>). Similarly, zero
   2112      * instances are not equal if their scale differs.
   2113      */
   2114     @Override
   2115     public boolean equals(Object x) {
   2116         if (this == x) {
   2117             return true;
   2118         }
   2119         if (x instanceof BigDecimal) {
   2120             BigDecimal x1 = (BigDecimal) x;
   2121             return x1.scale == scale
   2122                    && (bitLength < 64 ? (x1.smallValue == smallValue)
   2123                     : intVal.equals(x1.intVal));
   2124         }
   2125         return false;
   2126     }
   2127 
   2128     /**
   2129      * Returns the minimum of this {@code BigDecimal} and {@code val}.
   2130      *
   2131      * @param val
   2132      *            value to be used to compute the minimum with this.
   2133      * @return {@code min(this, val}.
   2134      * @throws NullPointerException
   2135      *             if {@code val == null}.
   2136      */
   2137     public BigDecimal min(BigDecimal val) {
   2138         return ((compareTo(val) <= 0) ? this : val);
   2139     }
   2140 
   2141     /**
   2142      * Returns the maximum of this {@code BigDecimal} and {@code val}.
   2143      *
   2144      * @param val
   2145      *            value to be used to compute the maximum with this.
   2146      * @return {@code max(this, val}.
   2147      * @throws NullPointerException
   2148      *             if {@code val == null}.
   2149      */
   2150     public BigDecimal max(BigDecimal val) {
   2151         return ((compareTo(val) >= 0) ? this : val);
   2152     }
   2153 
   2154     /**
   2155      * Returns a hash code for this {@code BigDecimal}.
   2156      *
   2157      * @return hash code for {@code this}.
   2158      */
   2159     @Override
   2160     public int hashCode() {
   2161         if (hashCode != 0) {
   2162             return hashCode;
   2163         }
   2164         if (bitLength < 64) {
   2165             hashCode = (int)(smallValue & 0xffffffff);
   2166             hashCode = 33 * hashCode +  (int)((smallValue >> 32) & 0xffffffff);
   2167             hashCode = 17 * hashCode + scale;
   2168             return hashCode;
   2169         }
   2170         hashCode = 17 * intVal.hashCode() + scale;
   2171         return hashCode;
   2172     }
   2173 
   2174     /**
   2175      * Returns a canonical string representation of this {@code BigDecimal}. If
   2176      * necessary, scientific notation is used. This representation always prints
   2177      * all significant digits of this value.
   2178      * <p>
   2179      * If the scale is negative or if {@code scale - precision >= 6} then
   2180      * scientific notation is used.
   2181      *
   2182      * @return a string representation of {@code this} in scientific notation if
   2183      *         necessary.
   2184      */
   2185     @Override
   2186     public String toString() {
   2187         if (toStringImage != null) {
   2188             return toStringImage;
   2189         }
   2190         if(bitLength < 32) {
   2191             toStringImage = Conversion.toDecimalScaledString(smallValue,scale);
   2192             return toStringImage;
   2193         }
   2194         String intString = getUnscaledValue().toString();
   2195         if (scale == 0) {
   2196             return intString;
   2197         }
   2198         int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
   2199         int end = intString.length();
   2200         long exponent = -(long)scale + end - begin;
   2201         StringBuilder result = new StringBuilder();
   2202 
   2203         result.append(intString);
   2204         if ((scale > 0) && (exponent >= -6)) {
   2205             if (exponent >= 0) {
   2206                 result.insert(end - scale, '.');
   2207             } else {
   2208                 result.insert(begin - 1, "0.");
   2209                 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
   2210             }
   2211         } else {
   2212             if (end - begin >= 1) {
   2213                 result.insert(begin, '.');
   2214                 end++;
   2215             }
   2216             result.insert(end, 'E');
   2217             if (exponent > 0) {
   2218                 result.insert(++end, '+');
   2219             }
   2220             result.insert(++end, Long.toString(exponent));
   2221         }
   2222         toStringImage = result.toString();
   2223         return toStringImage;
   2224     }
   2225 
   2226     /**
   2227      * Returns a string representation of this {@code BigDecimal}. This
   2228      * representation always prints all significant digits of this value.
   2229      * <p>
   2230      * If the scale is negative or if {@code scale - precision >= 6} then
   2231      * engineering notation is used. Engineering notation is similar to the
   2232      * scientific notation except that the exponent is made to be a multiple of
   2233      * 3 such that the integer part is >= 1 and < 1000.
   2234      *
   2235      * @return a string representation of {@code this} in engineering notation
   2236      *         if necessary.
   2237      */
   2238     public String toEngineeringString() {
   2239         String intString = getUnscaledValue().toString();
   2240         if (scale == 0) {
   2241             return intString;
   2242         }
   2243         int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
   2244         int end = intString.length();
   2245         long exponent = -(long)scale + end - begin;
   2246         StringBuilder result = new StringBuilder(intString);
   2247 
   2248         if ((scale > 0) && (exponent >= -6)) {
   2249             if (exponent >= 0) {
   2250                 result.insert(end - scale, '.');
   2251             } else {
   2252                 result.insert(begin - 1, "0.");
   2253                 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
   2254             }
   2255         } else {
   2256             int delta = end - begin;
   2257             int rem = (int)(exponent % 3);
   2258 
   2259             if (rem != 0) {
   2260                 // adjust exponent so it is a multiple of three
   2261                 if (getUnscaledValue().signum() == 0) {
   2262                     // zero value
   2263                     rem = (rem < 0) ? -rem : 3 - rem;
   2264                     exponent += rem;
   2265                 } else {
   2266                     // nonzero value
   2267                     rem = (rem < 0) ? rem + 3 : rem;
   2268                     exponent -= rem;
   2269                     begin += rem;
   2270                 }
   2271                 if (delta < 3) {
   2272                     for (int i = rem - delta; i > 0; i--) {
   2273                         result.insert(end++, '0');
   2274                     }
   2275                 }
   2276             }
   2277             if (end - begin >= 1) {
   2278                 result.insert(begin, '.');
   2279                 end++;
   2280             }
   2281             if (exponent != 0) {
   2282                 result.insert(end, 'E');
   2283                 if (exponent > 0) {
   2284                     result.insert(++end, '+');
   2285                 }
   2286                 result.insert(++end, Long.toString(exponent));
   2287             }
   2288         }
   2289         return result.toString();
   2290     }
   2291 
   2292     /**
   2293      * Returns a string representation of this {@code BigDecimal}. No scientific
   2294      * notation is used. This methods adds zeros where necessary.
   2295      * <p>
   2296      * If this string representation is used to create a new instance, this
   2297      * instance is generally not identical to {@code this} as the precision
   2298      * changes.
   2299      * <p>
   2300      * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns
   2301      * {@code false}.
   2302      * <p>
   2303      * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}.
   2304      *
   2305      * @return a string representation of {@code this} without exponent part.
   2306      */
   2307     public String toPlainString() {
   2308         String intStr = getUnscaledValue().toString();
   2309         if ((scale == 0) || ((isZero()) && (scale < 0))) {
   2310             return intStr;
   2311         }
   2312         int begin = (signum() < 0) ? 1 : 0;
   2313         int delta = scale;
   2314         // We take space for all digits, plus a possible decimal point, plus 'scale'
   2315         StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale));
   2316 
   2317         if (begin == 1) {
   2318             // If the number is negative, we insert a '-' character at front
   2319             result.append('-');
   2320         }
   2321         if (scale > 0) {
   2322             delta -= (intStr.length() - begin);
   2323             if (delta >= 0) {
   2324                 result.append("0.");
   2325                 // To append zeros after the decimal point
   2326                 for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) {
   2327                     result.append(CH_ZEROS);
   2328                 }
   2329                 result.append(CH_ZEROS, 0, delta);
   2330                 result.append(intStr.substring(begin));
   2331             } else {
   2332                 delta = begin - delta;
   2333                 result.append(intStr.substring(begin, delta));
   2334                 result.append('.');
   2335                 result.append(intStr.substring(delta));
   2336             }
   2337         } else {// (scale <= 0)
   2338             result.append(intStr.substring(begin));
   2339             // To append trailing zeros
   2340             for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) {
   2341                 result.append(CH_ZEROS);
   2342             }
   2343             result.append(CH_ZEROS, 0, -delta);
   2344         }
   2345         return result.toString();
   2346     }
   2347 
   2348     /**
   2349      * Returns this {@code BigDecimal} as a big integer instance. A fractional
   2350      * part is discarded.
   2351      *
   2352      * @return this {@code BigDecimal} as a big integer instance.
   2353      */
   2354     public BigInteger toBigInteger() {
   2355         if ((scale == 0) || (isZero())) {
   2356             return getUnscaledValue();
   2357         } else if (scale < 0) {
   2358             return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
   2359         } else {// (scale > 0)
   2360             return getUnscaledValue().divide(Multiplication.powerOf10(scale));
   2361         }
   2362     }
   2363 
   2364     /**
   2365      * Returns this {@code BigDecimal} as a big integer instance if it has no
   2366      * fractional part. If this {@code BigDecimal} has a fractional part, i.e.
   2367      * if rounding would be necessary, an {@code ArithmeticException} is thrown.
   2368      *
   2369      * @return this {@code BigDecimal} as a big integer value.
   2370      * @throws ArithmeticException
   2371      *             if rounding is necessary.
   2372      */
   2373     public BigInteger toBigIntegerExact() {
   2374         if ((scale == 0) || (isZero())) {
   2375             return getUnscaledValue();
   2376         } else if (scale < 0) {
   2377             return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
   2378         } else {// (scale > 0)
   2379             BigInteger[] integerAndFraction;
   2380             // An optimization before do a heavy division
   2381             if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) {
   2382                 throw new ArithmeticException("Rounding necessary");
   2383             }
   2384             integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale));
   2385             if (integerAndFraction[1].signum() != 0) {
   2386                 // It exists a non-zero fractional part
   2387                 throw new ArithmeticException("Rounding necessary");
   2388             }
   2389             return integerAndFraction[0];
   2390         }
   2391     }
   2392 
   2393     /**
   2394      * Returns this {@code BigDecimal} as an long value. Any fractional part is
   2395      * discarded. If the integral part of {@code this} is too big to be
   2396      * represented as an long, then {@code this % 2<sup>64</sup>} is returned.
   2397      */
   2398     @Override
   2399     public long longValue() {
   2400         /*
   2401          * If scale <= -64 there are at least 64 trailing bits zero in
   2402          * 10^(-scale). If the scale is positive and very large the long value
   2403          * could be zero.
   2404          */
   2405         return ((scale <= -64) || (scale > approxPrecision()) ? 0L : toBigInteger().longValue());
   2406     }
   2407 
   2408     /**
   2409      * Returns this {@code BigDecimal} as a long value if it has no fractional
   2410      * part and if its value fits to the int range ([-2<sup>63</sup>..2<sup>63</sup>-1]). If
   2411      * these conditions are not met, an {@code ArithmeticException} is thrown.
   2412      *
   2413      * @throws ArithmeticException
   2414      *             if rounding is necessary or the number doesn't fit in a long.
   2415      */
   2416     public long longValueExact() {
   2417         return valueExact(64);
   2418     }
   2419 
   2420     /**
   2421      * Returns this {@code BigDecimal} as an int value. Any fractional part is
   2422      * discarded. If the integral part of {@code this} is too big to be
   2423      * represented as an int, then {@code this % 2<sup>32</sup>} is returned.
   2424      */
   2425     @Override
   2426     public int intValue() {
   2427         /*
   2428          * If scale <= -32 there are at least 32 trailing bits zero in
   2429          * 10^(-scale). If the scale is positive and very large the long value
   2430          * could be zero.
   2431          */
   2432         return ((scale <= -32) || (scale > approxPrecision()) ? 0 : toBigInteger().intValue());
   2433     }
   2434 
   2435     /**
   2436      * Returns this {@code BigDecimal} as a int value if it has no fractional
   2437      * part and if its value fits to the int range ([-2<sup>31</sup>..2<sup>31</sup>-1]). If
   2438      * these conditions are not met, an {@code ArithmeticException} is thrown.
   2439      *
   2440      * @throws ArithmeticException
   2441      *             if rounding is necessary or the number doesn't fit in an int.
   2442      */
   2443     public int intValueExact() {
   2444         return (int) valueExact(32);
   2445     }
   2446 
   2447     /**
   2448      * Returns this {@code BigDecimal} as a short value if it has no fractional
   2449      * part and if its value fits to the short range ([-2<sup>15</sup>..2<sup>15</sup>-1]). If
   2450      * these conditions are not met, an {@code ArithmeticException} is thrown.
   2451      *
   2452      * @throws ArithmeticException
   2453      *             if rounding is necessary of the number doesn't fit in a short.
   2454      */
   2455     public short shortValueExact() {
   2456         return (short) valueExact(16);
   2457     }
   2458 
   2459     /**
   2460      * Returns this {@code BigDecimal} as a byte value if it has no fractional
   2461      * part and if its value fits to the byte range ([-128..127]). If these
   2462      * conditions are not met, an {@code ArithmeticException} is thrown.
   2463      *
   2464      * @throws ArithmeticException
   2465      *             if rounding is necessary or the number doesn't fit in a byte.
   2466      */
   2467     public byte byteValueExact() {
   2468         return (byte) valueExact(8);
   2469     }
   2470 
   2471     /**
   2472      * Returns this {@code BigDecimal} as a float value. If {@code this} is too
   2473      * big to be represented as an float, then {@code Float.POSITIVE_INFINITY}
   2474      * or {@code Float.NEGATIVE_INFINITY} is returned.
   2475      * <p>
   2476      * Note, that if the unscaled value has more than 24 significant digits,
   2477      * then this decimal cannot be represented exactly in a float variable. In
   2478      * this case the result is rounded.
   2479      * <p>
   2480      * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
   2481      * represented exactly as a float, and thus {@code x1.equals(new
   2482      * BigDecimal(x1.floatValue())} returns {@code false} for this case.
   2483      * <p>
   2484      * Similarly, if the instance {@code new BigDecimal(16777217)} is converted
   2485      * to a float, the result is {@code 1.6777216E}7.
   2486      *
   2487      * @return this {@code BigDecimal} as a float value.
   2488      */
   2489     @Override
   2490     public float floatValue() {
   2491         /* A similar code like in doubleValue() could be repeated here,
   2492          * but this simple implementation is quite efficient. */
   2493         float floatResult = signum();
   2494         long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
   2495         if ((powerOfTwo < -149) || (floatResult == 0.0f)) {
   2496             // Cases which 'this' is very small
   2497             floatResult *= 0.0f;
   2498         } else if (powerOfTwo > 129) {
   2499             // Cases which 'this' is very large
   2500             floatResult *= Float.POSITIVE_INFINITY;
   2501         } else {
   2502             floatResult = (float)doubleValue();
   2503         }
   2504         return floatResult;
   2505     }
   2506 
   2507     /**
   2508      * Returns this {@code BigDecimal} as a double value. If {@code this} is too
   2509      * big to be represented as an float, then {@code Double.POSITIVE_INFINITY}
   2510      * or {@code Double.NEGATIVE_INFINITY} is returned.
   2511      * <p>
   2512      * Note, that if the unscaled value has more than 53 significant digits,
   2513      * then this decimal cannot be represented exactly in a double variable. In
   2514      * this case the result is rounded.
   2515      * <p>
   2516      * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
   2517      * represented exactly as a double, and thus {@code x1.equals(new
   2518      * BigDecimal(x1.doubleValue())} returns {@code false} for this case.
   2519      * <p>
   2520      * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is
   2521      * converted to a double, the result is {@code 9.007199254740992E15}.
   2522      * <p>
   2523      *
   2524      * @return this {@code BigDecimal} as a double value.
   2525      */
   2526     @Override
   2527     public double doubleValue() {
   2528         int sign = signum();
   2529         int exponent = 1076; // bias + 53
   2530         int lowestSetBit;
   2531         int discardedSize;
   2532         long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
   2533         long bits; // IEEE-754 Standard
   2534         long tempBits; // for temporal calculations
   2535         BigInteger mantissa;
   2536 
   2537         if ((powerOfTwo < -1074) || (sign == 0)) {
   2538             // Cases which 'this' is very small
   2539             return (sign * 0.0d);
   2540         } else if (powerOfTwo > 1025) {
   2541             // Cases which 'this' is very large
   2542             return (sign * Double.POSITIVE_INFINITY);
   2543         }
   2544         mantissa = getUnscaledValue().abs();
   2545         // Let be:  this = [u,s], with s > 0
   2546         if (scale <= 0) {
   2547             // mantissa = abs(u) * 10^s
   2548             mantissa = mantissa.multiply(Multiplication.powerOf10(-scale));
   2549         } else {// (scale > 0)
   2550             BigInteger quotAndRem[];
   2551             BigInteger powerOfTen = Multiplication.powerOf10(scale);
   2552             int k = 100 - (int)powerOfTwo;
   2553             int compRem;
   2554 
   2555             if (k > 0) {
   2556                 /* Computing (mantissa * 2^k) , where 'k' is a enough big
   2557                  * power of '2' to can divide by 10^s */
   2558                 mantissa = mantissa.shiftLeft(k);
   2559                 exponent -= k;
   2560             }
   2561             // Computing (mantissa * 2^k) / 10^s
   2562             quotAndRem = mantissa.divideAndRemainder(powerOfTen);
   2563             // To check if the fractional part >= 0.5
   2564             compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen);
   2565             // To add two rounded bits at end of mantissa
   2566             mantissa = quotAndRem[0].shiftLeft(2).add(
   2567                     BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1));
   2568             exponent -= 2;
   2569         }
   2570         lowestSetBit = mantissa.getLowestSetBit();
   2571         discardedSize = mantissa.bitLength() - 54;
   2572         if (discardedSize > 0) {// (n > 54)
   2573             // mantissa = (abs(u) * 10^s) >> (n - 54)
   2574             bits = mantissa.shiftRight(discardedSize).longValue();
   2575             tempBits = bits;
   2576             // #bits = 54, to check if the discarded fraction produces a carry
   2577             if ((((bits & 1) == 1) && (lowestSetBit < discardedSize))
   2578                     || ((bits & 3) == 3)) {
   2579                 bits += 2;
   2580             }
   2581         } else {// (n <= 54)
   2582             // mantissa = (abs(u) * 10^s) << (54 - n)
   2583             bits = mantissa.longValue() << -discardedSize;
   2584             tempBits = bits;
   2585             // #bits = 54, to check if the discarded fraction produces a carry:
   2586             if ((bits & 3) == 3) {
   2587                 bits += 2;
   2588             }
   2589         }
   2590         // Testing bit 54 to check if the carry creates a new binary digit
   2591         if ((bits & 0x40000000000000L) == 0) {
   2592             // To drop the last bit of mantissa (first discarded)
   2593             bits >>= 1;
   2594             // exponent = 2^(s-n+53+bias)
   2595             exponent += discardedSize;
   2596         } else {// #bits = 54
   2597             bits >>= 2;
   2598             exponent += discardedSize + 1;
   2599         }
   2600         // To test if the 53-bits number fits in 'double'
   2601         if (exponent > 2046) {// (exponent - bias > 1023)
   2602             return (sign * Double.POSITIVE_INFINITY);
   2603         } else if (exponent <= 0) {// (exponent - bias <= -1023)
   2604             // Denormalized numbers (having exponent == 0)
   2605             if (exponent < -53) {// exponent - bias < -1076
   2606                 return (sign * 0.0d);
   2607             }
   2608             // -1076 <= exponent - bias <= -1023
   2609             // To discard '- exponent + 1' bits
   2610             bits = tempBits >> 1;
   2611             tempBits = bits & (-1L >>> (63 + exponent));
   2612             bits >>= (-exponent );
   2613             // To test if after discard bits, a new carry is generated
   2614             if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0)
   2615             && (lowestSetBit < discardedSize))) {
   2616                 bits += 1;
   2617             }
   2618             exponent = 0;
   2619             bits >>= 1;
   2620         }
   2621         // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)]
   2622         bits = (sign & 0x8000000000000000L) | ((long)exponent << 52)
   2623                 | (bits & 0xFFFFFFFFFFFFFL);
   2624         return Double.longBitsToDouble(bits);
   2625     }
   2626 
   2627     /**
   2628      * Returns the unit in the last place (ULP) of this {@code BigDecimal}
   2629      * instance. An ULP is the distance to the nearest big decimal with the same
   2630      * precision.
   2631      *
   2632      * <p>The amount of a rounding error in the evaluation of a floating-point
   2633      * operation is often expressed in ULPs. An error of 1 ULP is often seen as
   2634      * a tolerable error.
   2635      *
   2636      * <p>For class {@code BigDecimal}, the ULP of a number is simply 10<sup>-scale</sup>.
   2637      * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}.
   2638      *
   2639      * @return unit in the last place (ULP) of this {@code BigDecimal} instance.
   2640      */
   2641     public BigDecimal ulp() {
   2642         return valueOf(1, scale);
   2643     }
   2644 
   2645     /* Private Methods */
   2646 
   2647     /**
   2648      * It does all rounding work of the public method
   2649      * {@code round(MathContext)}, performing an inplace rounding
   2650      * without creating a new object.
   2651      *
   2652      * @param mc
   2653      *            the {@code MathContext} for perform the rounding.
   2654      * @see #round(MathContext)
   2655      */
   2656     private void inplaceRound(MathContext mc) {
   2657         int mcPrecision = mc.getPrecision();
   2658         if (approxPrecision() < mcPrecision || mcPrecision == 0) {
   2659             return;
   2660         }
   2661         int discardedPrecision = precision() - mcPrecision;
   2662         // If no rounding is necessary it returns immediately
   2663         if ((discardedPrecision <= 0)) {
   2664             return;
   2665         }
   2666         // When the number is small perform an efficient rounding
   2667         if (this.bitLength < 64) {
   2668             smallRound(mc, discardedPrecision);
   2669             return;
   2670         }
   2671         // Getting the integer part and the discarded fraction
   2672         BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision);
   2673         BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction);
   2674         long newScale = (long)scale - discardedPrecision;
   2675         int compRem;
   2676         BigDecimal tempBD;
   2677         // If the discarded fraction is non-zero, perform rounding
   2678         if (integerAndFraction[1].signum() != 0) {
   2679             // To check if the discarded fraction >= 0.5
   2680             compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction));
   2681             // To look if there is a carry
   2682             compRem =  roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0,
   2683                     integerAndFraction[1].signum() * (5 + compRem),
   2684                     mc.getRoundingMode());
   2685             if (compRem != 0) {
   2686                 integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem));
   2687             }
   2688             tempBD = new BigDecimal(integerAndFraction[0]);
   2689             // If after to add the increment the precision changed, we normalize the size
   2690             if (tempBD.precision() > mcPrecision) {
   2691                 integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN);
   2692                 newScale--;
   2693             }
   2694         }
   2695         // To update all internal fields
   2696         scale = safeLongToInt(newScale);
   2697         precision = mcPrecision;
   2698         setUnscaledValue(integerAndFraction[0]);
   2699     }
   2700 
   2701     private static int longCompareTo(long value1, long value2) {
   2702         return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0);
   2703     }
   2704     /**
   2705      * This method implements an efficient rounding for numbers which unscaled
   2706      * value fits in the type {@code long}.
   2707      *
   2708      * @param mc
   2709      *            the context to use
   2710      * @param discardedPrecision
   2711      *            the number of decimal digits that are discarded
   2712      * @see #round(MathContext)
   2713      */
   2714     private void smallRound(MathContext mc, int discardedPrecision) {
   2715         long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision];
   2716         long newScale = (long)scale - discardedPrecision;
   2717         long unscaledVal = smallValue;
   2718         // Getting the integer part and the discarded fraction
   2719         long integer = unscaledVal / sizeOfFraction;
   2720         long fraction = unscaledVal % sizeOfFraction;
   2721         int compRem;
   2722         // If the discarded fraction is non-zero perform rounding
   2723         if (fraction != 0) {
   2724             // To check if the discarded fraction >= 0.5
   2725             compRem = longCompareTo(Math.abs(fraction) * 2, sizeOfFraction);
   2726             // To look if there is a carry
   2727             integer += roundingBehavior( ((int)integer) & 1,
   2728                     Long.signum(fraction) * (5 + compRem),
   2729                     mc.getRoundingMode());
   2730             // If after to add the increment the precision changed, we normalize the size
   2731             if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) {
   2732                 integer /= 10;
   2733                 newScale--;
   2734             }
   2735         }
   2736         // To update all internal fields
   2737         scale = safeLongToInt(newScale);
   2738         precision = mc.getPrecision();
   2739         smallValue = integer;
   2740         bitLength = bitLength(integer);
   2741         intVal = null;
   2742     }
   2743 
   2744     /**
   2745      * Return an increment that can be -1,0 or 1, depending of
   2746      * {@code roundingMode}.
   2747      *
   2748      * @param parityBit
   2749      *            can be 0 or 1, it's only used in the case
   2750      *            {@code HALF_EVEN}
   2751      * @param fraction
   2752      *            the mantissa to be analyzed
   2753      * @param roundingMode
   2754      *            the type of rounding
   2755      * @return the carry propagated after rounding
   2756      */
   2757     private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) {
   2758         int increment = 0; // the carry after rounding
   2759 
   2760         switch (roundingMode) {
   2761             case UNNECESSARY:
   2762                 if (fraction != 0) {
   2763                     throw new ArithmeticException("Rounding necessary");
   2764                 }
   2765                 break;
   2766             case UP:
   2767                 increment = Integer.signum(fraction);
   2768                 break;
   2769             case DOWN:
   2770                 break;
   2771             case CEILING:
   2772                 increment = Math.max(Integer.signum(fraction), 0);
   2773                 break;
   2774             case FLOOR:
   2775                 increment = Math.min(Integer.signum(fraction), 0);
   2776                 break;
   2777             case HALF_UP:
   2778                 if (Math.abs(fraction) >= 5) {
   2779                     increment = Integer.signum(fraction);
   2780                 }
   2781                 break;
   2782             case HALF_DOWN:
   2783                 if (Math.abs(fraction) > 5) {
   2784                     increment = Integer.signum(fraction);
   2785                 }
   2786                 break;
   2787             case HALF_EVEN:
   2788                 if (Math.abs(fraction) + parityBit > 5) {
   2789                     increment = Integer.signum(fraction);
   2790                 }
   2791                 break;
   2792         }
   2793         return increment;
   2794     }
   2795 
   2796     /**
   2797      * If {@code intVal} has a fractional part throws an exception,
   2798      * otherwise it counts the number of bits of value and checks if it's out of
   2799      * the range of the primitive type. If the number fits in the primitive type
   2800      * returns this number as {@code long}, otherwise throws an
   2801      * exception.
   2802      *
   2803      * @param bitLengthOfType
   2804      *            number of bits of the type whose value will be calculated
   2805      *            exactly
   2806      * @return the exact value of the integer part of {@code BigDecimal}
   2807      *         when is possible
   2808      * @throws ArithmeticException when rounding is necessary or the
   2809      *             number don't fit in the primitive type
   2810      */
   2811     private long valueExact(int bitLengthOfType) {
   2812         BigInteger bigInteger = toBigIntegerExact();
   2813 
   2814         if (bigInteger.bitLength() < bitLengthOfType) {
   2815             // It fits in the primitive type
   2816             return bigInteger.longValue();
   2817         }
   2818         throw new ArithmeticException("Rounding necessary");
   2819     }
   2820 
   2821     /**
   2822      * If the precision already was calculated it returns that value, otherwise
   2823      * it calculates a very good approximation efficiently . Note that this
   2824      * value will be {@code precision()} or {@code precision()-1}
   2825      * in the worst case.
   2826      *
   2827      * @return an approximation of {@code precision()} value
   2828      */
   2829     private int approxPrecision() {
   2830         return precision > 0
   2831                 ? precision
   2832                 : (int) ((this.bitLength - 1) * LOG10_2) + 1;
   2833     }
   2834 
   2835     private static int safeLongToInt(long longValue) {
   2836         if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
   2837             throw new ArithmeticException("Out of int range: " + longValue);
   2838         }
   2839         return (int) longValue;
   2840     }
   2841 
   2842     /**
   2843      * It returns the value 0 with the most approximated scale of type
   2844      * {@code int}. if {@code longScale > Integer.MAX_VALUE} the
   2845      * scale will be {@code Integer.MAX_VALUE}; if
   2846      * {@code longScale < Integer.MIN_VALUE} the scale will be
   2847      * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is
   2848      * casted to the type {@code int}.
   2849      *
   2850      * @param longScale
   2851      *            the scale to which the value 0 will be scaled.
   2852      * @return the value 0 scaled by the closer scale of type {@code int}.
   2853      * @see #scale
   2854      */
   2855     private static BigDecimal zeroScaledBy(long longScale) {
   2856         if (longScale == (int) longScale) {
   2857             return valueOf(0,(int)longScale);
   2858             }
   2859         if (longScale >= 0) {
   2860             return new BigDecimal( 0, Integer.MAX_VALUE);
   2861         }
   2862         return new BigDecimal( 0, Integer.MIN_VALUE);
   2863     }
   2864 
   2865     /**
   2866      * Assigns all transient fields upon deserialization of a
   2867      * {@code BigDecimal} instance (bitLength and smallValue). The transient
   2868      * field precision is assigned lazily.
   2869      */
   2870     private void readObject(ObjectInputStream in) throws IOException,
   2871             ClassNotFoundException {
   2872         in.defaultReadObject();
   2873 
   2874         this.bitLength = intVal.bitLength();
   2875         if (this.bitLength < 64) {
   2876             this.smallValue = intVal.longValue();
   2877         }
   2878     }
   2879 
   2880     /**
   2881      * Prepares this {@code BigDecimal} for serialization, i.e. the
   2882      * non-transient field {@code intVal} is assigned.
   2883      */
   2884     private void writeObject(ObjectOutputStream out) throws IOException {
   2885         getUnscaledValue();
   2886         out.defaultWriteObject();
   2887     }
   2888 
   2889     private BigInteger getUnscaledValue() {
   2890         if(intVal == null) {
   2891             intVal = BigInteger.valueOf(smallValue);
   2892         }
   2893         return intVal;
   2894     }
   2895 
   2896     private void setUnscaledValue(BigInteger unscaledValue) {
   2897         this.intVal = unscaledValue;
   2898         this.bitLength = unscaledValue.bitLength();
   2899         if(this.bitLength < 64) {
   2900             this.smallValue = unscaledValue.longValue();
   2901         }
   2902     }
   2903 
   2904     private static int bitLength(long smallValue) {
   2905         if(smallValue < 0) {
   2906             smallValue = ~smallValue;
   2907         }
   2908         return 64 - Long.numberOfLeadingZeros(smallValue);
   2909     }
   2910 
   2911     private static int bitLength(int smallValue) {
   2912         if(smallValue < 0) {
   2913             smallValue = ~smallValue;
   2914         }
   2915         return 32 - Integer.numberOfLeadingZeros(smallValue);
   2916     }
   2917 
   2918 }
   2919