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
18package java.math;
19
20import java.io.IOException;
21import java.io.ObjectInputStream;
22import java.io.ObjectOutputStream;
23import java.io.Serializable;
24import java.util.Arrays;
25import 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 */
35public 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
1029        // Check whether the diffScale will fit into an int. See http://b/17393664.
1030        if (bitLength(diffScale) > 32) {
1031            throw new ArithmeticException(
1032                    "Unable to perform divisor / dividend scaling: the difference in scale is too" +
1033                            " big (" + diffScale + ")");
1034        }
1035
1036        if(this.bitLength < 64 && divisor.bitLength < 64 ) {
1037            if(diffScale == 0) {
1038                return dividePrimitiveLongs(this.smallValue,
1039                        divisor.smallValue,
1040                        scale,
1041                        roundingMode );
1042            } else if(diffScale > 0) {
1043                if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1044                        divisor.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale] < 64) {
1045                    return dividePrimitiveLongs(this.smallValue,
1046                            divisor.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],
1047                            scale,
1048                            roundingMode);
1049                }
1050            } else { // diffScale < 0
1051                if(-diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1052                        this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-diffScale] < 64) {
1053                    return dividePrimitiveLongs(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale],
1054                            divisor.smallValue,
1055                            scale,
1056                            roundingMode);
1057                }
1058
1059            }
1060        }
1061        BigInteger scaledDividend = this.getUnscaledValue();
1062        BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2'
1063
1064        if (diffScale > 0) {
1065            // Multiply 'u2'  by:  10^((s1 - s2) - scale)
1066            scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale);
1067        } else if (diffScale < 0) {
1068            // Multiply 'u1'  by:  10^(scale - (s1 - s2))
1069            scaledDividend  = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale);
1070        }
1071        return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode);
1072        }
1073
1074    private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) {
1075
1076        BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor);  // quotient and remainder
1077        // If after division there is a remainder...
1078        BigInteger quotient = quotAndRem[0];
1079        BigInteger remainder = quotAndRem[1];
1080        if (remainder.signum() == 0) {
1081            return new BigDecimal(quotient, scale);
1082        }
1083        int sign = scaledDividend.signum() * scaledDivisor.signum();
1084        int compRem;                                      // 'compare to remainder'
1085        if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2
1086            long rem = remainder.longValue();
1087            long divisor = scaledDivisor.longValue();
1088            compRem = longCompareTo(Math.abs(rem) * 2,Math.abs(divisor));
1089            // To look if there is a carry
1090            compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
1091                    sign * (5 + compRem), roundingMode);
1092
1093        } else {
1094            // Checking if:  remainder * 2 >= scaledDivisor
1095            compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs());
1096            compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0,
1097                    sign * (5 + compRem), roundingMode);
1098        }
1099            if (compRem != 0) {
1100            if(quotient.bitLength() < 63) {
1101                return valueOf(quotient.longValue() + compRem,scale);
1102            }
1103            quotient = quotient.add(BigInteger.valueOf(compRem));
1104            return new BigDecimal(quotient, scale);
1105        }
1106        // Constructing the result with the appropriate unscaled value
1107        return new BigDecimal(quotient, scale);
1108    }
1109
1110    private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) {
1111        long quotient = scaledDividend / scaledDivisor;
1112        long remainder = scaledDividend % scaledDivisor;
1113        int sign = Long.signum( scaledDividend ) * Long.signum( scaledDivisor );
1114        if (remainder != 0) {
1115            // Checking if:  remainder * 2 >= scaledDivisor
1116            int compRem;                                      // 'compare to remainder'
1117            compRem = longCompareTo(Math.abs(remainder) * 2,Math.abs(scaledDivisor));
1118            // To look if there is a carry
1119            quotient += roundingBehavior(((int)quotient) & 1,
1120                    sign * (5 + compRem),
1121                    roundingMode);
1122        }
1123        // Constructing the result with the appropriate unscaled value
1124        return valueOf(quotient, scale);
1125    }
1126
1127    /**
1128     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1129     * The scale of the result is the scale of {@code this}. If rounding is
1130     * required to meet the specified scale, then the specified rounding mode
1131     * {@code roundingMode} is applied.
1132     *
1133     * @param divisor
1134     *            value by which {@code this} is divided.
1135     * @param roundingMode
1136     *            rounding mode to be used to round the result.
1137     * @return {@code this / divisor} rounded according to the given rounding
1138     *         mode.
1139     * @throws NullPointerException
1140     *             if {@code divisor == null}.
1141     * @throws IllegalArgumentException
1142     *             if {@code roundingMode} is not a valid rounding mode.
1143     * @throws ArithmeticException
1144     *             if {@code divisor == 0}.
1145     * @throws ArithmeticException
1146     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1147     *             necessary according to the scale of this.
1148     */
1149    public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1150        return divide(divisor, scale, RoundingMode.valueOf(roundingMode));
1151    }
1152
1153    /**
1154     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1155     * The scale of the result is the scale of {@code this}. If rounding is
1156     * required to meet the specified scale, then the specified rounding mode
1157     * {@code roundingMode} is applied.
1158     *
1159     * @param divisor
1160     *            value by which {@code this} is divided.
1161     * @param roundingMode
1162     *            rounding mode to be used to round the result.
1163     * @return {@code this / divisor} rounded according to the given rounding
1164     *         mode.
1165     * @throws NullPointerException
1166     *             if {@code divisor == null} or {@code roundingMode == null}.
1167     * @throws ArithmeticException
1168     *             if {@code divisor == 0}.
1169     * @throws ArithmeticException
1170     *             if {@code roundingMode == RoundingMode.UNNECESSARY} and
1171     *             rounding is necessary according to the scale of this.
1172     */
1173    public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1174        return divide(divisor, scale, roundingMode);
1175    }
1176
1177    /**
1178     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1179     * The scale of the result is the difference of the scales of {@code this}
1180     * and {@code divisor}. If the exact result requires more digits, then the
1181     * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125}
1182     * which has a scale of {@code 7} and precision {@code 5}.
1183     *
1184     * @param divisor
1185     *            value by which {@code this} is divided.
1186     * @return {@code this / divisor}.
1187     * @throws NullPointerException
1188     *             if {@code divisor == null}.
1189     * @throws ArithmeticException
1190     *             if {@code divisor == 0}.
1191     * @throws ArithmeticException
1192     *             if the result cannot be represented exactly.
1193     */
1194    public BigDecimal divide(BigDecimal divisor) {
1195        BigInteger p = this.getUnscaledValue();
1196        BigInteger q = divisor.getUnscaledValue();
1197        BigInteger gcd; // greatest common divisor between 'p' and 'q'
1198        BigInteger quotAndRem[];
1199        long diffScale = (long)scale - divisor.scale;
1200        int newScale; // the new scale for final quotient
1201        int k; // number of factors "2" in 'q'
1202        int l = 0; // number of factors "5" in 'q'
1203        int i = 1;
1204        int lastPow = FIVE_POW.length - 1;
1205
1206        if (divisor.isZero()) {
1207            throw new ArithmeticException("Division by zero");
1208        }
1209        if (p.signum() == 0) {
1210            return zeroScaledBy(diffScale);
1211        }
1212        // To divide both by the GCD
1213        gcd = p.gcd(q);
1214        p = p.divide(gcd);
1215        q = q.divide(gcd);
1216        // To simplify all "2" factors of q, dividing by 2^k
1217        k = q.getLowestSetBit();
1218        q = q.shiftRight(k);
1219        // To simplify all "5" factors of q, dividing by 5^l
1220        do {
1221            quotAndRem = q.divideAndRemainder(FIVE_POW[i]);
1222            if (quotAndRem[1].signum() == 0) {
1223                l += i;
1224                if (i < lastPow) {
1225                    i++;
1226                }
1227                q = quotAndRem[0];
1228            } else {
1229                if (i == 1) {
1230                    break;
1231                }
1232                i = 1;
1233            }
1234        } while (true);
1235        // If  abs(q) != 1  then the quotient is periodic
1236        if (!q.abs().equals(BigInteger.ONE)) {
1237            throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result");
1238        }
1239        // The sign of the is fixed and the quotient will be saved in 'p'
1240        if (q.signum() < 0) {
1241            p = p.negate();
1242        }
1243        // Checking if the new scale is out of range
1244        newScale = safeLongToInt(diffScale + Math.max(k, l));
1245        // k >= 0  and  l >= 0  implies that  k - l  is in the 32-bit range
1246        i = k - l;
1247
1248        p = (i > 0) ? Multiplication.multiplyByFivePow(p, i)
1249        : p.shiftLeft(-i);
1250        return new BigDecimal(p, newScale);
1251    }
1252
1253    /**
1254     * Returns a new {@code BigDecimal} whose value is {@code this / divisor}.
1255     * The result is rounded according to the passed context {@code mc}. If the
1256     * passed math context specifies precision {@code 0}, then this call is
1257     * equivalent to {@code this.divide(divisor)}.
1258     *
1259     * @param divisor
1260     *            value by which {@code this} is divided.
1261     * @param mc
1262     *            rounding mode and precision for the result of this operation.
1263     * @return {@code this / divisor}.
1264     * @throws NullPointerException
1265     *             if {@code divisor == null} or {@code mc == null}.
1266     * @throws ArithmeticException
1267     *             if {@code divisor == 0}.
1268     * @throws ArithmeticException
1269     *             if {@code mc.getRoundingMode() == UNNECESSARY} and rounding
1270     *             is necessary according {@code mc.getPrecision()}.
1271     */
1272    public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1273        /* Calculating how many zeros must be append to 'dividend'
1274         * to obtain a  quotient with at least 'mc.precision()' digits */
1275        long trailingZeros = mc.getPrecision() + 2L
1276                + divisor.approxPrecision() - approxPrecision();
1277        long diffScale = (long)scale - divisor.scale;
1278        long newScale = diffScale; // scale of the final quotient
1279        int compRem; // to compare the remainder
1280        int i = 1; // index
1281        int lastPow = TEN_POW.length - 1; // last power of ten
1282        BigInteger integerQuot; // for temporal results
1283        BigInteger quotAndRem[] = {getUnscaledValue()};
1284        // In special cases it reduces the problem to call the dual method
1285        if ((mc.getPrecision() == 0) || (this.isZero())
1286        || (divisor.isZero())) {
1287            return this.divide(divisor);
1288        }
1289        if (trailingZeros > 0) {
1290            // To append trailing zeros at end of dividend
1291            quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(trailingZeros) );
1292            newScale += trailingZeros;
1293        }
1294        quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() );
1295        integerQuot = quotAndRem[0];
1296        // Calculating the exact quotient with at least 'mc.precision()' digits
1297        if (quotAndRem[1].signum() != 0) {
1298            // Checking if:   2 * remainder >= divisor ?
1299            compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() );
1300            // quot := quot * 10 + r;     with 'r' in {-6,-5,-4, 0,+4,+5,+6}
1301            integerQuot = integerQuot.multiply(BigInteger.TEN)
1302            .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem)));
1303            newScale++;
1304        } else {
1305            // To strip trailing zeros until the preferred scale is reached
1306            while (!integerQuot.testBit(0)) {
1307                quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]);
1308                if ((quotAndRem[1].signum() == 0)
1309                        && (newScale - i >= diffScale)) {
1310                    newScale -= i;
1311                    if (i < lastPow) {
1312                        i++;
1313                    }
1314                    integerQuot = quotAndRem[0];
1315                } else {
1316                    if (i == 1) {
1317                        break;
1318                    }
1319                    i = 1;
1320                }
1321            }
1322        }
1323        // To perform rounding
1324        return new BigDecimal(integerQuot, safeLongToInt(newScale), mc);
1325    }
1326
1327    /**
1328     * Returns a new {@code BigDecimal} whose value is the integral part of
1329     * {@code this / divisor}. The quotient is rounded down towards zero to the
1330     * next integer. For example, {@code 0.5/0.2 = 2}.
1331     *
1332     * @param divisor
1333     *            value by which {@code this} is divided.
1334     * @return integral part of {@code this / divisor}.
1335     * @throws NullPointerException
1336     *             if {@code divisor == null}.
1337     * @throws ArithmeticException
1338     *             if {@code divisor == 0}.
1339     */
1340    public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1341        BigInteger integralValue; // the integer of result
1342        BigInteger powerOfTen; // some power of ten
1343        BigInteger quotAndRem[] = {getUnscaledValue()};
1344        long newScale = (long)this.scale - divisor.scale;
1345        long tempScale = 0;
1346        int i = 1;
1347        int lastPow = TEN_POW.length - 1;
1348
1349        if (divisor.isZero()) {
1350            throw new ArithmeticException("Division by zero");
1351        }
1352        if ((divisor.approxPrecision() + newScale > this.approxPrecision() + 1L)
1353        || (this.isZero())) {
1354            /* If the divisor's integer part is greater than this's integer part,
1355             * the result must be zero with the appropriate scale */
1356            integralValue = BigInteger.ZERO;
1357        } else if (newScale == 0) {
1358            integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() );
1359        } else if (newScale > 0) {
1360            powerOfTen = Multiplication.powerOf10(newScale);
1361            integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) );
1362            integralValue = integralValue.multiply(powerOfTen);
1363        } else {// (newScale < 0)
1364            powerOfTen = Multiplication.powerOf10(-newScale);
1365            integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() );
1366            // To strip trailing zeros approximating to the preferred scale
1367            while (!integralValue.testBit(0)) {
1368                quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]);
1369                if ((quotAndRem[1].signum() == 0)
1370                        && (tempScale - i >= newScale)) {
1371                    tempScale -= i;
1372                    if (i < lastPow) {
1373                        i++;
1374                    }
1375                    integralValue = quotAndRem[0];
1376                } else {
1377                    if (i == 1) {
1378                        break;
1379                    }
1380                    i = 1;
1381                }
1382            }
1383            newScale = tempScale;
1384        }
1385        return ((integralValue.signum() == 0)
1386        ? zeroScaledBy(newScale)
1387                : new BigDecimal(integralValue, safeLongToInt(newScale)));
1388    }
1389
1390    /**
1391     * Returns a new {@code BigDecimal} whose value is the integral part of
1392     * {@code this / divisor}. The quotient is rounded down towards zero to the
1393     * next integer. The rounding mode passed with the parameter {@code mc} is
1394     * not considered. But if the precision of {@code mc > 0} and the integral
1395     * part requires more digits, then an {@code ArithmeticException} is thrown.
1396     *
1397     * @param divisor
1398     *            value by which {@code this} is divided.
1399     * @param mc
1400     *            math context which determines the maximal precision of the
1401     *            result.
1402     * @return integral part of {@code this / divisor}.
1403     * @throws NullPointerException
1404     *             if {@code divisor == null} or {@code mc == null}.
1405     * @throws ArithmeticException
1406     *             if {@code divisor == 0}.
1407     * @throws ArithmeticException
1408     *             if {@code mc.getPrecision() > 0} and the result requires more
1409     *             digits to be represented.
1410     */
1411    public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1412        int mcPrecision = mc.getPrecision();
1413        int diffPrecision = this.precision() - divisor.precision();
1414        int lastPow = TEN_POW.length - 1;
1415        long diffScale = (long)this.scale - divisor.scale;
1416        long newScale = diffScale;
1417        long quotPrecision = diffPrecision - diffScale + 1;
1418        BigInteger quotAndRem[] = new BigInteger[2];
1419        // In special cases it call the dual method
1420        if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) {
1421            return this.divideToIntegralValue(divisor);
1422        }
1423        // Let be:   this = [u1,s1]   and   divisor = [u2,s2]
1424        if (quotPrecision <= 0) {
1425            quotAndRem[0] = BigInteger.ZERO;
1426        } else if (diffScale == 0) {
1427            // CASE s1 == s2:  to calculate   u1 / u2
1428            quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() );
1429        } else if (diffScale > 0) {
1430            // CASE s1 >= s2:  to calculate   u1 / (u2 * 10^(s1-s2)
1431            quotAndRem[0] = this.getUnscaledValue().divide(
1432                    divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) );
1433            // To chose  10^newScale  to get a quotient with at least 'mc.precision()' digits
1434            newScale = Math.min(diffScale, Math.max(mcPrecision - quotPrecision + 1, 0));
1435            // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale
1436            quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale));
1437        } else {// CASE s2 > s1:
1438            /* To calculate the minimum power of ten, such that the quotient
1439             *   (u1 * 10^exp) / u2   has at least 'mc.precision()' digits. */
1440            long exp = Math.min(-diffScale, Math.max((long)mcPrecision - diffPrecision, 0));
1441            long compRemDiv;
1442            // Let be:   (u1 * 10^exp) / u2 = [q,r]
1443            quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)).
1444                    divideAndRemainder(divisor.getUnscaledValue());
1445            newScale += exp; // To fix the scale
1446            exp = -newScale; // The remaining power of ten
1447            // If after division there is a remainder...
1448            if ((quotAndRem[1].signum() != 0) && (exp > 0)) {
1449                // Log10(r) + ((s2 - s1) - exp) > mc.precision ?
1450                compRemDiv = (new BigDecimal(quotAndRem[1])).precision()
1451                + exp - divisor.precision();
1452                if (compRemDiv == 0) {
1453                    // To calculate:  (r * 10^exp2) / u2
1454                    quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)).
1455                            divide(divisor.getUnscaledValue());
1456                    compRemDiv = Math.abs(quotAndRem[1].signum());
1457                }
1458                if (compRemDiv > 0) {
1459                    throw new ArithmeticException("Division impossible");
1460                }
1461            }
1462        }
1463        // Fast return if the quotient is zero
1464        if (quotAndRem[0].signum() == 0) {
1465            return zeroScaledBy(diffScale);
1466        }
1467        BigInteger strippedBI = quotAndRem[0];
1468        BigDecimal integralValue = new BigDecimal(quotAndRem[0]);
1469        long resultPrecision = integralValue.precision();
1470        int i = 1;
1471        // To strip trailing zeros until the specified precision is reached
1472        while (!strippedBI.testBit(0)) {
1473            quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
1474            if ((quotAndRem[1].signum() == 0) &&
1475                    ((resultPrecision - i >= mcPrecision)
1476                    || (newScale - i >= diffScale)) ) {
1477                resultPrecision -= i;
1478                newScale -= i;
1479                if (i < lastPow) {
1480                    i++;
1481                }
1482                strippedBI = quotAndRem[0];
1483            } else {
1484                if (i == 1) {
1485                    break;
1486                }
1487                i = 1;
1488            }
1489        }
1490        // To check if the result fit in 'mc.precision()' digits
1491        if (resultPrecision > mcPrecision) {
1492            throw new ArithmeticException("Division impossible");
1493        }
1494        integralValue.scale = safeLongToInt(newScale);
1495        integralValue.setUnscaledValue(strippedBI);
1496        return integralValue;
1497    }
1498
1499    /**
1500     * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
1501     * <p>
1502     * The remainder is defined as {@code this -
1503     * this.divideToIntegralValue(divisor) * divisor}.
1504     *
1505     * @param divisor
1506     *            value by which {@code this} is divided.
1507     * @return {@code this % divisor}.
1508     * @throws NullPointerException
1509     *             if {@code divisor == null}.
1510     * @throws ArithmeticException
1511     *             if {@code divisor == 0}.
1512     */
1513    public BigDecimal remainder(BigDecimal divisor) {
1514        return divideAndRemainder(divisor)[1];
1515    }
1516
1517    /**
1518     * Returns a new {@code BigDecimal} whose value is {@code this % divisor}.
1519     * <p>
1520     * The remainder is defined as {@code this -
1521     * this.divideToIntegralValue(divisor) * divisor}.
1522     * <p>
1523     * The specified rounding mode {@code mc} is used for the division only.
1524     *
1525     * @param divisor
1526     *            value by which {@code this} is divided.
1527     * @param mc
1528     *            rounding mode and precision to be used.
1529     * @return {@code this % divisor}.
1530     * @throws NullPointerException
1531     *             if {@code divisor == null}.
1532     * @throws ArithmeticException
1533     *             if {@code divisor == 0}.
1534     * @throws ArithmeticException
1535     *             if {@code mc.getPrecision() > 0} and the result of {@code
1536     *             this.divideToIntegralValue(divisor, mc)} requires more digits
1537     *             to be represented.
1538     */
1539    public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1540        return divideAndRemainder(divisor, mc)[1];
1541    }
1542
1543    /**
1544     * Returns a {@code BigDecimal} array which contains the integral part of
1545     * {@code this / divisor} at index 0 and the remainder {@code this %
1546     * divisor} at index 1. The quotient is rounded down towards zero to the
1547     * next integer.
1548     *
1549     * @param divisor
1550     *            value by which {@code this} is divided.
1551     * @return {@code [this.divideToIntegralValue(divisor),
1552     *         this.remainder(divisor)]}.
1553     * @throws NullPointerException
1554     *             if {@code divisor == null}.
1555     * @throws ArithmeticException
1556     *             if {@code divisor == 0}.
1557     * @see #divideToIntegralValue
1558     * @see #remainder
1559     */
1560    public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1561        BigDecimal quotAndRem[] = new BigDecimal[2];
1562
1563        quotAndRem[0] = this.divideToIntegralValue(divisor);
1564        quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
1565        return quotAndRem;
1566    }
1567
1568    /**
1569     * Returns a {@code BigDecimal} array which contains the integral part of
1570     * {@code this / divisor} at index 0 and the remainder {@code this %
1571     * divisor} at index 1. The quotient is rounded down towards zero to the
1572     * next integer. The rounding mode passed with the parameter {@code mc} is
1573     * not considered. But if the precision of {@code mc > 0} and the integral
1574     * part requires more digits, then an {@code ArithmeticException} is thrown.
1575     *
1576     * @param divisor
1577     *            value by which {@code this} is divided.
1578     * @param mc
1579     *            math context which determines the maximal precision of the
1580     *            result.
1581     * @return {@code [this.divideToIntegralValue(divisor),
1582     *         this.remainder(divisor)]}.
1583     * @throws NullPointerException
1584     *             if {@code divisor == null}.
1585     * @throws ArithmeticException
1586     *             if {@code divisor == 0}.
1587     * @see #divideToIntegralValue
1588     * @see #remainder
1589     */
1590    public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1591        BigDecimal quotAndRem[] = new BigDecimal[2];
1592
1593        quotAndRem[0] = this.divideToIntegralValue(divisor, mc);
1594        quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) );
1595        return quotAndRem;
1596    }
1597
1598    /**
1599     * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The
1600     * scale of the result is {@code n * this.scale()}.
1601     *
1602     * <p>{@code x.pow(0)} returns {@code 1}, even if {@code x == 0}.
1603     *
1604     * <p>Implementation Note: The implementation is based on the ANSI standard
1605     * X3.274-1996 algorithm.
1606     *
1607     * @throws ArithmeticException
1608     *             if {@code n < 0} or {@code n > 999999999}.
1609     */
1610    public BigDecimal pow(int n) {
1611        if (n == 0) {
1612            return ONE;
1613        }
1614        if ((n < 0) || (n > 999999999)) {
1615            throw new ArithmeticException("Invalid operation");
1616        }
1617        long newScale = scale * (long)n;
1618        // Let be: this = [u,s]   so:  this^n = [u^n, s*n]
1619        return isZero() ? zeroScaledBy(newScale)
1620                : new BigDecimal(getUnscaledValue().pow(n), safeLongToInt(newScale));
1621    }
1622
1623    /**
1624     * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The
1625     * result is rounded according to the passed context {@code mc}.
1626     *
1627     * <p>Implementation Note: The implementation is based on the ANSI standard
1628     * X3.274-1996 algorithm.
1629     *
1630     * @param mc
1631     *            rounding mode and precision for the result of this operation.
1632     * @throws ArithmeticException
1633     *             if {@code n < 0} or {@code n > 999999999}.
1634     */
1635    public BigDecimal pow(int n, MathContext mc) {
1636        // The ANSI standard X3.274-1996 algorithm
1637        int m = Math.abs(n);
1638        int mcPrecision = mc.getPrecision();
1639        int elength = (int)Math.log10(m) + 1;   // decimal digits in 'n'
1640        int oneBitMask; // mask of bits
1641        BigDecimal accum; // the single accumulator
1642        MathContext newPrecision = mc; // MathContext by default
1643
1644        // In particular cases, it reduces the problem to call the other 'pow()'
1645        if ((n == 0) || ((isZero()) && (n > 0))) {
1646            return pow(n);
1647        }
1648        if ((m > 999999999) || ((mcPrecision == 0) && (n < 0))
1649                || ((mcPrecision > 0) && (elength > mcPrecision))) {
1650            throw new ArithmeticException("Invalid operation");
1651        }
1652        if (mcPrecision > 0) {
1653            newPrecision = new MathContext( mcPrecision + elength + 1,
1654                    mc.getRoundingMode());
1655        }
1656        // The result is calculated as if 'n' were positive
1657        accum = round(newPrecision);
1658        oneBitMask = Integer.highestOneBit(m) >> 1;
1659
1660        while (oneBitMask > 0) {
1661            accum = accum.multiply(accum, newPrecision);
1662            if ((m & oneBitMask) == oneBitMask) {
1663                accum = accum.multiply(this, newPrecision);
1664            }
1665            oneBitMask >>= 1;
1666        }
1667        // If 'n' is negative, the value is divided into 'ONE'
1668        if (n < 0) {
1669            accum = ONE.divide(accum, newPrecision);
1670        }
1671        // The final value is rounded to the destination precision
1672        accum.inplaceRound(mc);
1673        return accum;
1674    }
1675
1676    /**
1677     * Returns a {@code BigDecimal} whose value is the absolute value of
1678     * {@code this}. The scale of the result is the same as the scale of this.
1679     */
1680    public BigDecimal abs() {
1681        return ((signum() < 0) ? negate() : this);
1682    }
1683
1684    /**
1685     * Returns a {@code BigDecimal} whose value is the absolute value of
1686     * {@code this}. The result is rounded according to the passed context
1687     * {@code mc}.
1688     */
1689    public BigDecimal abs(MathContext mc) {
1690        BigDecimal result = (signum() < 0) ? negate() : new BigDecimal(getUnscaledValue(), scale);
1691        result.inplaceRound(mc);
1692        return result;
1693    }
1694
1695    /**
1696     * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
1697     * scale of the result is the same as the scale of this.
1698     *
1699     * @return {@code -this}
1700     */
1701    public BigDecimal negate() {
1702        if(bitLength < 63 || (bitLength == 63 && smallValue!=Long.MIN_VALUE)) {
1703            return valueOf(-smallValue,scale);
1704        }
1705        return new BigDecimal(getUnscaledValue().negate(), scale);
1706    }
1707
1708    /**
1709     * Returns a new {@code BigDecimal} whose value is the {@code -this}. The
1710     * result is rounded according to the passed context {@code mc}.
1711     *
1712     * @param mc
1713     *            rounding mode and precision for the result of this operation.
1714     * @return {@code -this}
1715     */
1716    public BigDecimal negate(MathContext mc) {
1717        BigDecimal result = negate();
1718        result.inplaceRound(mc);
1719        return result;
1720    }
1721
1722    /**
1723     * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale
1724     * of the result is the same as the scale of this.
1725     *
1726     * @return {@code this}
1727     */
1728    public BigDecimal plus() {
1729        return this;
1730    }
1731
1732    /**
1733     * Returns a new {@code BigDecimal} whose value is {@code +this}. The result
1734     * is rounded according to the passed context {@code mc}.
1735     *
1736     * @param mc
1737     *            rounding mode and precision for the result of this operation.
1738     * @return {@code this}, rounded
1739     */
1740    public BigDecimal plus(MathContext mc) {
1741        return round(mc);
1742    }
1743
1744    /**
1745     * Returns the sign of this {@code BigDecimal}.
1746     *
1747     * @return {@code -1} if {@code this < 0},
1748     *         {@code 0} if {@code this == 0},
1749     *         {@code 1} if {@code this > 0}.
1750     */
1751    public int signum() {
1752        if( bitLength < 64) {
1753            return Long.signum( this.smallValue );
1754        }
1755        return getUnscaledValue().signum();
1756    }
1757
1758    private boolean isZero() {
1759        //Watch out: -1 has a bitLength=0
1760        return bitLength == 0 && this.smallValue != -1;
1761    }
1762
1763    /**
1764     * Returns the scale of this {@code BigDecimal}. The scale is the number of
1765     * digits behind the decimal point. The value of this {@code BigDecimal} is
1766     * the {@code unsignedValue * 10<sup>-scale</sup>}. If the scale is negative,
1767     * then this {@code BigDecimal} represents a big integer.
1768     *
1769     * @return the scale of this {@code BigDecimal}.
1770     */
1771    public int scale() {
1772        return scale;
1773    }
1774
1775    /**
1776     * Returns the precision of this {@code BigDecimal}. The precision is the
1777     * number of decimal digits used to represent this decimal. It is equivalent
1778     * to the number of digits of the unscaled value. The precision of {@code 0}
1779     * is {@code 1} (independent of the scale).
1780     *
1781     * @return the precision of this {@code BigDecimal}.
1782     */
1783    public int precision() {
1784        // Return the cached value if we have one.
1785        if (precision != 0) {
1786            return precision;
1787        }
1788
1789        if (bitLength == 0) {
1790            precision = 1;
1791        } else if (bitLength < 64) {
1792            precision = decimalDigitsInLong(smallValue);
1793        } else {
1794            int decimalDigits = 1 + (int) ((bitLength - 1) * LOG10_2);
1795            // If after division the number isn't zero, there exists an additional digit
1796            if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) {
1797                decimalDigits++;
1798            }
1799            precision = decimalDigits;
1800        }
1801        return precision;
1802    }
1803
1804    private int decimalDigitsInLong(long value) {
1805        if (value == Long.MIN_VALUE) {
1806            return 19; // special case required because abs(MIN_VALUE) == MIN_VALUE
1807        } else {
1808            int index = Arrays.binarySearch(MathUtils.LONG_POWERS_OF_TEN, Math.abs(value));
1809            return (index < 0) ? (-index - 1) : (index + 1);
1810        }
1811    }
1812
1813    /**
1814     * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance
1815     * as a {@code BigInteger}. The unscaled value can be computed as
1816     * {@code this * 10<sup>scale</sup>}.
1817     */
1818    public BigInteger unscaledValue() {
1819        return getUnscaledValue();
1820    }
1821
1822    /**
1823     * Returns a new {@code BigDecimal} whose value is {@code this}, rounded
1824     * according to the passed context {@code mc}.
1825     * <p>
1826     * If {@code mc.precision = 0}, then no rounding is performed.
1827     * <p>
1828     * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY},
1829     * then an {@code ArithmeticException} is thrown if the result cannot be
1830     * represented exactly within the given precision.
1831     *
1832     * @param mc
1833     *            rounding mode and precision for the result of this operation.
1834     * @return {@code this} rounded according to the passed context.
1835     * @throws ArithmeticException
1836     *             if {@code mc.precision > 0} and {@code mc.roundingMode ==
1837     *             UNNECESSARY} and this cannot be represented within the given
1838     *             precision.
1839     */
1840    public BigDecimal round(MathContext mc) {
1841        BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scale);
1842
1843        thisBD.inplaceRound(mc);
1844        return thisBD;
1845    }
1846
1847    /**
1848     * Returns a new {@code BigDecimal} instance with the specified scale.
1849     * <p>
1850     * If the new scale is greater than the old scale, then additional zeros are
1851     * added to the unscaled value. In this case no rounding is necessary.
1852     * <p>
1853     * If the new scale is smaller than the old scale, then trailing digits are
1854     * removed. If these trailing digits are not zero, then the remaining
1855     * unscaled value has to be rounded. For this rounding operation the
1856     * specified rounding mode is used.
1857     *
1858     * @param newScale
1859     *            scale of the result returned.
1860     * @param roundingMode
1861     *            rounding mode to be used to round the result.
1862     * @return a new {@code BigDecimal} instance with the specified scale.
1863     * @throws NullPointerException
1864     *             if {@code roundingMode == null}.
1865     * @throws ArithmeticException
1866     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1867     *             necessary according to the given scale.
1868     */
1869    public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
1870        if (roundingMode == null) {
1871            throw new NullPointerException("roundingMode == null");
1872        }
1873        long diffScale = newScale - (long)scale;
1874        // Let be:  'this' = [u,s]
1875        if(diffScale == 0) {
1876            return this;
1877        }
1878        if(diffScale > 0) {
1879        // return  [u * 10^(s2 - s), newScale]
1880            if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1881                    (this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale]) < 64 ) {
1882                return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],newScale);
1883            }
1884            return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale);
1885        }
1886        // diffScale < 0
1887        // return  [u,s] / [1,newScale]  with the appropriate scale and rounding
1888        if(this.bitLength < 64 && -diffScale < MathUtils.LONG_POWERS_OF_TEN.length) {
1889            return dividePrimitiveLongs(this.smallValue, MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], newScale,roundingMode);
1890        }
1891        return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode);
1892    }
1893
1894    /**
1895     * Returns a new {@code BigDecimal} instance with the specified scale.
1896     * <p>
1897     * If the new scale is greater than the old scale, then additional zeros are
1898     * added to the unscaled value. In this case no rounding is necessary.
1899     * <p>
1900     * If the new scale is smaller than the old scale, then trailing digits are
1901     * removed. If these trailing digits are not zero, then the remaining
1902     * unscaled value has to be rounded. For this rounding operation the
1903     * specified rounding mode is used.
1904     *
1905     * @param newScale
1906     *            scale of the result returned.
1907     * @param roundingMode
1908     *            rounding mode to be used to round the result.
1909     * @return a new {@code BigDecimal} instance with the specified scale.
1910     * @throws IllegalArgumentException
1911     *             if {@code roundingMode} is not a valid rounding mode.
1912     * @throws ArithmeticException
1913     *             if {@code roundingMode == ROUND_UNNECESSARY} and rounding is
1914     *             necessary according to the given scale.
1915     */
1916    public BigDecimal setScale(int newScale, int roundingMode) {
1917        return setScale(newScale, RoundingMode.valueOf(roundingMode));
1918    }
1919
1920    /**
1921     * Returns a new {@code BigDecimal} instance with the specified scale. If
1922     * the new scale is greater than the old scale, then additional zeros are
1923     * added to the unscaled value. If the new scale is smaller than the old
1924     * scale, then trailing zeros are removed. If the trailing digits are not
1925     * zeros then an ArithmeticException is thrown.
1926     * <p>
1927     * If no exception is thrown, then the following equation holds: {@code
1928     * x.setScale(s).compareTo(x) == 0}.
1929     *
1930     * @param newScale
1931     *            scale of the result returned.
1932     * @return a new {@code BigDecimal} instance with the specified scale.
1933     * @throws ArithmeticException
1934     *             if rounding would be necessary.
1935     */
1936    public BigDecimal setScale(int newScale) {
1937        return setScale(newScale, RoundingMode.UNNECESSARY);
1938    }
1939
1940    /**
1941     * Returns a new {@code BigDecimal} instance where the decimal point has
1942     * been moved {@code n} places to the left. If {@code n < 0} then the
1943     * decimal point is moved {@code -n} places to the right.
1944     *
1945     * <p>The result is obtained by changing its scale. If the scale of the result
1946     * becomes negative, then its precision is increased such that the scale is
1947     * zero.
1948     *
1949     * <p>Note, that {@code movePointLeft(0)} returns a result which is
1950     * mathematically equivalent, but which has {@code scale >= 0}.
1951     */
1952    public BigDecimal movePointLeft(int n) {
1953        return movePoint(scale + (long)n);
1954    }
1955
1956    private BigDecimal movePoint(long newScale) {
1957        if (isZero()) {
1958            return zeroScaledBy(Math.max(newScale, 0));
1959        }
1960        /*
1961         * When: 'n'== Integer.MIN_VALUE isn't possible to call to
1962         * movePointRight(-n) since -Integer.MIN_VALUE == Integer.MIN_VALUE
1963         */
1964        if(newScale >= 0) {
1965            if(bitLength < 64) {
1966                return valueOf(smallValue, safeLongToInt(newScale));
1967            }
1968            return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
1969        }
1970        if(-newScale < MathUtils.LONG_POWERS_OF_TEN.length &&
1971                bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-newScale] < 64 ) {
1972            return valueOf(smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-newScale],0);
1973        }
1974        return new BigDecimal(Multiplication.multiplyByTenPow(
1975                getUnscaledValue(), safeLongToInt(-newScale)), 0);
1976    }
1977
1978    /**
1979     * Returns a new {@code BigDecimal} instance where the decimal point has
1980     * been moved {@code n} places to the right. If {@code n < 0} then the
1981     * decimal point is moved {@code -n} places to the left.
1982     *
1983     * <p>The result is obtained by changing its scale. If the scale of the result
1984     * becomes negative, then its precision is increased such that the scale is
1985     * zero.
1986     *
1987     * <p>Note, that {@code movePointRight(0)} returns a result which is
1988     * mathematically equivalent, but which has scale >= 0.
1989     */
1990    public BigDecimal movePointRight(int n) {
1991        return movePoint(scale - (long)n);
1992    }
1993
1994    /**
1995     * Returns a new {@code BigDecimal} whose value is {@code this * 10<sup>n</sup>}.
1996     * The scale of the result is {@code this.scale()} - {@code n}.
1997     * The precision of the result is the precision of {@code this}.
1998     *
1999     * <p>This method has the same effect as {@link #movePointRight}, except that
2000     * the precision is not changed.
2001     */
2002    public BigDecimal scaleByPowerOfTen(int n) {
2003        long newScale = scale - (long)n;
2004        if(bitLength < 64) {
2005            //Taking care when a 0 is to be scaled
2006            if( smallValue==0  ){
2007                return zeroScaledBy( newScale );
2008            }
2009            return valueOf(smallValue, safeLongToInt(newScale));
2010        }
2011        return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale));
2012    }
2013
2014    /**
2015     * Returns a new {@code BigDecimal} instance with the same value as {@code
2016     * this} but with a unscaled value where the trailing zeros have been
2017     * removed. If the unscaled value of {@code this} has n trailing zeros, then
2018     * the scale and the precision of the result has been reduced by n.
2019     *
2020     * @return a new {@code BigDecimal} instance equivalent to this where the
2021     *         trailing zeros of the unscaled value have been removed.
2022     */
2023    public BigDecimal stripTrailingZeros() {
2024        int i = 1; // 1 <= i <= 18
2025        int lastPow = TEN_POW.length - 1;
2026        long newScale = scale;
2027
2028        if (isZero()) {
2029            // Preserve RI compatibility, so BigDecimal.equals (which checks
2030            // value *and* scale) continues to work.
2031            return this;
2032        }
2033        BigInteger strippedBI = getUnscaledValue();
2034        BigInteger[] quotAndRem;
2035
2036        // while the number is even...
2037        while (!strippedBI.testBit(0)) {
2038            // To divide by 10^i
2039            quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]);
2040            // To look the remainder
2041            if (quotAndRem[1].signum() == 0) {
2042                // To adjust the scale
2043                newScale -= i;
2044                if (i < lastPow) {
2045                    // To set to the next power
2046                    i++;
2047                }
2048                strippedBI = quotAndRem[0];
2049            } else {
2050                if (i == 1) {
2051                    // 'this' has no more trailing zeros
2052                    break;
2053                }
2054                // To set to the smallest power of ten
2055                i = 1;
2056            }
2057        }
2058        return new BigDecimal(strippedBI, safeLongToInt(newScale));
2059    }
2060
2061    /**
2062     * Compares this {@code BigDecimal} with {@code val}. Returns one of the
2063     * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as
2064     * if {@code this.subtract(val)} is computed. If this difference is > 0 then
2065     * 1 is returned, if the difference is < 0 then -1 is returned, and if the
2066     * difference is 0 then 0 is returned. This means, that if two decimal
2067     * instances are compared which are equal in value but differ in scale, then
2068     * these two instances are considered as equal.
2069     *
2070     * @param val
2071     *            value to be compared with {@code this}.
2072     * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val},
2073     *         {@code 0} if {@code this == val}.
2074     * @throws NullPointerException
2075     *             if {@code val == null}.
2076     */
2077    public int compareTo(BigDecimal val) {
2078        int thisSign = signum();
2079        int valueSign = val.signum();
2080
2081        if( thisSign == valueSign) {
2082            if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) {
2083                return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0;
2084            }
2085            long diffScale = (long)this.scale - val.scale;
2086            int diffPrecision = this.approxPrecision() - val.approxPrecision();
2087            if (diffPrecision > diffScale + 1) {
2088                return thisSign;
2089            } else if (diffPrecision < diffScale - 1) {
2090                return -thisSign;
2091            } else {// thisSign == val.signum()  and  diffPrecision is aprox. diffScale
2092                BigInteger thisUnscaled = this.getUnscaledValue();
2093                BigInteger valUnscaled = val.getUnscaledValue();
2094                // If any of both precision is bigger, append zeros to the shorter one
2095                if (diffScale < 0) {
2096                    thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale));
2097                } else if (diffScale > 0) {
2098                    valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale));
2099                }
2100                return thisUnscaled.compareTo(valUnscaled);
2101            }
2102        } else if (thisSign < valueSign) {
2103            return -1;
2104        } else  {
2105            return 1;
2106        }
2107    }
2108
2109    /**
2110     * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if
2111     * this instance is equal to this big decimal. Two big decimals are equal if
2112     * their unscaled value and their scale is equal. For example, 1.0
2113     * (10*10<sup>-1</sup>) is not equal to 1.00 (100*10<sup>-2</sup>). Similarly, zero
2114     * instances are not equal if their scale differs.
2115     */
2116    @Override
2117    public boolean equals(Object x) {
2118        if (this == x) {
2119            return true;
2120        }
2121        if (x instanceof BigDecimal) {
2122            BigDecimal x1 = (BigDecimal) x;
2123            return x1.scale == scale
2124                   && (bitLength < 64 ? (x1.smallValue == smallValue)
2125                    : intVal.equals(x1.intVal));
2126        }
2127        return false;
2128    }
2129
2130    /**
2131     * Returns the minimum of this {@code BigDecimal} and {@code val}.
2132     *
2133     * @param val
2134     *            value to be used to compute the minimum with this.
2135     * @return {@code min(this, val}.
2136     * @throws NullPointerException
2137     *             if {@code val == null}.
2138     */
2139    public BigDecimal min(BigDecimal val) {
2140        return ((compareTo(val) <= 0) ? this : val);
2141    }
2142
2143    /**
2144     * Returns the maximum of this {@code BigDecimal} and {@code val}.
2145     *
2146     * @param val
2147     *            value to be used to compute the maximum with this.
2148     * @return {@code max(this, val}.
2149     * @throws NullPointerException
2150     *             if {@code val == null}.
2151     */
2152    public BigDecimal max(BigDecimal val) {
2153        return ((compareTo(val) >= 0) ? this : val);
2154    }
2155
2156    /**
2157     * Returns a hash code for this {@code BigDecimal}.
2158     *
2159     * @return hash code for {@code this}.
2160     */
2161    @Override
2162    public int hashCode() {
2163        if (hashCode != 0) {
2164            return hashCode;
2165        }
2166        if (bitLength < 64) {
2167            hashCode = (int)(smallValue & 0xffffffff);
2168            hashCode = 33 * hashCode +  (int)((smallValue >> 32) & 0xffffffff);
2169            hashCode = 17 * hashCode + scale;
2170            return hashCode;
2171        }
2172        hashCode = 17 * intVal.hashCode() + scale;
2173        return hashCode;
2174    }
2175
2176    /**
2177     * Returns a canonical string representation of this {@code BigDecimal}. If
2178     * necessary, scientific notation is used. This representation always prints
2179     * all significant digits of this value.
2180     * <p>
2181     * If the scale is negative or if {@code scale - precision >= 6} then
2182     * scientific notation is used.
2183     *
2184     * @return a string representation of {@code this} in scientific notation if
2185     *         necessary.
2186     */
2187    @Override
2188    public String toString() {
2189        if (toStringImage != null) {
2190            return toStringImage;
2191        }
2192        if(bitLength < 32) {
2193            toStringImage = Conversion.toDecimalScaledString(smallValue,scale);
2194            return toStringImage;
2195        }
2196        String intString = getUnscaledValue().toString();
2197        if (scale == 0) {
2198            return intString;
2199        }
2200        int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
2201        int end = intString.length();
2202        long exponent = -(long)scale + end - begin;
2203        StringBuilder result = new StringBuilder();
2204
2205        result.append(intString);
2206        if ((scale > 0) && (exponent >= -6)) {
2207            if (exponent >= 0) {
2208                result.insert(end - scale, '.');
2209            } else {
2210                result.insert(begin - 1, "0.");
2211                result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
2212            }
2213        } else {
2214            if (end - begin >= 1) {
2215                result.insert(begin, '.');
2216                end++;
2217            }
2218            result.insert(end, 'E');
2219            if (exponent > 0) {
2220                result.insert(++end, '+');
2221            }
2222            result.insert(++end, Long.toString(exponent));
2223        }
2224        toStringImage = result.toString();
2225        return toStringImage;
2226    }
2227
2228    /**
2229     * Returns a string representation of this {@code BigDecimal}. This
2230     * representation always prints all significant digits of this value.
2231     * <p>
2232     * If the scale is negative or if {@code scale - precision >= 6} then
2233     * engineering notation is used. Engineering notation is similar to the
2234     * scientific notation except that the exponent is made to be a multiple of
2235     * 3 such that the integer part is >= 1 and < 1000.
2236     *
2237     * @return a string representation of {@code this} in engineering notation
2238     *         if necessary.
2239     */
2240    public String toEngineeringString() {
2241        String intString = getUnscaledValue().toString();
2242        if (scale == 0) {
2243            return intString;
2244        }
2245        int begin = (getUnscaledValue().signum() < 0) ? 2 : 1;
2246        int end = intString.length();
2247        long exponent = -(long)scale + end - begin;
2248        StringBuilder result = new StringBuilder(intString);
2249
2250        if ((scale > 0) && (exponent >= -6)) {
2251            if (exponent >= 0) {
2252                result.insert(end - scale, '.');
2253            } else {
2254                result.insert(begin - 1, "0.");
2255                result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1);
2256            }
2257        } else {
2258            int delta = end - begin;
2259            int rem = (int)(exponent % 3);
2260
2261            if (rem != 0) {
2262                // adjust exponent so it is a multiple of three
2263                if (getUnscaledValue().signum() == 0) {
2264                    // zero value
2265                    rem = (rem < 0) ? -rem : 3 - rem;
2266                    exponent += rem;
2267                } else {
2268                    // nonzero value
2269                    rem = (rem < 0) ? rem + 3 : rem;
2270                    exponent -= rem;
2271                    begin += rem;
2272                }
2273                if (delta < 3) {
2274                    for (int i = rem - delta; i > 0; i--) {
2275                        result.insert(end++, '0');
2276                    }
2277                }
2278            }
2279            if (end - begin >= 1) {
2280                result.insert(begin, '.');
2281                end++;
2282            }
2283            if (exponent != 0) {
2284                result.insert(end, 'E');
2285                if (exponent > 0) {
2286                    result.insert(++end, '+');
2287                }
2288                result.insert(++end, Long.toString(exponent));
2289            }
2290        }
2291        return result.toString();
2292    }
2293
2294    /**
2295     * Returns a string representation of this {@code BigDecimal}. No scientific
2296     * notation is used. This methods adds zeros where necessary.
2297     * <p>
2298     * If this string representation is used to create a new instance, this
2299     * instance is generally not identical to {@code this} as the precision
2300     * changes.
2301     * <p>
2302     * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns
2303     * {@code false}.
2304     * <p>
2305     * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}.
2306     *
2307     * @return a string representation of {@code this} without exponent part.
2308     */
2309    public String toPlainString() {
2310        String intStr = getUnscaledValue().toString();
2311        if ((scale == 0) || ((isZero()) && (scale < 0))) {
2312            return intStr;
2313        }
2314        int begin = (signum() < 0) ? 1 : 0;
2315        int delta = scale;
2316        // We take space for all digits, plus a possible decimal point, plus 'scale'
2317        StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale));
2318
2319        if (begin == 1) {
2320            // If the number is negative, we insert a '-' character at front
2321            result.append('-');
2322        }
2323        if (scale > 0) {
2324            delta -= (intStr.length() - begin);
2325            if (delta >= 0) {
2326                result.append("0.");
2327                // To append zeros after the decimal point
2328                for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) {
2329                    result.append(CH_ZEROS);
2330                }
2331                result.append(CH_ZEROS, 0, delta);
2332                result.append(intStr.substring(begin));
2333            } else {
2334                delta = begin - delta;
2335                result.append(intStr.substring(begin, delta));
2336                result.append('.');
2337                result.append(intStr.substring(delta));
2338            }
2339        } else {// (scale <= 0)
2340            result.append(intStr.substring(begin));
2341            // To append trailing zeros
2342            for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) {
2343                result.append(CH_ZEROS);
2344            }
2345            result.append(CH_ZEROS, 0, -delta);
2346        }
2347        return result.toString();
2348    }
2349
2350    /**
2351     * Returns this {@code BigDecimal} as a big integer instance. A fractional
2352     * part is discarded.
2353     *
2354     * @return this {@code BigDecimal} as a big integer instance.
2355     */
2356    public BigInteger toBigInteger() {
2357        if ((scale == 0) || (isZero())) {
2358            return getUnscaledValue();
2359        } else if (scale < 0) {
2360            return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
2361        } else {// (scale > 0)
2362            return getUnscaledValue().divide(Multiplication.powerOf10(scale));
2363        }
2364    }
2365
2366    /**
2367     * Returns this {@code BigDecimal} as a big integer instance if it has no
2368     * fractional part. If this {@code BigDecimal} has a fractional part, i.e.
2369     * if rounding would be necessary, an {@code ArithmeticException} is thrown.
2370     *
2371     * @return this {@code BigDecimal} as a big integer value.
2372     * @throws ArithmeticException
2373     *             if rounding is necessary.
2374     */
2375    public BigInteger toBigIntegerExact() {
2376        if ((scale == 0) || (isZero())) {
2377            return getUnscaledValue();
2378        } else if (scale < 0) {
2379            return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale));
2380        } else {// (scale > 0)
2381            BigInteger[] integerAndFraction;
2382            // An optimization before do a heavy division
2383            if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) {
2384                throw new ArithmeticException("Rounding necessary");
2385            }
2386            integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale));
2387            if (integerAndFraction[1].signum() != 0) {
2388                // It exists a non-zero fractional part
2389                throw new ArithmeticException("Rounding necessary");
2390            }
2391            return integerAndFraction[0];
2392        }
2393    }
2394
2395    /**
2396     * Returns this {@code BigDecimal} as an long value. Any fractional part is
2397     * discarded. If the integral part of {@code this} is too big to be
2398     * represented as an long, then {@code this % 2<sup>64</sup>} is returned.
2399     */
2400    @Override
2401    public long longValue() {
2402        /*
2403         * If scale <= -64 there are at least 64 trailing bits zero in
2404         * 10^(-scale). If the scale is positive and very large the long value
2405         * could be zero.
2406         */
2407        return ((scale <= -64) || (scale > approxPrecision()) ? 0L : toBigInteger().longValue());
2408    }
2409
2410    /**
2411     * Returns this {@code BigDecimal} as a long value if it has no fractional
2412     * part and if its value fits to the int range ([-2<sup>63</sup>..2<sup>63</sup>-1]). If
2413     * these conditions are not met, an {@code ArithmeticException} is thrown.
2414     *
2415     * @throws ArithmeticException
2416     *             if rounding is necessary or the number doesn't fit in a long.
2417     */
2418    public long longValueExact() {
2419        return valueExact(64);
2420    }
2421
2422    /**
2423     * Returns this {@code BigDecimal} as an int value. Any fractional part is
2424     * discarded. If the integral part of {@code this} is too big to be
2425     * represented as an int, then {@code this % 2<sup>32</sup>} is returned.
2426     */
2427    @Override
2428    public int intValue() {
2429        /*
2430         * If scale <= -32 there are at least 32 trailing bits zero in
2431         * 10^(-scale). If the scale is positive and very large the long value
2432         * could be zero.
2433         */
2434        return ((scale <= -32) || (scale > approxPrecision()) ? 0 : toBigInteger().intValue());
2435    }
2436
2437    /**
2438     * Returns this {@code BigDecimal} as a int value if it has no fractional
2439     * part and if its value fits to the int range ([-2<sup>31</sup>..2<sup>31</sup>-1]). If
2440     * these conditions are not met, an {@code ArithmeticException} is thrown.
2441     *
2442     * @throws ArithmeticException
2443     *             if rounding is necessary or the number doesn't fit in an int.
2444     */
2445    public int intValueExact() {
2446        return (int) valueExact(32);
2447    }
2448
2449    /**
2450     * Returns this {@code BigDecimal} as a short value if it has no fractional
2451     * part and if its value fits to the short range ([-2<sup>15</sup>..2<sup>15</sup>-1]). If
2452     * these conditions are not met, an {@code ArithmeticException} is thrown.
2453     *
2454     * @throws ArithmeticException
2455     *             if rounding is necessary of the number doesn't fit in a short.
2456     */
2457    public short shortValueExact() {
2458        return (short) valueExact(16);
2459    }
2460
2461    /**
2462     * Returns this {@code BigDecimal} as a byte value if it has no fractional
2463     * part and if its value fits to the byte range ([-128..127]). If these
2464     * conditions are not met, an {@code ArithmeticException} is thrown.
2465     *
2466     * @throws ArithmeticException
2467     *             if rounding is necessary or the number doesn't fit in a byte.
2468     */
2469    public byte byteValueExact() {
2470        return (byte) valueExact(8);
2471    }
2472
2473    /**
2474     * Returns this {@code BigDecimal} as a float value. If {@code this} is too
2475     * big to be represented as an float, then {@code Float.POSITIVE_INFINITY}
2476     * or {@code Float.NEGATIVE_INFINITY} is returned.
2477     * <p>
2478     * Note, that if the unscaled value has more than 24 significant digits,
2479     * then this decimal cannot be represented exactly in a float variable. In
2480     * this case the result is rounded.
2481     * <p>
2482     * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
2483     * represented exactly as a float, and thus {@code x1.equals(new
2484     * BigDecimal(x1.floatValue())} returns {@code false} for this case.
2485     * <p>
2486     * Similarly, if the instance {@code new BigDecimal(16777217)} is converted
2487     * to a float, the result is {@code 1.6777216E}7.
2488     *
2489     * @return this {@code BigDecimal} as a float value.
2490     */
2491    @Override
2492    public float floatValue() {
2493        /* A similar code like in doubleValue() could be repeated here,
2494         * but this simple implementation is quite efficient. */
2495        float floatResult = signum();
2496        long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
2497        if ((powerOfTwo < -149) || (floatResult == 0.0f)) {
2498            // Cases which 'this' is very small
2499            floatResult *= 0.0f;
2500        } else if (powerOfTwo > 129) {
2501            // Cases which 'this' is very large
2502            floatResult *= Float.POSITIVE_INFINITY;
2503        } else {
2504            floatResult = (float)doubleValue();
2505        }
2506        return floatResult;
2507    }
2508
2509    /**
2510     * Returns this {@code BigDecimal} as a double value. If {@code this} is too
2511     * big to be represented as an float, then {@code Double.POSITIVE_INFINITY}
2512     * or {@code Double.NEGATIVE_INFINITY} is returned.
2513     * <p>
2514     * Note, that if the unscaled value has more than 53 significant digits,
2515     * then this decimal cannot be represented exactly in a double variable. In
2516     * this case the result is rounded.
2517     * <p>
2518     * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be
2519     * represented exactly as a double, and thus {@code x1.equals(new
2520     * BigDecimal(x1.doubleValue())} returns {@code false} for this case.
2521     * <p>
2522     * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is
2523     * converted to a double, the result is {@code 9.007199254740992E15}.
2524     * <p>
2525     *
2526     * @return this {@code BigDecimal} as a double value.
2527     */
2528    @Override
2529    public double doubleValue() {
2530        int sign = signum();
2531        int exponent = 1076; // bias + 53
2532        int lowestSetBit;
2533        int discardedSize;
2534        long powerOfTwo = this.bitLength - (long)(scale / LOG10_2);
2535        long bits; // IEEE-754 Standard
2536        long tempBits; // for temporal calculations
2537        BigInteger mantissa;
2538
2539        if ((powerOfTwo < -1074) || (sign == 0)) {
2540            // Cases which 'this' is very small
2541            return (sign * 0.0d);
2542        } else if (powerOfTwo > 1025) {
2543            // Cases which 'this' is very large
2544            return (sign * Double.POSITIVE_INFINITY);
2545        }
2546        mantissa = getUnscaledValue().abs();
2547        // Let be:  this = [u,s], with s > 0
2548        if (scale <= 0) {
2549            // mantissa = abs(u) * 10^s
2550            mantissa = mantissa.multiply(Multiplication.powerOf10(-scale));
2551        } else {// (scale > 0)
2552            BigInteger quotAndRem[];
2553            BigInteger powerOfTen = Multiplication.powerOf10(scale);
2554            int k = 100 - (int)powerOfTwo;
2555            int compRem;
2556
2557            if (k > 0) {
2558                /* Computing (mantissa * 2^k) , where 'k' is a enough big
2559                 * power of '2' to can divide by 10^s */
2560                mantissa = mantissa.shiftLeft(k);
2561                exponent -= k;
2562            }
2563            // Computing (mantissa * 2^k) / 10^s
2564            quotAndRem = mantissa.divideAndRemainder(powerOfTen);
2565            // To check if the fractional part >= 0.5
2566            compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen);
2567            // To add two rounded bits at end of mantissa
2568            mantissa = quotAndRem[0].shiftLeft(2).add(
2569                    BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1));
2570            exponent -= 2;
2571        }
2572        lowestSetBit = mantissa.getLowestSetBit();
2573        discardedSize = mantissa.bitLength() - 54;
2574        if (discardedSize > 0) {// (n > 54)
2575            // mantissa = (abs(u) * 10^s) >> (n - 54)
2576            bits = mantissa.shiftRight(discardedSize).longValue();
2577            tempBits = bits;
2578            // #bits = 54, to check if the discarded fraction produces a carry
2579            if ((((bits & 1) == 1) && (lowestSetBit < discardedSize))
2580                    || ((bits & 3) == 3)) {
2581                bits += 2;
2582            }
2583        } else {// (n <= 54)
2584            // mantissa = (abs(u) * 10^s) << (54 - n)
2585            bits = mantissa.longValue() << -discardedSize;
2586            tempBits = bits;
2587            // #bits = 54, to check if the discarded fraction produces a carry:
2588            if ((bits & 3) == 3) {
2589                bits += 2;
2590            }
2591        }
2592        // Testing bit 54 to check if the carry creates a new binary digit
2593        if ((bits & 0x40000000000000L) == 0) {
2594            // To drop the last bit of mantissa (first discarded)
2595            bits >>= 1;
2596            // exponent = 2^(s-n+53+bias)
2597            exponent += discardedSize;
2598        } else {// #bits = 54
2599            bits >>= 2;
2600            exponent += discardedSize + 1;
2601        }
2602        // To test if the 53-bits number fits in 'double'
2603        if (exponent > 2046) {// (exponent - bias > 1023)
2604            return (sign * Double.POSITIVE_INFINITY);
2605        } else if (exponent <= 0) {// (exponent - bias <= -1023)
2606            // Denormalized numbers (having exponent == 0)
2607            if (exponent < -53) {// exponent - bias < -1076
2608                return (sign * 0.0d);
2609            }
2610            // -1076 <= exponent - bias <= -1023
2611            // To discard '- exponent + 1' bits
2612            bits = tempBits >> 1;
2613            tempBits = bits & (-1L >>> (63 + exponent));
2614            bits >>= (-exponent );
2615            // To test if after discard bits, a new carry is generated
2616            if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0)
2617            && (lowestSetBit < discardedSize))) {
2618                bits += 1;
2619            }
2620            exponent = 0;
2621            bits >>= 1;
2622        }
2623        // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)]
2624        bits = (sign & 0x8000000000000000L) | ((long)exponent << 52)
2625                | (bits & 0xFFFFFFFFFFFFFL);
2626        return Double.longBitsToDouble(bits);
2627    }
2628
2629    /**
2630     * Returns the unit in the last place (ULP) of this {@code BigDecimal}
2631     * instance. An ULP is the distance to the nearest big decimal with the same
2632     * precision.
2633     *
2634     * <p>The amount of a rounding error in the evaluation of a floating-point
2635     * operation is often expressed in ULPs. An error of 1 ULP is often seen as
2636     * a tolerable error.
2637     *
2638     * <p>For class {@code BigDecimal}, the ULP of a number is simply 10<sup>-scale</sup>.
2639     * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}.
2640     *
2641     * @return unit in the last place (ULP) of this {@code BigDecimal} instance.
2642     */
2643    public BigDecimal ulp() {
2644        return valueOf(1, scale);
2645    }
2646
2647    /* Private Methods */
2648
2649    /**
2650     * It does all rounding work of the public method
2651     * {@code round(MathContext)}, performing an inplace rounding
2652     * without creating a new object.
2653     *
2654     * @param mc
2655     *            the {@code MathContext} for perform the rounding.
2656     * @see #round(MathContext)
2657     */
2658    private void inplaceRound(MathContext mc) {
2659        int mcPrecision = mc.getPrecision();
2660        if (approxPrecision() < mcPrecision || mcPrecision == 0) {
2661            return;
2662        }
2663        int discardedPrecision = precision() - mcPrecision;
2664        // If no rounding is necessary it returns immediately
2665        if ((discardedPrecision <= 0)) {
2666            return;
2667        }
2668        // When the number is small perform an efficient rounding
2669        if (this.bitLength < 64) {
2670            smallRound(mc, discardedPrecision);
2671            return;
2672        }
2673        // Getting the integer part and the discarded fraction
2674        BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision);
2675        BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction);
2676        long newScale = (long)scale - discardedPrecision;
2677        int compRem;
2678        BigDecimal tempBD;
2679        // If the discarded fraction is non-zero, perform rounding
2680        if (integerAndFraction[1].signum() != 0) {
2681            // To check if the discarded fraction >= 0.5
2682            compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction));
2683            // To look if there is a carry
2684            compRem =  roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0,
2685                    integerAndFraction[1].signum() * (5 + compRem),
2686                    mc.getRoundingMode());
2687            if (compRem != 0) {
2688                integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem));
2689            }
2690            tempBD = new BigDecimal(integerAndFraction[0]);
2691            // If after to add the increment the precision changed, we normalize the size
2692            if (tempBD.precision() > mcPrecision) {
2693                integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN);
2694                newScale--;
2695            }
2696        }
2697        // To update all internal fields
2698        scale = safeLongToInt(newScale);
2699        precision = mcPrecision;
2700        setUnscaledValue(integerAndFraction[0]);
2701    }
2702
2703    private static int longCompareTo(long value1, long value2) {
2704        return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0);
2705    }
2706    /**
2707     * This method implements an efficient rounding for numbers which unscaled
2708     * value fits in the type {@code long}.
2709     *
2710     * @param mc
2711     *            the context to use
2712     * @param discardedPrecision
2713     *            the number of decimal digits that are discarded
2714     * @see #round(MathContext)
2715     */
2716    private void smallRound(MathContext mc, int discardedPrecision) {
2717        long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision];
2718        long newScale = (long)scale - discardedPrecision;
2719        long unscaledVal = smallValue;
2720        // Getting the integer part and the discarded fraction
2721        long integer = unscaledVal / sizeOfFraction;
2722        long fraction = unscaledVal % sizeOfFraction;
2723        int compRem;
2724        // If the discarded fraction is non-zero perform rounding
2725        if (fraction != 0) {
2726            // To check if the discarded fraction >= 0.5
2727            compRem = longCompareTo(Math.abs(fraction) * 2, sizeOfFraction);
2728            // To look if there is a carry
2729            integer += roundingBehavior( ((int)integer) & 1,
2730                    Long.signum(fraction) * (5 + compRem),
2731                    mc.getRoundingMode());
2732            // If after to add the increment the precision changed, we normalize the size
2733            if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) {
2734                integer /= 10;
2735                newScale--;
2736            }
2737        }
2738        // To update all internal fields
2739        scale = safeLongToInt(newScale);
2740        precision = mc.getPrecision();
2741        smallValue = integer;
2742        bitLength = bitLength(integer);
2743        intVal = null;
2744    }
2745
2746    /**
2747     * Return an increment that can be -1,0 or 1, depending of
2748     * {@code roundingMode}.
2749     *
2750     * @param parityBit
2751     *            can be 0 or 1, it's only used in the case
2752     *            {@code HALF_EVEN}
2753     * @param fraction
2754     *            the mantissa to be analyzed
2755     * @param roundingMode
2756     *            the type of rounding
2757     * @return the carry propagated after rounding
2758     */
2759    private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) {
2760        int increment = 0; // the carry after rounding
2761
2762        switch (roundingMode) {
2763            case UNNECESSARY:
2764                if (fraction != 0) {
2765                    throw new ArithmeticException("Rounding necessary");
2766                }
2767                break;
2768            case UP:
2769                increment = Integer.signum(fraction);
2770                break;
2771            case DOWN:
2772                break;
2773            case CEILING:
2774                increment = Math.max(Integer.signum(fraction), 0);
2775                break;
2776            case FLOOR:
2777                increment = Math.min(Integer.signum(fraction), 0);
2778                break;
2779            case HALF_UP:
2780                if (Math.abs(fraction) >= 5) {
2781                    increment = Integer.signum(fraction);
2782                }
2783                break;
2784            case HALF_DOWN:
2785                if (Math.abs(fraction) > 5) {
2786                    increment = Integer.signum(fraction);
2787                }
2788                break;
2789            case HALF_EVEN:
2790                if (Math.abs(fraction) + parityBit > 5) {
2791                    increment = Integer.signum(fraction);
2792                }
2793                break;
2794        }
2795        return increment;
2796    }
2797
2798    /**
2799     * If {@code intVal} has a fractional part throws an exception,
2800     * otherwise it counts the number of bits of value and checks if it's out of
2801     * the range of the primitive type. If the number fits in the primitive type
2802     * returns this number as {@code long}, otherwise throws an
2803     * exception.
2804     *
2805     * @param bitLengthOfType
2806     *            number of bits of the type whose value will be calculated
2807     *            exactly
2808     * @return the exact value of the integer part of {@code BigDecimal}
2809     *         when is possible
2810     * @throws ArithmeticException when rounding is necessary or the
2811     *             number don't fit in the primitive type
2812     */
2813    private long valueExact(int bitLengthOfType) {
2814        BigInteger bigInteger = toBigIntegerExact();
2815
2816        if (bigInteger.bitLength() < bitLengthOfType) {
2817            // It fits in the primitive type
2818            return bigInteger.longValue();
2819        }
2820        throw new ArithmeticException("Rounding necessary");
2821    }
2822
2823    /**
2824     * If the precision already was calculated it returns that value, otherwise
2825     * it calculates a very good approximation efficiently . Note that this
2826     * value will be {@code precision()} or {@code precision()-1}
2827     * in the worst case.
2828     *
2829     * @return an approximation of {@code precision()} value
2830     */
2831    private int approxPrecision() {
2832        return precision > 0
2833                ? precision
2834                : (int) ((this.bitLength - 1) * LOG10_2) + 1;
2835    }
2836
2837    private static int safeLongToInt(long longValue) {
2838        if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) {
2839            throw new ArithmeticException("Out of int range: " + longValue);
2840        }
2841        return (int) longValue;
2842    }
2843
2844    /**
2845     * It returns the value 0 with the most approximated scale of type
2846     * {@code int}. if {@code longScale > Integer.MAX_VALUE} the
2847     * scale will be {@code Integer.MAX_VALUE}; if
2848     * {@code longScale < Integer.MIN_VALUE} the scale will be
2849     * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is
2850     * casted to the type {@code int}.
2851     *
2852     * @param longScale
2853     *            the scale to which the value 0 will be scaled.
2854     * @return the value 0 scaled by the closer scale of type {@code int}.
2855     * @see #scale
2856     */
2857    private static BigDecimal zeroScaledBy(long longScale) {
2858        if (longScale == (int) longScale) {
2859            return valueOf(0,(int)longScale);
2860            }
2861        if (longScale >= 0) {
2862            return new BigDecimal( 0, Integer.MAX_VALUE);
2863        }
2864        return new BigDecimal( 0, Integer.MIN_VALUE);
2865    }
2866
2867    /**
2868     * Assigns all transient fields upon deserialization of a
2869     * {@code BigDecimal} instance (bitLength and smallValue). The transient
2870     * field precision is assigned lazily.
2871     */
2872    private void readObject(ObjectInputStream in) throws IOException,
2873            ClassNotFoundException {
2874        in.defaultReadObject();
2875
2876        this.bitLength = intVal.bitLength();
2877        if (this.bitLength < 64) {
2878            this.smallValue = intVal.longValue();
2879        }
2880    }
2881
2882    /**
2883     * Prepares this {@code BigDecimal} for serialization, i.e. the
2884     * non-transient field {@code intVal} is assigned.
2885     */
2886    private void writeObject(ObjectOutputStream out) throws IOException {
2887        getUnscaledValue();
2888        out.defaultWriteObject();
2889    }
2890
2891    private BigInteger getUnscaledValue() {
2892        if(intVal == null) {
2893            intVal = BigInteger.valueOf(smallValue);
2894        }
2895        return intVal;
2896    }
2897
2898    private void setUnscaledValue(BigInteger unscaledValue) {
2899        this.intVal = unscaledValue;
2900        this.bitLength = unscaledValue.bitLength();
2901        if(this.bitLength < 64) {
2902            this.smallValue = unscaledValue.longValue();
2903        }
2904    }
2905
2906    private static int bitLength(long smallValue) {
2907        if(smallValue < 0) {
2908            smallValue = ~smallValue;
2909        }
2910        return 64 - Long.numberOfLeadingZeros(smallValue);
2911    }
2912
2913    private static int bitLength(int smallValue) {
2914        if(smallValue < 0) {
2915            smallValue = ~smallValue;
2916        }
2917        return 32 - Integer.numberOfLeadingZeros(smallValue);
2918    }
2919
2920}
2921