2 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
27 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
32 import java.util.Arrays;
33 import static java.math.BigInteger.LONG_MASK;
36 * Immutable, arbitrary-precision signed decimal numbers. A
37 * {@code BigDecimal} consists of an arbitrary precision integer
38 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
39 * or positive, the scale is the number of digits to the right of the
40 * decimal point. If negative, the unscaled value of the number is
41 * multiplied by ten to the power of the negation of the scale. The
42 * value of the number represented by the {@code BigDecimal} is
43 * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
45 * <p>The {@code BigDecimal} class provides operations for
46 * arithmetic, scale manipulation, rounding, comparison, hashing, and
47 * format conversion. The {@link #toString} method provides a
48 * canonical representation of a {@code BigDecimal}.
50 * <p>The {@code BigDecimal} class gives its user complete control
51 * over rounding behavior. If no rounding mode is specified and the
52 * exact result cannot be represented, an exception is thrown;
53 * otherwise, calculations can be carried out to a chosen precision
54 * and rounding mode by supplying an appropriate {@link MathContext}
55 * object to the operation. In either case, eight <em>rounding
56 * modes</em> are provided for the control of rounding. Using the
57 * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
58 * represent rounding mode is largely obsolete; the enumeration values
59 * of the {@code RoundingMode} {@code enum}, (such as {@link
60 * RoundingMode#HALF_UP}) should be used instead.
62 * <p>When a {@code MathContext} object is supplied with a precision
63 * setting of 0 (for example, {@link MathContext#UNLIMITED}),
64 * arithmetic operations are exact, as are the arithmetic methods
65 * which take no {@code MathContext} object. (This is the only
66 * behavior that was supported in releases prior to 5.) As a
67 * corollary of computing the exact result, the rounding mode setting
68 * of a {@code MathContext} object with a precision setting of 0 is
69 * not used and thus irrelevant. In the case of divide, the exact
70 * quotient could have an infinitely long decimal expansion; for
71 * example, 1 divided by 3. If the quotient has a nonterminating
72 * decimal expansion and the operation is specified to return an exact
73 * result, an {@code ArithmeticException} is thrown. Otherwise, the
74 * exact result of the division is returned, as done for other
77 * <p>When the precision setting is not 0, the rules of
78 * {@code BigDecimal} arithmetic are broadly compatible with selected
79 * modes of operation of the arithmetic defined in ANSI X3.274-1996
80 * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
81 * standards, {@code BigDecimal} includes many rounding modes, which
82 * were mandatory for division in {@code BigDecimal} releases prior
83 * to 5. Any conflicts between these ANSI standards and the
84 * {@code BigDecimal} specification are resolved in favor of
87 * <p>Since the same numerical value can have different
88 * representations (with different scales), the rules of arithmetic
89 * and rounding must specify both the numerical result and the scale
90 * used in the result's representation.
93 * <p>In general the rounding modes and precision setting determine
94 * how operations return results with a limited number of digits when
95 * the exact result has more digits (perhaps infinitely many in the
96 * case of division) than the number of digits returned.
99 * total number of digits to return is specified by the
100 * {@code MathContext}'s {@code precision} setting; this determines
101 * the result's <i>precision</i>. The digit count starts from the
102 * leftmost nonzero digit of the exact result. The rounding mode
103 * determines how any discarded trailing digits affect the returned
106 * <p>For all arithmetic operators , the operation is carried out as
107 * though an exact intermediate result were first calculated and then
108 * rounded to the number of digits specified by the precision setting
109 * (if necessary), using the selected rounding mode. If the exact
110 * result is not returned, some digit positions of the exact result
111 * are discarded. When rounding increases the magnitude of the
112 * returned result, it is possible for a new digit position to be
113 * created by a carry propagating to a leading {@literal "9"} digit.
114 * For example, rounding the value 999.9 to three digits rounding up
115 * would be numerically equal to one thousand, represented as
116 * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
117 * the leading digit position of the returned result.
119 * <p>Besides a logical exact result, each arithmetic operation has a
120 * preferred scale for representing a result. The preferred
121 * scale for each operation is listed in the table below.
124 * <caption><b>Preferred Scales for Results of Arithmetic Operations
126 * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr>
127 * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td>
128 * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td>
129 * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td>
130 * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td>
133 * These scales are the ones used by the methods which return exact
134 * arithmetic results; except that an exact divide may have to use a
135 * larger scale since the exact result may have more digits. For
136 * example, {@code 1/32} is {@code 0.03125}.
138 * <p>Before rounding, the scale of the logical exact intermediate
139 * result is the preferred scale for that operation. If the exact
140 * numerical result cannot be represented in {@code precision}
141 * digits, rounding selects the set of digits to return and the scale
142 * of the result is reduced from the scale of the intermediate result
143 * to the least scale which can represent the {@code precision}
144 * digits actually returned. If the exact result can be represented
145 * with at most {@code precision} digits, the representation
146 * of the result with the scale closest to the preferred scale is
147 * returned. In particular, an exactly representable quotient may be
148 * represented in fewer than {@code precision} digits by removing
149 * trailing zeros and decreasing the scale. For example, rounding to
150 * three digits using the {@linkplain RoundingMode#FLOOR floor}
151 * rounding mode, <br>
153 * {@code 19/100 = 0.19 // integer=19, scale=2} <br>
157 * {@code 21/110 = 0.190 // integer=190, scale=3} <br>
159 * <p>Note that for add, subtract, and multiply, the reduction in
160 * scale will equal the number of digit positions of the exact result
161 * which are discarded. If the rounding causes a carry propagation to
162 * create a new high-order digit position, an additional digit of the
163 * result is discarded than when no new digit position is created.
165 * <p>Other methods may have slightly different rounding semantics.
166 * For example, the result of the {@code pow} method using the
167 * {@linkplain #pow(int, MathContext) specified algorithm} can
168 * occasionally differ from the rounded mathematical result by more
169 * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>.
171 * <p>Two types of operations are provided for manipulating the scale
172 * of a {@code BigDecimal}: scaling/rounding operations and decimal
173 * point motion operations. Scaling/rounding operations ({@link
174 * #setScale setScale} and {@link #round round}) return a
175 * {@code BigDecimal} whose value is approximately (or exactly) equal
176 * to that of the operand, but whose scale or precision is the
177 * specified value; that is, they increase or decrease the precision
178 * of the stored number with minimal effect on its value. Decimal
179 * point motion operations ({@link #movePointLeft movePointLeft} and
180 * {@link #movePointRight movePointRight}) return a
181 * {@code BigDecimal} created from the operand by moving the decimal
182 * point a specified distance in the specified direction.
184 * <p>For the sake of brevity and clarity, pseudo-code is used
185 * throughout the descriptions of {@code BigDecimal} methods. The
186 * pseudo-code expression {@code (i + j)} is shorthand for "a
187 * {@code BigDecimal} whose value is that of the {@code BigDecimal}
188 * {@code i} added to that of the {@code BigDecimal}
189 * {@code j}." The pseudo-code expression {@code (i == j)} is
190 * shorthand for "{@code true} if and only if the
191 * {@code BigDecimal} {@code i} represents the same value as the
192 * {@code BigDecimal} {@code j}." Other pseudo-code expressions
193 * are interpreted similarly. Square brackets are used to represent
194 * the particular {@code BigInteger} and scale pair defining a
195 * {@code BigDecimal} value; for example [19, 2] is the
196 * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
198 * <p>Note: care should be exercised if {@code BigDecimal} objects
199 * are used as keys in a {@link java.util.SortedMap SortedMap} or
200 * elements in a {@link java.util.SortedSet SortedSet} since
201 * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
202 * with equals</i>. See {@link Comparable}, {@link
203 * java.util.SortedMap} or {@link java.util.SortedSet} for more
206 * <p>All methods and constructors for this class throw
207 * {@code NullPointerException} when passed a {@code null} object
208 * reference for any input parameter.
213 * @see java.util.SortedMap
214 * @see java.util.SortedSet
216 * @author Mike Cowlishaw
217 * @author Joseph D. Darcy
219 public class BigDecimal extends Number implements Comparable<BigDecimal> {
221 * The unscaled value of this BigDecimal, as returned by {@link
225 * @see #unscaledValue
227 private volatile BigInteger intVal;
230 * The scale of this BigDecimal, as returned by {@link #scale}.
235 private int scale; // Note: this may have any value, so
236 // calculations must be done in longs
238 * The number of decimal digits in this BigDecimal, or 0 if the
239 * number of digits are not known (lookaside information). If
240 * nonzero, the value is guaranteed correct. Use the precision()
241 * method to obtain and set the value if it might be 0. This
242 * field is mutable until set nonzero.
246 private transient int precision;
249 * Used to store the canonical string representation, if computed.
251 private transient String stringCache;
254 * Sentinel value for {@link #intCompact} indicating the
255 * significand information is only available from {@code intVal}.
257 static final long INFLATED = Long.MIN_VALUE;
260 * If the absolute value of the significand of this BigDecimal is
261 * less than or equal to {@code Long.MAX_VALUE}, the value can be
262 * compactly stored in this field and used in computations.
264 private transient long intCompact;
266 // All 18-digit base ten strings fit into a long; not all 19-digit
268 private static final int MAX_COMPACT_DIGITS = 18;
270 private static final int MAX_BIGINT_BITS = 62;
272 /* Appease the serialization gods */
273 private static final long serialVersionUID = 6108874887143696463L;
275 // Cache of common small BigDecimal values.
276 private static final BigDecimal zeroThroughTen[] = {
277 new BigDecimal(BigInteger.ZERO, 0, 0, 1),
278 new BigDecimal(BigInteger.ONE, 1, 0, 1),
279 new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),
280 new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
281 new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
282 new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
283 new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
284 new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
285 new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
286 new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
287 new BigDecimal(BigInteger.TEN, 10, 0, 2),
290 // Cache of zero scaled by 0 - 15
291 private static final BigDecimal[] ZERO_SCALED_BY = {
293 new BigDecimal(BigInteger.ZERO, 0, 1, 1),
294 new BigDecimal(BigInteger.ZERO, 0, 2, 1),
295 new BigDecimal(BigInteger.ZERO, 0, 3, 1),
296 new BigDecimal(BigInteger.ZERO, 0, 4, 1),
297 new BigDecimal(BigInteger.ZERO, 0, 5, 1),
298 new BigDecimal(BigInteger.ZERO, 0, 6, 1),
299 new BigDecimal(BigInteger.ZERO, 0, 7, 1),
300 new BigDecimal(BigInteger.ZERO, 0, 8, 1),
301 new BigDecimal(BigInteger.ZERO, 0, 9, 1),
302 new BigDecimal(BigInteger.ZERO, 0, 10, 1),
303 new BigDecimal(BigInteger.ZERO, 0, 11, 1),
304 new BigDecimal(BigInteger.ZERO, 0, 12, 1),
305 new BigDecimal(BigInteger.ZERO, 0, 13, 1),
306 new BigDecimal(BigInteger.ZERO, 0, 14, 1),
307 new BigDecimal(BigInteger.ZERO, 0, 15, 1),
310 // Half of Long.MIN_VALUE & Long.MAX_VALUE.
311 private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
312 private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
316 * The value 0, with a scale of 0.
320 public static final BigDecimal ZERO =
324 * The value 1, with a scale of 0.
328 public static final BigDecimal ONE =
332 * The value 10, with a scale of 0.
336 public static final BigDecimal TEN =
342 * Trusted package private constructor.
343 * Trusted simply means if val is INFLATED, intVal could not be null and
344 * if intVal is null, val could not be INFLATED.
346 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
348 this.precision = prec;
349 this.intCompact = val;
350 this.intVal = intVal;
354 * Translates a character array representation of a
355 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
356 * same sequence of characters as the {@link #BigDecimal(String)}
357 * constructor, while allowing a sub-array to be specified.
359 * <p>Note that if the sequence of characters is already available
360 * within a character array, using this constructor is faster than
361 * converting the {@code char} array to string and using the
362 * {@code BigDecimal(String)} constructor .
364 * @param in {@code char} array that is the source of characters.
365 * @param offset first character in the array to inspect.
366 * @param len number of characters to consider.
367 * @throws NumberFormatException if {@code in} is not a valid
368 * representation of a {@code BigDecimal} or the defined subarray
369 * is not wholly within {@code in}.
372 public BigDecimal(char[] in, int offset, int len) {
373 // protect against huge length.
374 if (offset+len > in.length || offset < 0)
375 throw new NumberFormatException();
376 // This is the primary string to BigDecimal constructor; all
377 // incoming strings end up here; it uses explicit (inline)
378 // parsing for speed and generates at most one intermediate
379 // (temporary) object (a char[] array) for non-compact case.
381 // Use locals for all fields values until completion
382 int prec = 0; // record precision value
383 int scl = 0; // record scale value
384 long rs = 0; // the compact value in long
385 BigInteger rb = null; // the inflated value in BigInteger
387 // use array bounds checking to handle too-long, len == 0,
391 boolean isneg = false; // assume positive
392 if (in[offset] == '-') {
393 isneg = true; // leading minus means negative
396 } else if (in[offset] == '+') { // leading + allowed
401 // should now be at numeric part of the significand
402 boolean dot = false; // true when there is a '.'
403 int cfirst = offset; // record start of integer
404 long exp = 0; // exponent
405 char c; // current character
407 boolean isCompact = (len <= MAX_COMPACT_DIGITS);
408 // integer significand array & idx is the index to it. The array
409 // is ONLY used when we can't use a compact representation.
410 char coeff[] = isCompact ? null : new char[len];
413 for (; len > 0; offset++, len--) {
416 if ((c >= '0' && c <= '9') || Character.isDigit(c)) {
417 // First compact case, we need not to preserve the character
418 // and we can just compute the value in place.
420 int digit = Character.digit(c, 10);
427 } // else digit is a redundant leading zero
429 if (prec != 1 || rs != 0)
430 ++prec; // prec unchanged if preceded by 0s
431 rs = rs * 10 + digit;
433 } else { // the unscaled value is likely a BigInteger object.
434 if (c == '0' || Character.digit(c, 10) == 0) {
438 } else if (idx != 0) {
441 } // else c must be a redundant leading zero
443 if (prec != 1 || idx != 0)
444 ++prec; // prec unchanged if preceded by 0s
456 throw new NumberFormatException();
461 if ((c != 'e') && (c != 'E'))
462 throw new NumberFormatException();
466 boolean negexp = (c == '-');
468 if (negexp || c == '+') {
473 if (len <= 0) // no exponent digits
474 throw new NumberFormatException();
475 // skip leading zeros in the exponent
476 while (len > 10 && Character.digit(c, 10) == 0) {
481 if (len > 10) // too many nonzero exponent digits
482 throw new NumberFormatException();
483 // c now holds first digit of exponent
486 if (c >= '0' && c <= '9') {
489 v = Character.digit(c, 10);
490 if (v < 0) // not a digit
491 throw new NumberFormatException();
495 break; // that was final character
499 if (negexp) // apply sign
501 // Next test is required for backwards compatibility
502 if ((int)exp != exp) // overflow
503 throw new NumberFormatException();
504 break; // [saves a test]
506 // here when no characters left
507 if (prec == 0) // no digits found
508 throw new NumberFormatException();
510 // Adjust scale if exp is not zero.
511 if (exp != 0) { // had significant exponent
512 // Can't call checkScale which relies on proper fields value
513 long adjustedScale = scl - exp;
514 if (adjustedScale > Integer.MAX_VALUE ||
515 adjustedScale < Integer.MIN_VALUE)
516 throw new NumberFormatException("Scale out of range.");
517 scl = (int)adjustedScale;
520 // Remove leading zeros from precision (digits count)
522 rs = isneg ? -rs : rs;
526 quick = (coeff.length != prec) ?
527 Arrays.copyOf(coeff, prec) : coeff;
529 quick = new char[prec + 1];
531 System.arraycopy(coeff, 0, quick, 1, prec);
533 rb = new BigInteger(quick);
534 rs = compactValFor(rb);
536 } catch (ArrayIndexOutOfBoundsException e) {
537 throw new NumberFormatException();
538 } catch (NegativeArraySizeException e) {
539 throw new NumberFormatException();
542 this.precision = prec;
543 this.intCompact = rs;
544 this.intVal = (rs != INFLATED) ? null : rb;
548 * Translates a character array representation of a
549 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
550 * same sequence of characters as the {@link #BigDecimal(String)}
551 * constructor, while allowing a sub-array to be specified and
552 * with rounding according to the context settings.
554 * <p>Note that if the sequence of characters is already available
555 * within a character array, using this constructor is faster than
556 * converting the {@code char} array to string and using the
557 * {@code BigDecimal(String)} constructor .
559 * @param in {@code char} array that is the source of characters.
560 * @param offset first character in the array to inspect.
561 * @param len number of characters to consider..
562 * @param mc the context to use.
563 * @throws ArithmeticException if the result is inexact but the
564 * rounding mode is {@code UNNECESSARY}.
565 * @throws NumberFormatException if {@code in} is not a valid
566 * representation of a {@code BigDecimal} or the defined subarray
567 * is not wholly within {@code in}.
570 public BigDecimal(char[] in, int offset, int len, MathContext mc) {
571 this(in, offset, len);
572 if (mc.precision > 0)
577 * Translates a character array representation of a
578 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
579 * same sequence of characters as the {@link #BigDecimal(String)}
582 * <p>Note that if the sequence of characters is already available
583 * as a character array, using this constructor is faster than
584 * converting the {@code char} array to string and using the
585 * {@code BigDecimal(String)} constructor .
587 * @param in {@code char} array that is the source of characters.
588 * @throws NumberFormatException if {@code in} is not a valid
589 * representation of a {@code BigDecimal}.
592 public BigDecimal(char[] in) {
593 this(in, 0, in.length);
597 * Translates a character array representation of a
598 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
599 * same sequence of characters as the {@link #BigDecimal(String)}
600 * constructor and with rounding according to the context
603 * <p>Note that if the sequence of characters is already available
604 * as a character array, using this constructor is faster than
605 * converting the {@code char} array to string and using the
606 * {@code BigDecimal(String)} constructor .
608 * @param in {@code char} array that is the source of characters.
609 * @param mc the context to use.
610 * @throws ArithmeticException if the result is inexact but the
611 * rounding mode is {@code UNNECESSARY}.
612 * @throws NumberFormatException if {@code in} is not a valid
613 * representation of a {@code BigDecimal}.
616 public BigDecimal(char[] in, MathContext mc) {
617 this(in, 0, in.length, mc);
621 * Translates the string representation of a {@code BigDecimal}
622 * into a {@code BigDecimal}. The string representation consists
623 * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or
624 * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of
625 * zero or more decimal digits ("the integer"), optionally
626 * followed by a fraction, optionally followed by an exponent.
628 * <p>The fraction consists of a decimal point followed by zero
629 * or more decimal digits. The string must contain at least one
630 * digit in either the integer or the fraction. The number formed
631 * by the sign, the integer and the fraction is referred to as the
632 * <i>significand</i>.
634 * <p>The exponent consists of the character {@code 'e'}
635 * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>)
636 * followed by one or more decimal digits. The value of the
637 * exponent must lie between -{@link Integer#MAX_VALUE} ({@link
638 * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive.
640 * <p>More formally, the strings this constructor accepts are
641 * described by the following grammar:
644 * <dt><i>BigDecimalString:</i>
645 * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i>
651 * <dt><i>Significand:</i>
652 * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i>
653 * <dd>{@code .} <i>FractionPart</i>
654 * <dd><i>IntegerPart</i>
656 * <dt><i>IntegerPart:</i>
659 * <dt><i>FractionPart:</i>
662 * <dt><i>Exponent:</i>
663 * <dd><i>ExponentIndicator SignedInteger</i>
665 * <dt><i>ExponentIndicator:</i>
669 * <dt><i>SignedInteger:</i>
670 * <dd><i>Sign<sub>opt</sub> Digits</i>
674 * <dd><i>Digits Digit</i>
677 * <dd>any character for which {@link Character#isDigit}
678 * returns {@code true}, including 0, 1, 2 ...
682 * <p>The scale of the returned {@code BigDecimal} will be the
683 * number of digits in the fraction, or zero if the string
684 * contains no decimal point, subject to adjustment for any
685 * exponent; if the string contains an exponent, the exponent is
686 * subtracted from the scale. The value of the resulting scale
687 * must lie between {@code Integer.MIN_VALUE} and
688 * {@code Integer.MAX_VALUE}, inclusive.
690 * <p>The character-to-digit mapping is provided by {@link
691 * java.lang.Character#digit} set to convert to radix 10. The
692 * String may not contain any extraneous characters (whitespace,
695 * <p><b>Examples:</b><br>
696 * The value of the returned {@code BigDecimal} is equal to
697 * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
698 * For each string on the left, the resulting representation
699 * [{@code BigInteger}, {@code scale}] is shown on the right.
711 * "-1.23E-12" [-123,14]
712 * "1234.5E-4" [12345,5]
717 * <p>Note: For values other than {@code float} and
718 * {@code double} NaN and ±Infinity, this constructor is
719 * compatible with the values returned by {@link Float#toString}
720 * and {@link Double#toString}. This is generally the preferred
721 * way to convert a {@code float} or {@code double} into a
722 * BigDecimal, as it doesn't suffer from the unpredictability of
723 * the {@link #BigDecimal(double)} constructor.
725 * @param val String representation of {@code BigDecimal}.
727 * @throws NumberFormatException if {@code val} is not a valid
728 * representation of a {@code BigDecimal}.
730 public BigDecimal(String val) {
731 this(val.toCharArray(), 0, val.length());
735 * Translates the string representation of a {@code BigDecimal}
736 * into a {@code BigDecimal}, accepting the same strings as the
737 * {@link #BigDecimal(String)} constructor, with rounding
738 * according to the context settings.
740 * @param val string representation of a {@code BigDecimal}.
741 * @param mc the context to use.
742 * @throws ArithmeticException if the result is inexact but the
743 * rounding mode is {@code UNNECESSARY}.
744 * @throws NumberFormatException if {@code val} is not a valid
745 * representation of a BigDecimal.
748 public BigDecimal(String val, MathContext mc) {
749 this(val.toCharArray(), 0, val.length());
750 if (mc.precision > 0)
755 * Translates a {@code double} into a {@code BigDecimal} which
756 * is the exact decimal representation of the {@code double}'s
757 * binary floating-point value. The scale of the returned
758 * {@code BigDecimal} is the smallest value such that
759 * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
764 * The results of this constructor can be somewhat unpredictable.
765 * One might assume that writing {@code new BigDecimal(0.1)} in
766 * Java creates a {@code BigDecimal} which is exactly equal to
767 * 0.1 (an unscaled value of 1, with a scale of 1), but it is
769 * 0.1000000000000000055511151231257827021181583404541015625.
770 * This is because 0.1 cannot be represented exactly as a
771 * {@code double} (or, for that matter, as a binary fraction of
772 * any finite length). Thus, the value that is being passed
773 * <i>in</i> to the constructor is not exactly equal to 0.1,
774 * appearances notwithstanding.
777 * The {@code String} constructor, on the other hand, is
778 * perfectly predictable: writing {@code new BigDecimal("0.1")}
779 * creates a {@code BigDecimal} which is <i>exactly</i> equal to
780 * 0.1, as one would expect. Therefore, it is generally
781 * recommended that the {@linkplain #BigDecimal(String)
782 * <tt>String</tt> constructor} be used in preference to this one.
785 * When a {@code double} must be used as a source for a
786 * {@code BigDecimal}, note that this constructor provides an
787 * exact conversion; it does not give the same result as
788 * converting the {@code double} to a {@code String} using the
789 * {@link Double#toString(double)} method and then using the
790 * {@link #BigDecimal(String)} constructor. To get that result,
791 * use the {@code static} {@link #valueOf(double)} method.
794 * @param val {@code double} value to be converted to
795 * {@code BigDecimal}.
796 * @throws NumberFormatException if {@code val} is infinite or NaN.
798 public BigDecimal(double val) {
799 if (Double.isInfinite(val) || Double.isNaN(val))
800 throw new NumberFormatException("Infinite or NaN");
802 // Translate the double into sign, exponent and significand, according
803 // to the formulae in JLS, Section 20.10.22.
804 long valBits = Double.doubleToLongBits(val);
805 int sign = ((valBits >> 63)==0 ? 1 : -1);
806 int exponent = (int) ((valBits >> 52) & 0x7ffL);
807 long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
808 : (valBits & ((1L<<52) - 1)) | (1L<<52));
810 // At this point, val == sign * significand * 2**exponent.
813 * Special case zero to supress nonterminating normalization
814 * and bogus scale calculation.
816 if (significand == 0) {
817 intVal = BigInteger.ZERO;
824 while((significand & 1) == 0) { // i.e., significand is even
829 // Calculate intVal and scale
830 long s = sign * significand;
833 b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
835 } else if (exponent > 0) {
836 b = BigInteger.valueOf(2).pow(exponent).multiply(s);
838 b = BigInteger.valueOf(s);
840 intCompact = compactValFor(b);
841 intVal = (intCompact != INFLATED) ? null : b;
845 * Translates a {@code double} into a {@code BigDecimal}, with
846 * rounding according to the context settings. The scale of the
847 * {@code BigDecimal} is the smallest value such that
848 * <tt>(10<sup>scale</sup> × val)</tt> is an integer.
850 * <p>The results of this constructor can be somewhat unpredictable
851 * and its use is generally not recommended; see the notes under
852 * the {@link #BigDecimal(double)} constructor.
854 * @param val {@code double} value to be converted to
855 * {@code BigDecimal}.
856 * @param mc the context to use.
857 * @throws ArithmeticException if the result is inexact but the
858 * RoundingMode is UNNECESSARY.
859 * @throws NumberFormatException if {@code val} is infinite or NaN.
862 public BigDecimal(double val, MathContext mc) {
864 if (mc.precision > 0)
869 * Translates a {@code BigInteger} into a {@code BigDecimal}.
870 * The scale of the {@code BigDecimal} is zero.
872 * @param val {@code BigInteger} value to be converted to
873 * {@code BigDecimal}.
875 public BigDecimal(BigInteger val) {
876 intCompact = compactValFor(val);
877 intVal = (intCompact != INFLATED) ? null : val;
881 * Translates a {@code BigInteger} into a {@code BigDecimal}
882 * rounding according to the context settings. The scale of the
883 * {@code BigDecimal} is zero.
885 * @param val {@code BigInteger} value to be converted to
886 * {@code BigDecimal}.
887 * @param mc the context to use.
888 * @throws ArithmeticException if the result is inexact but the
889 * rounding mode is {@code UNNECESSARY}.
892 public BigDecimal(BigInteger val, MathContext mc) {
894 if (mc.precision > 0)
899 * Translates a {@code BigInteger} unscaled value and an
900 * {@code int} scale into a {@code BigDecimal}. The value of
901 * the {@code BigDecimal} is
902 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
904 * @param unscaledVal unscaled value of the {@code BigDecimal}.
905 * @param scale scale of the {@code BigDecimal}.
907 public BigDecimal(BigInteger unscaledVal, int scale) {
908 // Negative scales are now allowed
914 * Translates a {@code BigInteger} unscaled value and an
915 * {@code int} scale into a {@code BigDecimal}, with rounding
916 * according to the context settings. The value of the
917 * {@code BigDecimal} is <tt>(unscaledVal ×
918 * 10<sup>-scale</sup>)</tt>, rounded according to the
919 * {@code precision} and rounding mode settings.
921 * @param unscaledVal unscaled value of the {@code BigDecimal}.
922 * @param scale scale of the {@code BigDecimal}.
923 * @param mc the context to use.
924 * @throws ArithmeticException if the result is inexact but the
925 * rounding mode is {@code UNNECESSARY}.
928 public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) {
931 if (mc.precision > 0)
936 * Translates an {@code int} into a {@code BigDecimal}. The
937 * scale of the {@code BigDecimal} is zero.
939 * @param val {@code int} value to be converted to
940 * {@code BigDecimal}.
943 public BigDecimal(int val) {
948 * Translates an {@code int} into a {@code BigDecimal}, with
949 * rounding according to the context settings. The scale of the
950 * {@code BigDecimal}, before any rounding, is zero.
952 * @param val {@code int} value to be converted to {@code BigDecimal}.
953 * @param mc the context to use.
954 * @throws ArithmeticException if the result is inexact but the
955 * rounding mode is {@code UNNECESSARY}.
958 public BigDecimal(int val, MathContext mc) {
960 if (mc.precision > 0)
965 * Translates a {@code long} into a {@code BigDecimal}. The
966 * scale of the {@code BigDecimal} is zero.
968 * @param val {@code long} value to be converted to {@code BigDecimal}.
971 public BigDecimal(long val) {
972 this.intCompact = val;
973 this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
977 * Translates a {@code long} into a {@code BigDecimal}, with
978 * rounding according to the context settings. The scale of the
979 * {@code BigDecimal}, before any rounding, is zero.
981 * @param val {@code long} value to be converted to {@code BigDecimal}.
982 * @param mc the context to use.
983 * @throws ArithmeticException if the result is inexact but the
984 * rounding mode is {@code UNNECESSARY}.
987 public BigDecimal(long val, MathContext mc) {
989 if (mc.precision > 0)
993 // Static Factory Methods
996 * Translates a {@code long} unscaled value and an
997 * {@code int} scale into a {@code BigDecimal}. This
998 * {@literal "static factory method"} is provided in preference to
999 * a ({@code long}, {@code int}) constructor because it
1000 * allows for reuse of frequently used {@code BigDecimal} values..
1002 * @param unscaledVal unscaled value of the {@code BigDecimal}.
1003 * @param scale scale of the {@code BigDecimal}.
1004 * @return a {@code BigDecimal} whose value is
1005 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
1007 public static BigDecimal valueOf(long unscaledVal, int scale) {
1009 return valueOf(unscaledVal);
1010 else if (unscaledVal == 0) {
1011 if (scale > 0 && scale < ZERO_SCALED_BY.length)
1012 return ZERO_SCALED_BY[scale];
1014 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1016 return new BigDecimal(unscaledVal == INFLATED ?
1017 BigInteger.valueOf(unscaledVal) : null,
1018 unscaledVal, scale, 0);
1022 * Translates a {@code long} value into a {@code BigDecimal}
1023 * with a scale of zero. This {@literal "static factory method"}
1024 * is provided in preference to a ({@code long}) constructor
1025 * because it allows for reuse of frequently used
1026 * {@code BigDecimal} values.
1028 * @param val value of the {@code BigDecimal}.
1029 * @return a {@code BigDecimal} whose value is {@code val}.
1031 public static BigDecimal valueOf(long val) {
1032 if (val >= 0 && val < zeroThroughTen.length)
1033 return zeroThroughTen[(int)val];
1034 else if (val != INFLATED)
1035 return new BigDecimal(null, val, 0, 0);
1036 return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
1040 * Translates a {@code double} into a {@code BigDecimal}, using
1041 * the {@code double}'s canonical string representation provided
1042 * by the {@link Double#toString(double)} method.
1044 * <p><b>Note:</b> This is generally the preferred way to convert
1045 * a {@code double} (or {@code float}) into a
1046 * {@code BigDecimal}, as the value returned is equal to that
1047 * resulting from constructing a {@code BigDecimal} from the
1048 * result of using {@link Double#toString(double)}.
1050 * @param val {@code double} to convert to a {@code BigDecimal}.
1051 * @return a {@code BigDecimal} whose value is equal to or approximately
1052 * equal to the value of {@code val}.
1053 * @throws NumberFormatException if {@code val} is infinite or NaN.
1056 public static BigDecimal valueOf(double val) {
1057 // Reminder: a zero double returns '0.0', so we cannot fastpath
1058 // to use the constant ZERO. This might be important enough to
1059 // justify a factory approach, a cache, or a few private
1060 // constants, later.
1061 return new BigDecimal(Double.toString(val));
1064 // Arithmetic Operations
1066 * Returns a {@code BigDecimal} whose value is {@code (this +
1067 * augend)}, and whose scale is {@code max(this.scale(),
1070 * @param augend value to be added to this {@code BigDecimal}.
1071 * @return {@code this + augend}
1073 public BigDecimal add(BigDecimal augend) {
1074 long xs = this.intCompact;
1075 long ys = augend.intCompact;
1076 BigInteger fst = (xs != INFLATED) ? null : this.intVal;
1077 BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
1078 int rscale = this.scale;
1080 long sdiff = (long)rscale - augend.scale;
1083 int raise = checkScale(-sdiff);
1084 rscale = augend.scale;
1085 if (xs == INFLATED ||
1086 (xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
1087 fst = bigMultiplyPowerTen(raise);
1089 int raise = augend.checkScale(sdiff);
1090 if (ys == INFLATED ||
1091 (ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
1092 snd = augend.bigMultiplyPowerTen(raise);
1095 if (xs != INFLATED && ys != INFLATED) {
1097 // See "Hacker's Delight" section 2-12 for explanation of
1098 // the overflow test.
1099 if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
1100 return BigDecimal.valueOf(sum, rscale);
1103 fst = BigInteger.valueOf(xs);
1105 snd = BigInteger.valueOf(ys);
1106 BigInteger sum = fst.add(snd);
1107 return (fst.signum == snd.signum) ?
1108 new BigDecimal(sum, INFLATED, rscale, 0) :
1109 new BigDecimal(sum, rscale);
1113 * Returns a {@code BigDecimal} whose value is {@code (this + augend)},
1114 * with rounding according to the context settings.
1116 * If either number is zero and the precision setting is nonzero then
1117 * the other number, rounded if necessary, is used as the result.
1119 * @param augend value to be added to this {@code BigDecimal}.
1120 * @param mc the context to use.
1121 * @return {@code this + augend}, rounded as necessary.
1122 * @throws ArithmeticException if the result is inexact but the
1123 * rounding mode is {@code UNNECESSARY}.
1126 public BigDecimal add(BigDecimal augend, MathContext mc) {
1127 if (mc.precision == 0)
1129 BigDecimal lhs = this;
1131 // Could optimize if values are compact
1135 // If either number is zero then the other number, rounded and
1136 // scaled if necessary, is used as the result.
1138 boolean lhsIsZero = lhs.signum() == 0;
1139 boolean augendIsZero = augend.signum() == 0;
1141 if (lhsIsZero || augendIsZero) {
1142 int preferredScale = Math.max(lhs.scale(), augend.scale());
1145 // Could use a factory for zero instead of a new object
1146 if (lhsIsZero && augendIsZero)
1147 return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
1149 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
1151 if (result.scale() == preferredScale)
1153 else if (result.scale() > preferredScale) {
1154 BigDecimal scaledResult =
1155 new BigDecimal(result.intVal, result.intCompact,
1157 scaledResult.stripZerosToMatchScale(preferredScale);
1158 return scaledResult;
1159 } else { // result.scale < preferredScale
1160 int precisionDiff = mc.precision - result.precision();
1161 int scaleDiff = preferredScale - result.scale();
1163 if (precisionDiff >= scaleDiff)
1164 return result.setScale(preferredScale); // can achieve target scale
1166 return result.setScale(result.scale() + precisionDiff);
1171 long padding = (long)lhs.scale - augend.scale;
1172 if (padding != 0) { // scales differ; alignment needed
1173 BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
1179 BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
1181 return doRound(d, mc);
1185 * Returns an array of length two, the sum of whose entries is
1186 * equal to the rounded sum of the {@code BigDecimal} arguments.
1188 * <p>If the digit positions of the arguments have a sufficient
1189 * gap between them, the value smaller in magnitude can be
1190 * condensed into a {@literal "sticky bit"} and the end result will
1191 * round the same way <em>if</em> the precision of the final
1192 * result does not include the high order digit of the small
1193 * magnitude operand.
1195 * <p>Note that while strictly speaking this is an optimization,
1196 * it makes a much wider range of additions practical.
1198 * <p>This corresponds to a pre-shift operation in a fixed
1199 * precision floating-point adder; this method is complicated by
1200 * variable precision of the result as determined by the
1201 * MathContext. A more nuanced operation could implement a
1202 * {@literal "right shift"} on the smaller magnitude operand so
1203 * that the number of digits of the smaller operand could be
1204 * reduced even though the significands partially overlapped.
1206 private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend,
1207 long padding, MathContext mc) {
1208 assert padding != 0;
1212 if (padding < 0) { // lhs is big; augend is small
1215 } else { // lhs is small; augend is big
1221 * This is the estimated scale of an ulp of the result; it
1222 * assumes that the result doesn't have a carry-out on a true
1223 * add (e.g. 999 + 1 => 1000) or any subtractive cancellation
1224 * on borrowing (e.g. 100 - 1.2 => 98.8)
1226 long estResultUlpScale = (long)big.scale - big.precision() + mc.precision;
1229 * The low-order digit position of big is big.scale(). This
1230 * is true regardless of whether big has a positive or
1231 * negative scale. The high-order digit position of small is
1232 * small.scale - (small.precision() - 1). To do the full
1233 * condensation, the digit positions of big and small must be
1234 * disjoint *and* the digit positions of small should not be
1235 * directly visible in the result.
1237 long smallHighDigitPos = (long)small.scale - small.precision() + 1;
1238 if (smallHighDigitPos > big.scale + 2 && // big and small disjoint
1239 smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible
1240 small = BigDecimal.valueOf(small.signum(),
1241 this.checkScale(Math.max(big.scale, estResultUlpScale) + 3));
1244 // Since addition is symmetric, preserving input order in
1245 // returned operands doesn't matter
1246 BigDecimal[] result = {big, small};
1251 * Returns a {@code BigDecimal} whose value is {@code (this -
1252 * subtrahend)}, and whose scale is {@code max(this.scale(),
1253 * subtrahend.scale())}.
1255 * @param subtrahend value to be subtracted from this {@code BigDecimal}.
1256 * @return {@code this - subtrahend}
1258 public BigDecimal subtract(BigDecimal subtrahend) {
1259 return add(subtrahend.negate());
1263 * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
1264 * with rounding according to the context settings.
1266 * If {@code subtrahend} is zero then this, rounded if necessary, is used as the
1267 * result. If this is zero then the result is {@code subtrahend.negate(mc)}.
1269 * @param subtrahend value to be subtracted from this {@code BigDecimal}.
1270 * @param mc the context to use.
1271 * @return {@code this - subtrahend}, rounded as necessary.
1272 * @throws ArithmeticException if the result is inexact but the
1273 * rounding mode is {@code UNNECESSARY}.
1276 public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) {
1277 BigDecimal nsubtrahend = subtrahend.negate();
1278 if (mc.precision == 0)
1279 return add(nsubtrahend);
1280 // share the special rounding code in add()
1281 return add(nsubtrahend, mc);
1285 * Returns a {@code BigDecimal} whose value is <tt>(this ×
1286 * multiplicand)</tt>, and whose scale is {@code (this.scale() +
1287 * multiplicand.scale())}.
1289 * @param multiplicand value to be multiplied by this {@code BigDecimal}.
1290 * @return {@code this * multiplicand}
1292 public BigDecimal multiply(BigDecimal multiplicand) {
1293 long x = this.intCompact;
1294 long y = multiplicand.intCompact;
1295 int productScale = checkScale((long)scale + multiplicand.scale);
1297 // Might be able to do a more clever check incorporating the
1298 // inflated check into the overflow computation.
1299 if (x != INFLATED && y != INFLATED) {
1301 * If the product is not an overflowed value, continue
1302 * to use the compact representation. if either of x or y
1303 * is INFLATED, the product should also be regarded as
1304 * an overflow. Before using the overflow test suggested in
1305 * "Hacker's Delight" section 2-12, we perform quick checks
1306 * using the precision information to see whether the overflow
1307 * would occur since division is expensive on most CPUs.
1309 long product = x * y;
1310 long prec = this.precision() + multiplicand.precision();
1311 if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
1312 return BigDecimal.valueOf(product, productScale);
1313 return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
1317 if (x == INFLATED && y == INFLATED)
1318 rb = this.intVal.multiply(multiplicand.intVal);
1319 else if (x != INFLATED)
1320 rb = multiplicand.intVal.multiply(x);
1322 rb = this.intVal.multiply(y);
1323 return new BigDecimal(rb, INFLATED, productScale, 0);
1327 * Returns a {@code BigDecimal} whose value is <tt>(this ×
1328 * multiplicand)</tt>, with rounding according to the context settings.
1330 * @param multiplicand value to be multiplied by this {@code BigDecimal}.
1331 * @param mc the context to use.
1332 * @return {@code this * multiplicand}, rounded as necessary.
1333 * @throws ArithmeticException if the result is inexact but the
1334 * rounding mode is {@code UNNECESSARY}.
1337 public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) {
1338 if (mc.precision == 0)
1339 return multiply(multiplicand);
1340 return doRound(this.multiply(multiplicand), mc);
1344 * Returns a {@code BigDecimal} whose value is {@code (this /
1345 * divisor)}, and whose scale is as specified. If rounding must
1346 * be performed to generate a result with the specified scale, the
1347 * specified rounding mode is applied.
1349 * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method
1350 * should be used in preference to this legacy method.
1352 * @param divisor value by which this {@code BigDecimal} is to be divided.
1353 * @param scale scale of the {@code BigDecimal} quotient to be returned.
1354 * @param roundingMode rounding mode to apply.
1355 * @return {@code this / divisor}
1356 * @throws ArithmeticException if {@code divisor} is zero,
1357 * {@code roundingMode==ROUND_UNNECESSARY} and
1358 * the specified scale is insufficient to represent the result
1359 * of the division exactly.
1360 * @throws IllegalArgumentException if {@code roundingMode} does not
1361 * represent a valid rounding mode.
1364 * @see #ROUND_CEILING
1366 * @see #ROUND_HALF_UP
1367 * @see #ROUND_HALF_DOWN
1368 * @see #ROUND_HALF_EVEN
1369 * @see #ROUND_UNNECESSARY
1371 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) {
1373 * IMPLEMENTATION NOTE: This method *must* return a new object
1374 * since divideAndRound uses divide to generate a value whose
1375 * scale is then modified.
1377 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
1378 throw new IllegalArgumentException("Invalid rounding mode");
1380 * Rescale dividend or divisor (whichever can be "upscaled" to
1381 * produce correctly scaled quotient).
1382 * Take care to detect out-of-range scales
1384 BigDecimal dividend = this;
1385 if (checkScale((long)scale + divisor.scale) > this.scale)
1386 dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
1388 divisor = divisor.setScale(checkScale((long)this.scale - scale),
1390 return divideAndRound(dividend.intCompact, dividend.intVal,
1391 divisor.intCompact, divisor.intVal,
1392 scale, roundingMode, scale);
1396 * Internally used for division operation. The dividend and divisor are
1397 * passed both in {@code long} format and {@code BigInteger} format. The
1398 * returned {@code BigDecimal} object is the quotient whose scale is set to
1399 * the passed in scale. If the remainder is not zero, it will be rounded
1400 * based on the passed in roundingMode. Also, if the remainder is zero and
1401 * the last parameter, i.e. preferredScale is NOT equal to scale, the
1402 * trailing zeros of the result is stripped to match the preferredScale.
1404 private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend,
1405 long ldivisor, BigInteger bdivisor,
1406 int scale, int roundingMode,
1407 int preferredScale) {
1408 boolean isRemainderZero; // record remainder is zero or not
1409 int qsign; // quotient sign
1410 long q = 0, r = 0; // store quotient & remainder in long
1411 MutableBigInteger mq = null; // store quotient
1412 MutableBigInteger mr = null; // store remainder
1413 MutableBigInteger mdivisor = null;
1414 boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED);
1415 if (isLongDivision) {
1416 q = ldividend / ldivisor;
1417 if (roundingMode == ROUND_DOWN && scale == preferredScale)
1418 return new BigDecimal(null, q, scale, 0);
1419 r = ldividend % ldivisor;
1420 isRemainderZero = (r == 0);
1421 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1;
1423 if (bdividend == null)
1424 bdividend = BigInteger.valueOf(ldividend);
1425 // Descend into mutables for faster remainder checks
1426 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
1427 mq = new MutableBigInteger();
1428 if (ldivisor != INFLATED) {
1429 r = mdividend.divide(ldivisor, mq);
1430 isRemainderZero = (r == 0);
1431 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
1433 mdivisor = new MutableBigInteger(bdivisor.mag);
1434 mr = mdividend.divide(mdivisor, mq);
1435 isRemainderZero = mr.isZero();
1436 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1;
1439 boolean increment = false;
1440 if (!isRemainderZero) {
1442 /* Round as appropriate */
1443 if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited
1444 throw new ArithmeticException("Rounding necessary");
1445 } else if (roundingMode == ROUND_UP) { // Away from zero
1447 } else if (roundingMode == ROUND_DOWN) { // Towards zero
1449 } else if (roundingMode == ROUND_CEILING) { // Towards +infinity
1450 increment = (qsign > 0);
1451 } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity
1452 increment = (qsign < 0);
1454 if (isLongDivision || ldivisor != INFLATED) {
1455 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
1456 cmpFracHalf = 1; // 2 * r can't fit into long
1458 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
1461 cmpFracHalf = mr.compareHalf(mdivisor);
1463 if (cmpFracHalf < 0)
1464 increment = false; // We're closer to higher digit
1465 else if (cmpFracHalf > 0) // We're closer to lower digit
1467 else if (roundingMode == ROUND_HALF_UP)
1469 else if (roundingMode == ROUND_HALF_DOWN)
1471 else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd
1472 increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd();
1477 res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0);
1480 mq.add(MutableBigInteger.ONE);
1481 res = mq.toBigDecimal(qsign, scale);
1483 if (isRemainderZero && preferredScale != scale)
1484 res.stripZerosToMatchScale(preferredScale);
1489 * Returns a {@code BigDecimal} whose value is {@code (this /
1490 * divisor)}, and whose scale is as specified. If rounding must
1491 * be performed to generate a result with the specified scale, the
1492 * specified rounding mode is applied.
1494 * @param divisor value by which this {@code BigDecimal} is to be divided.
1495 * @param scale scale of the {@code BigDecimal} quotient to be returned.
1496 * @param roundingMode rounding mode to apply.
1497 * @return {@code this / divisor}
1498 * @throws ArithmeticException if {@code divisor} is zero,
1499 * {@code roundingMode==RoundingMode.UNNECESSARY} and
1500 * the specified scale is insufficient to represent the result
1501 * of the division exactly.
1504 public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
1505 return divide(divisor, scale, roundingMode.oldMode);
1509 * Returns a {@code BigDecimal} whose value is {@code (this /
1510 * divisor)}, and whose scale is {@code this.scale()}. If
1511 * rounding must be performed to generate a result with the given
1512 * scale, the specified rounding mode is applied.
1514 * <p>The new {@link #divide(BigDecimal, RoundingMode)} method
1515 * should be used in preference to this legacy method.
1517 * @param divisor value by which this {@code BigDecimal} is to be divided.
1518 * @param roundingMode rounding mode to apply.
1519 * @return {@code this / divisor}
1520 * @throws ArithmeticException if {@code divisor==0}, or
1521 * {@code roundingMode==ROUND_UNNECESSARY} and
1522 * {@code this.scale()} is insufficient to represent the result
1523 * of the division exactly.
1524 * @throws IllegalArgumentException if {@code roundingMode} does not
1525 * represent a valid rounding mode.
1528 * @see #ROUND_CEILING
1530 * @see #ROUND_HALF_UP
1531 * @see #ROUND_HALF_DOWN
1532 * @see #ROUND_HALF_EVEN
1533 * @see #ROUND_UNNECESSARY
1535 public BigDecimal divide(BigDecimal divisor, int roundingMode) {
1536 return this.divide(divisor, scale, roundingMode);
1540 * Returns a {@code BigDecimal} whose value is {@code (this /
1541 * divisor)}, and whose scale is {@code this.scale()}. If
1542 * rounding must be performed to generate a result with the given
1543 * scale, the specified rounding mode is applied.
1545 * @param divisor value by which this {@code BigDecimal} is to be divided.
1546 * @param roundingMode rounding mode to apply.
1547 * @return {@code this / divisor}
1548 * @throws ArithmeticException if {@code divisor==0}, or
1549 * {@code roundingMode==RoundingMode.UNNECESSARY} and
1550 * {@code this.scale()} is insufficient to represent the result
1551 * of the division exactly.
1554 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) {
1555 return this.divide(divisor, scale, roundingMode.oldMode);
1559 * Returns a {@code BigDecimal} whose value is {@code (this /
1560 * divisor)}, and whose preferred scale is {@code (this.scale() -
1561 * divisor.scale())}; if the exact quotient cannot be
1562 * represented (because it has a non-terminating decimal
1563 * expansion) an {@code ArithmeticException} is thrown.
1565 * @param divisor value by which this {@code BigDecimal} is to be divided.
1566 * @throws ArithmeticException if the exact quotient does not have a
1567 * terminating decimal expansion
1568 * @return {@code this / divisor}
1570 * @author Joseph D. Darcy
1572 public BigDecimal divide(BigDecimal divisor) {
1574 * Handle zero cases first.
1576 if (divisor.signum() == 0) { // x/0
1577 if (this.signum() == 0) // 0/0
1578 throw new ArithmeticException("Division undefined"); // NaN
1579 throw new ArithmeticException("Division by zero");
1582 // Calculate preferred scale
1583 int preferredScale = saturateLong((long)this.scale - divisor.scale);
1584 if (this.signum() == 0) // 0/y
1585 return (preferredScale >= 0 &&
1586 preferredScale < ZERO_SCALED_BY.length) ?
1587 ZERO_SCALED_BY[preferredScale] :
1588 BigDecimal.valueOf(0, preferredScale);
1593 * If the quotient this/divisor has a terminating decimal
1594 * expansion, the expansion can have no more than
1595 * (a.precision() + ceil(10*b.precision)/3) digits.
1596 * Therefore, create a MathContext object with this
1597 * precision and do a divide with the UNNECESSARY rounding
1600 MathContext mc = new MathContext( (int)Math.min(this.precision() +
1601 (long)Math.ceil(10.0*divisor.precision()/3.0),
1603 RoundingMode.UNNECESSARY);
1604 BigDecimal quotient;
1606 quotient = this.divide(divisor, mc);
1607 } catch (ArithmeticException e) {
1608 throw new ArithmeticException("Non-terminating decimal expansion; " +
1609 "no exact representable decimal result.");
1612 int quotientScale = quotient.scale();
1614 // divide(BigDecimal, mc) tries to adjust the quotient to
1615 // the desired one by removing trailing zeros; since the
1616 // exact divide method does not have an explicit digit
1617 // limit, we can add zeros too.
1619 if (preferredScale > quotientScale)
1620 return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1627 * Returns a {@code BigDecimal} whose value is {@code (this /
1628 * divisor)}, with rounding according to the context settings.
1630 * @param divisor value by which this {@code BigDecimal} is to be divided.
1631 * @param mc the context to use.
1632 * @return {@code this / divisor}, rounded as necessary.
1633 * @throws ArithmeticException if the result is inexact but the
1634 * rounding mode is {@code UNNECESSARY} or
1635 * {@code mc.precision == 0} and the quotient has a
1636 * non-terminating decimal expansion.
1639 public BigDecimal divide(BigDecimal divisor, MathContext mc) {
1640 int mcp = mc.precision;
1642 return divide(divisor);
1644 BigDecimal dividend = this;
1645 long preferredScale = (long)dividend.scale - divisor.scale;
1646 // Now calculate the answer. We use the existing
1647 // divide-and-round method, but as this rounds to scale we have
1648 // to normalize the values here to achieve the desired result.
1649 // For x/y we first handle y=0 and x=0, and then normalize x and
1650 // y to give x' and y' with the following constraints:
1651 // (a) 0.1 <= x' < 1
1652 // (b) x' <= y' < 10*x'
1653 // Dividing x'/y' with the required scale set to mc.precision then
1654 // will give a result in the range 0.1 to 1 rounded to exactly
1655 // the right number of digits (except in the case of a result of
1656 // 1.000... which can arise when x=y, or when rounding overflows
1657 // The 1.000... case will reduce properly to 1.
1658 if (divisor.signum() == 0) { // x/0
1659 if (dividend.signum() == 0) // 0/0
1660 throw new ArithmeticException("Division undefined"); // NaN
1661 throw new ArithmeticException("Division by zero");
1663 if (dividend.signum() == 0) // 0/y
1664 return new BigDecimal(BigInteger.ZERO, 0,
1665 saturateLong(preferredScale), 1);
1667 // Normalize dividend & divisor so that both fall into [0.1, 0.999...]
1668 int xscale = dividend.precision();
1669 int yscale = divisor.precision();
1670 dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
1672 divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
1674 if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
1675 yscale = divisor.scale -= 1; // [that is, divisor *= 10]
1677 // In order to find out whether the divide generates the exact result,
1678 // we avoid calling the above divide method. 'quotient' holds the
1679 // return BigDecimal object whose scale will be set to 'scl'.
1680 BigDecimal quotient;
1681 int scl = checkScale(preferredScale + yscale - xscale + mcp);
1682 if (checkScale((long)mcp + yscale) > xscale)
1683 dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
1685 divisor = divisor.setScale(checkScale((long)xscale - mcp),
1687 quotient = divideAndRound(dividend.intCompact, dividend.intVal,
1688 divisor.intCompact, divisor.intVal,
1689 scl, mc.roundingMode.oldMode,
1690 checkScale(preferredScale));
1691 // doRound, here, only affects 1000000000 case.
1692 quotient = doRound(quotient, mc);
1698 * Returns a {@code BigDecimal} whose value is the integer part
1699 * of the quotient {@code (this / divisor)} rounded down. The
1700 * preferred scale of the result is {@code (this.scale() -
1701 * divisor.scale())}.
1703 * @param divisor value by which this {@code BigDecimal} is to be divided.
1704 * @return The integer part of {@code this / divisor}.
1705 * @throws ArithmeticException if {@code divisor==0}
1708 public BigDecimal divideToIntegralValue(BigDecimal divisor) {
1709 // Calculate preferred scale
1710 int preferredScale = saturateLong((long)this.scale - divisor.scale);
1711 if (this.compareMagnitude(divisor) < 0) {
1712 // much faster when this << divisor
1713 return BigDecimal.valueOf(0, preferredScale);
1716 if(this.signum() == 0 && divisor.signum() != 0)
1717 return this.setScale(preferredScale, ROUND_UNNECESSARY);
1719 // Perform a divide with enough digits to round to a correct
1720 // integer value; then remove any fractional digits
1722 int maxDigits = (int)Math.min(this.precision() +
1723 (long)Math.ceil(10.0*divisor.precision()/3.0) +
1724 Math.abs((long)this.scale() - divisor.scale()) + 2,
1726 BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
1727 RoundingMode.DOWN));
1728 if (quotient.scale > 0) {
1729 quotient = quotient.setScale(0, RoundingMode.DOWN);
1730 quotient.stripZerosToMatchScale(preferredScale);
1733 if (quotient.scale < preferredScale) {
1734 // pad with zeros if necessary
1735 quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
1741 * Returns a {@code BigDecimal} whose value is the integer part
1742 * of {@code (this / divisor)}. Since the integer part of the
1743 * exact quotient does not depend on the rounding mode, the
1744 * rounding mode does not affect the values returned by this
1745 * method. The preferred scale of the result is
1746 * {@code (this.scale() - divisor.scale())}. An
1747 * {@code ArithmeticException} is thrown if the integer part of
1748 * the exact quotient needs more than {@code mc.precision}
1751 * @param divisor value by which this {@code BigDecimal} is to be divided.
1752 * @param mc the context to use.
1753 * @return The integer part of {@code this / divisor}.
1754 * @throws ArithmeticException if {@code divisor==0}
1755 * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result
1756 * requires a precision of more than {@code mc.precision} digits.
1758 * @author Joseph D. Darcy
1760 public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) {
1761 if (mc.precision == 0 || // exact result
1762 (this.compareMagnitude(divisor) < 0) ) // zero result
1763 return divideToIntegralValue(divisor);
1765 // Calculate preferred scale
1766 int preferredScale = saturateLong((long)this.scale - divisor.scale);
1769 * Perform a normal divide to mc.precision digits. If the
1770 * remainder has absolute value less than the divisor, the
1771 * integer portion of the quotient fits into mc.precision
1772 * digits. Next, remove any fractional digits from the
1773 * quotient and adjust the scale to the preferred value.
1775 BigDecimal result = this.
1776 divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
1778 if (result.scale() < 0) {
1780 * Result is an integer. See if quotient represents the
1781 * full integer portion of the exact quotient; if it does,
1782 * the computed remainder will be less than the divisor.
1784 BigDecimal product = result.multiply(divisor);
1785 // If the quotient is the full integer value,
1786 // |dividend-product| < |divisor|.
1787 if (this.subtract(product).compareMagnitude(divisor) >= 0) {
1788 throw new ArithmeticException("Division impossible");
1790 } else if (result.scale() > 0) {
1792 * Integer portion of quotient will fit into precision
1793 * digits; recompute quotient to scale 0 to avoid double
1794 * rounding and then try to adjust, if necessary.
1796 result = result.setScale(0, RoundingMode.DOWN);
1798 // else result.scale() == 0;
1801 if ((preferredScale > result.scale()) &&
1802 (precisionDiff = mc.precision - result.precision()) > 0) {
1803 return result.setScale(result.scale() +
1804 Math.min(precisionDiff, preferredScale - result.scale) );
1806 result.stripZerosToMatchScale(preferredScale);
1812 * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1814 * <p>The remainder is given by
1815 * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1816 * Note that this is not the modulo operation (the result can be
1819 * @param divisor value by which this {@code BigDecimal} is to be divided.
1820 * @return {@code this % divisor}.
1821 * @throws ArithmeticException if {@code divisor==0}
1824 public BigDecimal remainder(BigDecimal divisor) {
1825 BigDecimal divrem[] = this.divideAndRemainder(divisor);
1831 * Returns a {@code BigDecimal} whose value is {@code (this %
1832 * divisor)}, with rounding according to the context settings.
1833 * The {@code MathContext} settings affect the implicit divide
1834 * used to compute the remainder. The remainder computation
1835 * itself is by definition exact. Therefore, the remainder may
1836 * contain more than {@code mc.getPrecision()} digits.
1838 * <p>The remainder is given by
1839 * {@code this.subtract(this.divideToIntegralValue(divisor,
1840 * mc).multiply(divisor))}. Note that this is not the modulo
1841 * operation (the result can be negative).
1843 * @param divisor value by which this {@code BigDecimal} is to be divided.
1844 * @param mc the context to use.
1845 * @return {@code this % divisor}, rounded as necessary.
1846 * @throws ArithmeticException if {@code divisor==0}
1847 * @throws ArithmeticException if the result is inexact but the
1848 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1849 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1850 * require a precision of more than {@code mc.precision} digits.
1851 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1854 public BigDecimal remainder(BigDecimal divisor, MathContext mc) {
1855 BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
1860 * Returns a two-element {@code BigDecimal} array containing the
1861 * result of {@code divideToIntegralValue} followed by the result of
1862 * {@code remainder} on the two operands.
1864 * <p>Note that if both the integer quotient and remainder are
1865 * needed, this method is faster than using the
1866 * {@code divideToIntegralValue} and {@code remainder} methods
1867 * separately because the division need only be carried out once.
1869 * @param divisor value by which this {@code BigDecimal} is to be divided,
1870 * and the remainder computed.
1871 * @return a two element {@code BigDecimal} array: the quotient
1872 * (the result of {@code divideToIntegralValue}) is the initial element
1873 * and the remainder is the final element.
1874 * @throws ArithmeticException if {@code divisor==0}
1875 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1876 * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1879 public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
1880 // we use the identity x = i * y + r to determine r
1881 BigDecimal[] result = new BigDecimal[2];
1883 result[0] = this.divideToIntegralValue(divisor);
1884 result[1] = this.subtract(result[0].multiply(divisor));
1889 * Returns a two-element {@code BigDecimal} array containing the
1890 * result of {@code divideToIntegralValue} followed by the result of
1891 * {@code remainder} on the two operands calculated with rounding
1892 * according to the context settings.
1894 * <p>Note that if both the integer quotient and remainder are
1895 * needed, this method is faster than using the
1896 * {@code divideToIntegralValue} and {@code remainder} methods
1897 * separately because the division need only be carried out once.
1899 * @param divisor value by which this {@code BigDecimal} is to be divided,
1900 * and the remainder computed.
1901 * @param mc the context to use.
1902 * @return a two element {@code BigDecimal} array: the quotient
1903 * (the result of {@code divideToIntegralValue}) is the
1904 * initial element and the remainder is the final element.
1905 * @throws ArithmeticException if {@code divisor==0}
1906 * @throws ArithmeticException if the result is inexact but the
1907 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision}
1908 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would
1909 * require a precision of more than {@code mc.precision} digits.
1910 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext)
1911 * @see #remainder(java.math.BigDecimal, java.math.MathContext)
1914 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) {
1915 if (mc.precision == 0)
1916 return divideAndRemainder(divisor);
1918 BigDecimal[] result = new BigDecimal[2];
1919 BigDecimal lhs = this;
1921 result[0] = lhs.divideToIntegralValue(divisor, mc);
1922 result[1] = lhs.subtract(result[0].multiply(divisor));
1927 * Returns a {@code BigDecimal} whose value is
1928 * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to
1929 * unlimited precision.
1931 * <p>The parameter {@code n} must be in the range 0 through
1932 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link
1935 * Note that future releases may expand the allowable exponent
1936 * range of this method.
1938 * @param n power to raise this {@code BigDecimal} to.
1939 * @return <tt>this<sup>n</sup></tt>
1940 * @throws ArithmeticException if {@code n} is out of range.
1943 public BigDecimal pow(int n) {
1944 if (n < 0 || n > 999999999)
1945 throw new ArithmeticException("Invalid operation");
1946 // No need to calculate pow(n) if result will over/underflow.
1947 // Don't attempt to support "supernormal" numbers.
1948 int newScale = checkScale((long)scale * n);
1950 return new BigDecimal(intVal.pow(n), newScale);
1955 * Returns a {@code BigDecimal} whose value is
1956 * <tt>(this<sup>n</sup>)</tt>. The current implementation uses
1957 * the core algorithm defined in ANSI standard X3.274-1996 with
1958 * rounding according to the context settings. In general, the
1959 * returned numerical value is within two ulps of the exact
1960 * numerical value for the chosen precision. Note that future
1961 * releases may use a different algorithm with a decreased
1962 * allowable error bound and increased allowable exponent range.
1964 * <p>The X3.274-1996 algorithm is:
1967 * <li> An {@code ArithmeticException} exception is thrown if
1969 * <li>{@code abs(n) > 999999999}
1970 * <li>{@code mc.precision == 0} and {@code n < 0}
1971 * <li>{@code mc.precision > 0} and {@code n} has more than
1972 * {@code mc.precision} decimal digits
1975 * <li> if {@code n} is zero, {@link #ONE} is returned even if
1976 * {@code this} is zero, otherwise
1978 * <li> if {@code n} is positive, the result is calculated via
1979 * the repeated squaring technique into a single accumulator.
1980 * The individual multiplications with the accumulator use the
1981 * same math context settings as in {@code mc} except for a
1982 * precision increased to {@code mc.precision + elength + 1}
1983 * where {@code elength} is the number of decimal digits in
1986 * <li> if {@code n} is negative, the result is calculated as if
1987 * {@code n} were positive; this value is then divided into one
1988 * using the working precision specified above.
1990 * <li> The final value from either the positive or negative case
1991 * is then rounded to the destination precision.
1995 * @param n power to raise this {@code BigDecimal} to.
1996 * @param mc the context to use.
1997 * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996
1999 * @throws ArithmeticException if the result is inexact but the
2000 * rounding mode is {@code UNNECESSARY}, or {@code n} is out
2004 public BigDecimal pow(int n, MathContext mc) {
2005 if (mc.precision == 0)
2007 if (n < -999999999 || n > 999999999)
2008 throw new ArithmeticException("Invalid operation");
2010 return ONE; // x**0 == 1 in X3.274
2012 BigDecimal lhs = this;
2013 MathContext workmc = mc; // working settings
2014 int mag = Math.abs(n); // magnitude of n
2015 if (mc.precision > 0) {
2017 int elength = longDigitLength(mag); // length of n in digits
2018 if (elength > mc.precision) // X3.274 rule
2019 throw new ArithmeticException("Invalid operation");
2020 workmc = new MathContext(mc.precision + elength + 1,
2023 // ready to carry out power calculation...
2024 BigDecimal acc = ONE; // accumulator
2025 boolean seenbit = false; // set once we've seen a 1-bit
2026 for (int i=1;;i++) { // for each bit [top bit ignored]
2027 mag += mag; // shift left 1 bit
2028 if (mag < 0) { // top bit is set
2029 seenbit = true; // OK, we're off
2030 acc = acc.multiply(lhs, workmc); // acc=acc*x
2033 break; // that was the last bit
2035 acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
2036 // else (!seenbit) no point in squaring ONE
2038 // if negative n, calculate the reciprocal using working precision
2039 if (n<0) // [hence mc.precision>0]
2040 acc=ONE.divide(acc, workmc);
2041 // round to final precision and strip zeros
2042 return doRound(acc, mc);
2046 * Returns a {@code BigDecimal} whose value is the absolute value
2047 * of this {@code BigDecimal}, and whose scale is
2048 * {@code this.scale()}.
2050 * @return {@code abs(this)}
2052 public BigDecimal abs() {
2053 return (signum() < 0 ? negate() : this);
2057 * Returns a {@code BigDecimal} whose value is the absolute value
2058 * of this {@code BigDecimal}, with rounding according to the
2061 * @param mc the context to use.
2062 * @return {@code abs(this)}, rounded as necessary.
2063 * @throws ArithmeticException if the result is inexact but the
2064 * rounding mode is {@code UNNECESSARY}.
2067 public BigDecimal abs(MathContext mc) {
2068 return (signum() < 0 ? negate(mc) : plus(mc));
2072 * Returns a {@code BigDecimal} whose value is {@code (-this)},
2073 * and whose scale is {@code this.scale()}.
2075 * @return {@code -this}.
2077 public BigDecimal negate() {
2079 if (intCompact != INFLATED)
2080 result = BigDecimal.valueOf(-intCompact, scale);
2082 result = new BigDecimal(intVal.negate(), scale);
2083 result.precision = precision;
2089 * Returns a {@code BigDecimal} whose value is {@code (-this)},
2090 * with rounding according to the context settings.
2092 * @param mc the context to use.
2093 * @return {@code -this}, rounded as necessary.
2094 * @throws ArithmeticException if the result is inexact but the
2095 * rounding mode is {@code UNNECESSARY}.
2098 public BigDecimal negate(MathContext mc) {
2099 return negate().plus(mc);
2103 * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
2104 * scale is {@code this.scale()}.
2106 * <p>This method, which simply returns this {@code BigDecimal}
2107 * is included for symmetry with the unary minus method {@link
2110 * @return {@code this}.
2114 public BigDecimal plus() {
2119 * Returns a {@code BigDecimal} whose value is {@code (+this)},
2120 * with rounding according to the context settings.
2122 * <p>The effect of this method is identical to that of the {@link
2123 * #round(MathContext)} method.
2125 * @param mc the context to use.
2126 * @return {@code this}, rounded as necessary. A zero result will
2127 * have a scale of 0.
2128 * @throws ArithmeticException if the result is inexact but the
2129 * rounding mode is {@code UNNECESSARY}.
2130 * @see #round(MathContext)
2133 public BigDecimal plus(MathContext mc) {
2134 if (mc.precision == 0) // no rounding please
2136 return doRound(this, mc);
2140 * Returns the signum function of this {@code BigDecimal}.
2142 * @return -1, 0, or 1 as the value of this {@code BigDecimal}
2143 * is negative, zero, or positive.
2145 public int signum() {
2146 return (intCompact != INFLATED)?
2147 Long.signum(intCompact):
2152 * Returns the <i>scale</i> of this {@code BigDecimal}. If zero
2153 * or positive, the scale is the number of digits to the right of
2154 * the decimal point. If negative, the unscaled value of the
2155 * number is multiplied by ten to the power of the negation of the
2156 * scale. For example, a scale of {@code -3} means the unscaled
2157 * value is multiplied by 1000.
2159 * @return the scale of this {@code BigDecimal}.
2161 public int scale() {
2166 * Returns the <i>precision</i> of this {@code BigDecimal}. (The
2167 * precision is the number of digits in the unscaled value.)
2169 * <p>The precision of a zero value is 1.
2171 * @return the precision of this {@code BigDecimal}.
2174 public int precision() {
2175 int result = precision;
2177 long s = intCompact;
2179 result = longDigitLength(s);
2181 result = bigDigitLength(inflate());
2189 * Returns a {@code BigInteger} whose value is the <i>unscaled
2190 * value</i> of this {@code BigDecimal}. (Computes <tt>(this *
2191 * 10<sup>this.scale()</sup>)</tt>.)
2193 * @return the unscaled value of this {@code BigDecimal}.
2196 public BigInteger unscaledValue() {
2197 return this.inflate();
2203 * Rounding mode to round away from zero. Always increments the
2204 * digit prior to a nonzero discarded fraction. Note that this rounding
2205 * mode never decreases the magnitude of the calculated value.
2207 public final static int ROUND_UP = 0;
2210 * Rounding mode to round towards zero. Never increments the digit
2211 * prior to a discarded fraction (i.e., truncates). Note that this
2212 * rounding mode never increases the magnitude of the calculated value.
2214 public final static int ROUND_DOWN = 1;
2217 * Rounding mode to round towards positive infinity. If the
2218 * {@code BigDecimal} is positive, behaves as for
2219 * {@code ROUND_UP}; if negative, behaves as for
2220 * {@code ROUND_DOWN}. Note that this rounding mode never
2221 * decreases the calculated value.
2223 public final static int ROUND_CEILING = 2;
2226 * Rounding mode to round towards negative infinity. If the
2227 * {@code BigDecimal} is positive, behave as for
2228 * {@code ROUND_DOWN}; if negative, behave as for
2229 * {@code ROUND_UP}. Note that this rounding mode never
2230 * increases the calculated value.
2232 public final static int ROUND_FLOOR = 3;
2235 * Rounding mode to round towards {@literal "nearest neighbor"}
2236 * unless both neighbors are equidistant, in which case round up.
2237 * Behaves as for {@code ROUND_UP} if the discarded fraction is
2238 * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note
2239 * that this is the rounding mode that most of us were taught in
2242 public final static int ROUND_HALF_UP = 4;
2245 * Rounding mode to round towards {@literal "nearest neighbor"}
2246 * unless both neighbors are equidistant, in which case round
2247 * down. Behaves as for {@code ROUND_UP} if the discarded
2248 * fraction is {@literal >} 0.5; otherwise, behaves as for
2249 * {@code ROUND_DOWN}.
2251 public final static int ROUND_HALF_DOWN = 5;
2254 * Rounding mode to round towards the {@literal "nearest neighbor"}
2255 * unless both neighbors are equidistant, in which case, round
2256 * towards the even neighbor. Behaves as for
2257 * {@code ROUND_HALF_UP} if the digit to the left of the
2258 * discarded fraction is odd; behaves as for
2259 * {@code ROUND_HALF_DOWN} if it's even. Note that this is the
2260 * rounding mode that minimizes cumulative error when applied
2261 * repeatedly over a sequence of calculations.
2263 public final static int ROUND_HALF_EVEN = 6;
2266 * Rounding mode to assert that the requested operation has an exact
2267 * result, hence no rounding is necessary. If this rounding mode is
2268 * specified on an operation that yields an inexact result, an
2269 * {@code ArithmeticException} is thrown.
2271 public final static int ROUND_UNNECESSARY = 7;
2274 // Scaling/Rounding Operations
2277 * Returns a {@code BigDecimal} rounded according to the
2278 * {@code MathContext} settings. If the precision setting is 0 then
2279 * no rounding takes place.
2281 * <p>The effect of this method is identical to that of the
2282 * {@link #plus(MathContext)} method.
2284 * @param mc the context to use.
2285 * @return a {@code BigDecimal} rounded according to the
2286 * {@code MathContext} settings.
2287 * @throws ArithmeticException if the rounding mode is
2288 * {@code UNNECESSARY} and the
2289 * {@code BigDecimal} operation would require rounding.
2290 * @see #plus(MathContext)
2293 public BigDecimal round(MathContext mc) {
2298 * Returns a {@code BigDecimal} whose scale is the specified
2299 * value, and whose unscaled value is determined by multiplying or
2300 * dividing this {@code BigDecimal}'s unscaled value by the
2301 * appropriate power of ten to maintain its overall value. If the
2302 * scale is reduced by the operation, the unscaled value must be
2303 * divided (rather than multiplied), and the value may be changed;
2304 * in this case, the specified rounding mode is applied to the
2307 * <p>Note that since BigDecimal objects are immutable, calls of
2308 * this method do <i>not</i> result in the original object being
2309 * modified, contrary to the usual convention of having methods
2310 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2311 * Instead, {@code setScale} returns an object with the proper
2312 * scale; the returned object may or may not be newly allocated.
2314 * @param newScale scale of the {@code BigDecimal} value to be returned.
2315 * @param roundingMode The rounding mode to apply.
2316 * @return a {@code BigDecimal} whose scale is the specified value,
2317 * and whose unscaled value is determined by multiplying or
2318 * dividing this {@code BigDecimal}'s unscaled value by the
2319 * appropriate power of ten to maintain its overall value.
2320 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2321 * and the specified scaling operation would require
2326 public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2327 return setScale(newScale, roundingMode.oldMode);
2331 * Returns a {@code BigDecimal} whose scale is the specified
2332 * value, and whose unscaled value is determined by multiplying or
2333 * dividing this {@code BigDecimal}'s unscaled value by the
2334 * appropriate power of ten to maintain its overall value. If the
2335 * scale is reduced by the operation, the unscaled value must be
2336 * divided (rather than multiplied), and the value may be changed;
2337 * in this case, the specified rounding mode is applied to the
2340 * <p>Note that since BigDecimal objects are immutable, calls of
2341 * this method do <i>not</i> result in the original object being
2342 * modified, contrary to the usual convention of having methods
2343 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>.
2344 * Instead, {@code setScale} returns an object with the proper
2345 * scale; the returned object may or may not be newly allocated.
2347 * <p>The new {@link #setScale(int, RoundingMode)} method should
2348 * be used in preference to this legacy method.
2350 * @param newScale scale of the {@code BigDecimal} value to be returned.
2351 * @param roundingMode The rounding mode to apply.
2352 * @return a {@code BigDecimal} whose scale is the specified value,
2353 * and whose unscaled value is determined by multiplying or
2354 * dividing this {@code BigDecimal}'s unscaled value by the
2355 * appropriate power of ten to maintain its overall value.
2356 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2357 * and the specified scaling operation would require
2359 * @throws IllegalArgumentException if {@code roundingMode} does not
2360 * represent a valid rounding mode.
2363 * @see #ROUND_CEILING
2365 * @see #ROUND_HALF_UP
2366 * @see #ROUND_HALF_DOWN
2367 * @see #ROUND_HALF_EVEN
2368 * @see #ROUND_UNNECESSARY
2370 public BigDecimal setScale(int newScale, int roundingMode) {
2371 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
2372 throw new IllegalArgumentException("Invalid rounding mode");
2374 int oldScale = this.scale;
2375 if (newScale == oldScale) // easy case
2377 if (this.signum() == 0) // zero can have any scale
2378 return BigDecimal.valueOf(0, newScale);
2380 long rs = this.intCompact;
2381 if (newScale > oldScale) {
2382 int raise = checkScale((long)newScale - oldScale);
2383 BigInteger rb = null;
2384 if (rs == INFLATED ||
2385 (rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
2386 rb = bigMultiplyPowerTen(raise);
2387 return new BigDecimal(rb, rs, newScale,
2388 (precision > 0) ? precision + raise : 0);
2390 // newScale < oldScale -- drop some digits
2391 // Can't predict the precision due to the effect of rounding.
2392 int drop = checkScale((long)oldScale - newScale);
2393 if (drop < LONG_TEN_POWERS_TABLE.length)
2394 return divideAndRound(rs, this.intVal,
2395 LONG_TEN_POWERS_TABLE[drop], null,
2396 newScale, roundingMode, newScale);
2398 return divideAndRound(rs, this.intVal,
2399 INFLATED, bigTenToThe(drop),
2400 newScale, roundingMode, newScale);
2405 * Returns a {@code BigDecimal} whose scale is the specified
2406 * value, and whose value is numerically equal to this
2407 * {@code BigDecimal}'s. Throws an {@code ArithmeticException}
2408 * if this is not possible.
2410 * <p>This call is typically used to increase the scale, in which
2411 * case it is guaranteed that there exists a {@code BigDecimal}
2412 * of the specified scale and the correct value. The call can
2413 * also be used to reduce the scale if the caller knows that the
2414 * {@code BigDecimal} has sufficiently many zeros at the end of
2415 * its fractional part (i.e., factors of ten in its integer value)
2416 * to allow for the rescaling without changing its value.
2418 * <p>This method returns the same result as the two-argument
2419 * versions of {@code setScale}, but saves the caller the trouble
2420 * of specifying a rounding mode in cases where it is irrelevant.
2422 * <p>Note that since {@code BigDecimal} objects are immutable,
2423 * calls of this method do <i>not</i> result in the original
2424 * object being modified, contrary to the usual convention of
2425 * having methods named <tt>set<i>X</i></tt> mutate field
2426 * <i>{@code X}</i>. Instead, {@code setScale} returns an
2427 * object with the proper scale; the returned object may or may
2428 * not be newly allocated.
2430 * @param newScale scale of the {@code BigDecimal} value to be returned.
2431 * @return a {@code BigDecimal} whose scale is the specified value, and
2432 * whose unscaled value is determined by multiplying or dividing
2433 * this {@code BigDecimal}'s unscaled value by the appropriate
2434 * power of ten to maintain its overall value.
2435 * @throws ArithmeticException if the specified scaling operation would
2437 * @see #setScale(int, int)
2438 * @see #setScale(int, RoundingMode)
2440 public BigDecimal setScale(int newScale) {
2441 return setScale(newScale, ROUND_UNNECESSARY);
2444 // Decimal Point Motion Operations
2447 * Returns a {@code BigDecimal} which is equivalent to this one
2448 * with the decimal point moved {@code n} places to the left. If
2449 * {@code n} is non-negative, the call merely adds {@code n} to
2450 * the scale. If {@code n} is negative, the call is equivalent
2451 * to {@code movePointRight(-n)}. The {@code BigDecimal}
2452 * returned by this call has value <tt>(this ×
2453 * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n,
2456 * @param n number of places to move the decimal point to the left.
2457 * @return a {@code BigDecimal} which is equivalent to this one with the
2458 * decimal point moved {@code n} places to the left.
2459 * @throws ArithmeticException if scale overflows.
2461 public BigDecimal movePointLeft(int n) {
2462 // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
2463 int newScale = checkScale((long)scale + n);
2464 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2465 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2469 * Returns a {@code BigDecimal} which is equivalent to this one
2470 * with the decimal point moved {@code n} places to the right.
2471 * If {@code n} is non-negative, the call merely subtracts
2472 * {@code n} from the scale. If {@code n} is negative, the call
2473 * is equivalent to {@code movePointLeft(-n)}. The
2474 * {@code BigDecimal} returned by this call has value <tt>(this
2475 * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n,
2478 * @param n number of places to move the decimal point to the right.
2479 * @return a {@code BigDecimal} which is equivalent to this one
2480 * with the decimal point moved {@code n} places to the right.
2481 * @throws ArithmeticException if scale overflows.
2483 public BigDecimal movePointRight(int n) {
2484 // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
2485 int newScale = checkScale((long)scale - n);
2486 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
2487 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
2491 * Returns a BigDecimal whose numerical value is equal to
2492 * ({@code this} * 10<sup>n</sup>). The scale of
2493 * the result is {@code (this.scale() - n)}.
2495 * @throws ArithmeticException if the scale would be
2496 * outside the range of a 32-bit integer.
2500 public BigDecimal scaleByPowerOfTen(int n) {
2501 return new BigDecimal(intVal, intCompact,
2502 checkScale((long)scale - n), precision);
2506 * Returns a {@code BigDecimal} which is numerically equal to
2507 * this one but with any trailing zeros removed from the
2508 * representation. For example, stripping the trailing zeros from
2509 * the {@code BigDecimal} value {@code 600.0}, which has
2510 * [{@code BigInteger}, {@code scale}] components equals to
2511 * [6000, 1], yields {@code 6E2} with [{@code BigInteger},
2512 * {@code scale}] components equals to [6, -2]
2514 * @return a numerically equal {@code BigDecimal} with any
2515 * trailing zeros removed.
2518 public BigDecimal stripTrailingZeros() {
2520 BigDecimal result = new BigDecimal(intVal, scale);
2521 result.stripZerosToMatchScale(Long.MIN_VALUE);
2525 // Comparison Operations
2528 * Compares this {@code BigDecimal} with the specified
2529 * {@code BigDecimal}. Two {@code BigDecimal} objects that are
2530 * equal in value but have a different scale (like 2.0 and 2.00)
2531 * are considered equal by this method. This method is provided
2532 * in preference to individual methods for each of the six boolean
2533 * comparison operators ({@literal <}, ==,
2534 * {@literal >}, {@literal >=}, !=, {@literal <=}). The
2535 * suggested idiom for performing these comparisons is:
2536 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
2537 * <<i>op</i>> is one of the six comparison operators.
2539 * @param val {@code BigDecimal} to which this {@code BigDecimal} is
2541 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2542 * less than, equal to, or greater than {@code val}.
2544 public int compareTo(BigDecimal val) {
2545 // Quick path for equal scale and non-inflated case.
2546 if (scale == val.scale) {
2547 long xs = intCompact;
2548 long ys = val.intCompact;
2549 if (xs != INFLATED && ys != INFLATED)
2550 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2552 int xsign = this.signum();
2553 int ysign = val.signum();
2555 return (xsign > ysign) ? 1 : -1;
2558 int cmp = compareMagnitude(val);
2559 return (xsign > 0) ? cmp : -cmp;
2563 * Version of compareTo that ignores sign.
2565 private int compareMagnitude(BigDecimal val) {
2566 // Match scales, avoid unnecessary inflation
2567 long ys = val.intCompact;
2568 long xs = this.intCompact;
2570 return (ys == 0) ? 0 : -1;
2574 int sdiff = this.scale - val.scale;
2576 // Avoid matching scales if the (adjusted) exponents differ
2577 int xae = this.precision() - this.scale; // [-1]
2578 int yae = val.precision() - val.scale; // [-1]
2583 BigInteger rb = null;
2585 if ( (xs == INFLATED ||
2586 (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) &&
2588 rb = bigMultiplyPowerTen(-sdiff);
2589 return rb.compareMagnitude(val.intVal);
2591 } else { // sdiff > 0
2592 if ( (ys == INFLATED ||
2593 (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) &&
2595 rb = val.bigMultiplyPowerTen(sdiff);
2596 return this.intVal.compareMagnitude(rb);
2601 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2602 else if (ys != INFLATED)
2605 return this.intVal.compareMagnitude(val.intVal);
2609 * Compares this {@code BigDecimal} with the specified
2610 * {@code Object} for equality. Unlike {@link
2611 * #compareTo(BigDecimal) compareTo}, this method considers two
2612 * {@code BigDecimal} objects equal only if they are equal in
2613 * value and scale (thus 2.0 is not equal to 2.00 when compared by
2616 * @param x {@code Object} to which this {@code BigDecimal} is
2618 * @return {@code true} if and only if the specified {@code Object} is a
2619 * {@code BigDecimal} whose value and scale are equal to this
2620 * {@code BigDecimal}'s.
2621 * @see #compareTo(java.math.BigDecimal)
2625 public boolean equals(Object x) {
2626 if (!(x instanceof BigDecimal))
2628 BigDecimal xDec = (BigDecimal) x;
2631 if (scale != xDec.scale)
2633 long s = this.intCompact;
2634 long xs = xDec.intCompact;
2635 if (s != INFLATED) {
2637 xs = compactValFor(xDec.intVal);
2639 } else if (xs != INFLATED)
2640 return xs == compactValFor(this.intVal);
2642 return this.inflate().equals(xDec.inflate());
2646 * Returns the minimum of this {@code BigDecimal} and
2649 * @param val value with which the minimum is to be computed.
2650 * @return the {@code BigDecimal} whose value is the lesser of this
2651 * {@code BigDecimal} and {@code val}. If they are equal,
2652 * as defined by the {@link #compareTo(BigDecimal) compareTo}
2653 * method, {@code this} is returned.
2654 * @see #compareTo(java.math.BigDecimal)
2656 public BigDecimal min(BigDecimal val) {
2657 return (compareTo(val) <= 0 ? this : val);
2661 * Returns the maximum of this {@code BigDecimal} and {@code val}.
2663 * @param val value with which the maximum is to be computed.
2664 * @return the {@code BigDecimal} whose value is the greater of this
2665 * {@code BigDecimal} and {@code val}. If they are equal,
2666 * as defined by the {@link #compareTo(BigDecimal) compareTo}
2667 * method, {@code this} is returned.
2668 * @see #compareTo(java.math.BigDecimal)
2670 public BigDecimal max(BigDecimal val) {
2671 return (compareTo(val) >= 0 ? this : val);
2677 * Returns the hash code for this {@code BigDecimal}. Note that
2678 * two {@code BigDecimal} objects that are numerically equal but
2679 * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
2680 * have the same hash code.
2682 * @return hash code for this {@code BigDecimal}.
2683 * @see #equals(Object)
2686 public int hashCode() {
2687 if (intCompact != INFLATED) {
2688 long val2 = (intCompact < 0)? -intCompact : intCompact;
2689 int temp = (int)( ((int)(val2 >>> 32)) * 31 +
2690 (val2 & LONG_MASK));
2691 return 31*((intCompact < 0) ?-temp:temp) + scale;
2693 return 31*intVal.hashCode() + scale;
2696 // Format Converters
2699 * Returns the string representation of this {@code BigDecimal},
2700 * using scientific notation if an exponent is needed.
2702 * <p>A standard canonical string form of the {@code BigDecimal}
2703 * is created as though by the following steps: first, the
2704 * absolute value of the unscaled value of the {@code BigDecimal}
2705 * is converted to a string in base ten using the characters
2706 * {@code '0'} through {@code '9'} with no leading zeros (except
2707 * if its value is zero, in which case a single {@code '0'}
2708 * character is used).
2710 * <p>Next, an <i>adjusted exponent</i> is calculated; this is the
2711 * negated scale, plus the number of characters in the converted
2712 * unscaled value, less one. That is,
2713 * {@code -scale+(ulength-1)}, where {@code ulength} is the
2714 * length of the absolute value of the unscaled value in decimal
2715 * digits (its <i>precision</i>).
2717 * <p>If the scale is greater than or equal to zero and the
2718 * adjusted exponent is greater than or equal to {@code -6}, the
2719 * number will be converted to a character form without using
2720 * exponential notation. In this case, if the scale is zero then
2721 * no decimal point is added and if the scale is positive a
2722 * decimal point will be inserted with the scale specifying the
2723 * number of characters to the right of the decimal point.
2724 * {@code '0'} characters are added to the left of the converted
2725 * unscaled value as necessary. If no character precedes the
2726 * decimal point after this insertion then a conventional
2727 * {@code '0'} character is prefixed.
2729 * <p>Otherwise (that is, if the scale is negative, or the
2730 * adjusted exponent is less than {@code -6}), the number will be
2731 * converted to a character form using exponential notation. In
2732 * this case, if the converted {@code BigInteger} has more than
2733 * one digit a decimal point is inserted after the first digit.
2734 * An exponent in character form is then suffixed to the converted
2735 * unscaled value (perhaps with inserted decimal point); this
2736 * comprises the letter {@code 'E'} followed immediately by the
2737 * adjusted exponent converted to a character form. The latter is
2738 * in base ten, using the characters {@code '0'} through
2739 * {@code '9'} with no leading zeros, and is always prefixed by a
2740 * sign character {@code '-'} (<tt>'\u002D'</tt>) if the
2741 * adjusted exponent is negative, {@code '+'}
2742 * (<tt>'\u002B'</tt>) otherwise).
2744 * <p>Finally, the entire string is prefixed by a minus sign
2745 * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled
2746 * value is less than zero. No sign character is prefixed if the
2747 * unscaled value is zero or positive.
2749 * <p><b>Examples:</b>
2750 * <p>For each representation [<i>unscaled value</i>, <i>scale</i>]
2751 * on the left, the resulting string is shown on the right.
2755 * [123,-1] "1.23E+3"
2756 * [123,-3] "1.23E+5"
2759 * [123,10] "1.23E-8"
2760 * [-123,12] "-1.23E-10"
2766 * <li>There is a one-to-one mapping between the distinguishable
2767 * {@code BigDecimal} values and the result of this conversion.
2768 * That is, every distinguishable {@code BigDecimal} value
2769 * (unscaled value and scale) has a unique string representation
2770 * as a result of using {@code toString}. If that string
2771 * representation is converted back to a {@code BigDecimal} using
2772 * the {@link #BigDecimal(String)} constructor, then the original
2773 * value will be recovered.
2775 * <li>The string produced for a given number is always the same;
2776 * it is not affected by locale. This means that it can be used
2777 * as a canonical string representation for exchanging decimal
2778 * data, or as a key for a Hashtable, etc. Locale-sensitive
2779 * number formatting and parsing is handled by the {@link
2780 * java.text.NumberFormat} class and its subclasses.
2782 * <li>The {@link #toEngineeringString} method may be used for
2783 * presenting numbers with exponents in engineering notation, and the
2784 * {@link #setScale(int,RoundingMode) setScale} method may be used for
2785 * rounding a {@code BigDecimal} so it has a known number of digits after
2786 * the decimal point.
2788 * <li>The digit-to-character mapping provided by
2789 * {@code Character.forDigit} is used.
2793 * @return string representation of this {@code BigDecimal}.
2794 * @see Character#forDigit
2795 * @see #BigDecimal(java.lang.String)
2798 public String toString() {
2799 String sc = stringCache;
2801 stringCache = sc = layoutChars(true);
2806 * Returns a string representation of this {@code BigDecimal},
2807 * using engineering notation if an exponent is needed.
2809 * <p>Returns a string that represents the {@code BigDecimal} as
2810 * described in the {@link #toString()} method, except that if
2811 * exponential notation is used, the power of ten is adjusted to
2812 * be a multiple of three (engineering notation) such that the
2813 * integer part of nonzero values will be in the range 1 through
2814 * 999. If exponential notation is used for zero values, a
2815 * decimal point and one or two fractional zero digits are used so
2816 * that the scale of the zero value is preserved. Note that
2817 * unlike the output of {@link #toString()}, the output of this
2818 * method is <em>not</em> guaranteed to recover the same [integer,
2819 * scale] pair of this {@code BigDecimal} if the output string is
2820 * converting back to a {@code BigDecimal} using the {@linkplain
2821 * #BigDecimal(String) string constructor}. The result of this method meets
2822 * the weaker constraint of always producing a numerically equal
2823 * result from applying the string constructor to the method's output.
2825 * @return string representation of this {@code BigDecimal}, using
2826 * engineering notation if an exponent is needed.
2829 public String toEngineeringString() {
2830 return layoutChars(false);
2834 * Returns a string representation of this {@code BigDecimal}
2835 * without an exponent field. For values with a positive scale,
2836 * the number of digits to the right of the decimal point is used
2837 * to indicate scale. For values with a zero or negative scale,
2838 * the resulting string is generated as if the value were
2839 * converted to a numerically equal value with zero scale and as
2840 * if all the trailing zeros of the zero scale value were present
2843 * The entire string is prefixed by a minus sign character '-'
2844 * (<tt>'\u002D'</tt>) if the unscaled value is less than
2845 * zero. No sign character is prefixed if the unscaled value is
2848 * Note that if the result of this method is passed to the
2849 * {@linkplain #BigDecimal(String) string constructor}, only the
2850 * numerical value of this {@code BigDecimal} will necessarily be
2851 * recovered; the representation of the new {@code BigDecimal}
2852 * may have a different scale. In particular, if this
2853 * {@code BigDecimal} has a negative scale, the string resulting
2854 * from this method will have a scale of zero when processed by
2855 * the string constructor.
2857 * (This method behaves analogously to the {@code toString}
2858 * method in 1.4 and earlier releases.)
2860 * @return a string representation of this {@code BigDecimal}
2861 * without an exponent field.
2864 * @see #toEngineeringString()
2866 public String toPlainString() {
2867 BigDecimal bd = this;
2869 bd = bd.setScale(0);
2871 if (bd.scale == 0) // No decimal point
2872 return bd.intVal.toString();
2873 return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
2876 /* Returns a digit.digit string */
2877 private String getValueString(int signum, String intString, int scale) {
2878 /* Insert decimal point */
2880 int insertionPoint = intString.length() - scale;
2881 if (insertionPoint == 0) { /* Point goes right before intVal */
2882 return (signum<0 ? "-0." : "0.") + intString;
2883 } else if (insertionPoint > 0) { /* Point goes inside intVal */
2884 buf = new StringBuilder(intString);
2885 buf.insert(insertionPoint, '.');
2888 } else { /* We must insert zeros between point and intVal */
2889 buf = new StringBuilder(3-insertionPoint + intString.length());
2890 buf.append(signum<0 ? "-0." : "0.");
2891 for (int i=0; i<-insertionPoint; i++)
2893 buf.append(intString);
2895 return buf.toString();
2899 * Converts this {@code BigDecimal} to a {@code BigInteger}.
2900 * This conversion is analogous to the
2901 * <i>narrowing primitive conversion</i> from {@code double} to
2902 * {@code long} as defined in section 5.1.3 of
2903 * <cite>The Java™ Language Specification</cite>:
2904 * any fractional part of this
2905 * {@code BigDecimal} will be discarded. Note that this
2906 * conversion can lose information about the precision of the
2907 * {@code BigDecimal} value.
2909 * To have an exception thrown if the conversion is inexact (in
2910 * other words if a nonzero fractional part is discarded), use the
2911 * {@link #toBigIntegerExact()} method.
2913 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2915 public BigInteger toBigInteger() {
2916 // force to an integer, quietly
2917 return this.setScale(0, ROUND_DOWN).inflate();
2921 * Converts this {@code BigDecimal} to a {@code BigInteger},
2922 * checking for lost information. An exception is thrown if this
2923 * {@code BigDecimal} has a nonzero fractional part.
2925 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
2926 * @throws ArithmeticException if {@code this} has a nonzero
2930 public BigInteger toBigIntegerExact() {
2931 // round to an integer, with Exception if decimal part non-0
2932 return this.setScale(0, ROUND_UNNECESSARY).inflate();
2936 * Converts this {@code BigDecimal} to a {@code long}.
2937 * This conversion is analogous to the
2938 * <i>narrowing primitive conversion</i> from {@code double} to
2939 * {@code short} as defined in section 5.1.3 of
2940 * <cite>The Java™ Language Specification</cite>:
2941 * any fractional part of this
2942 * {@code BigDecimal} will be discarded, and if the resulting
2943 * "{@code BigInteger}" is too big to fit in a
2944 * {@code long}, only the low-order 64 bits are returned.
2945 * Note that this conversion can lose information about the
2946 * overall magnitude and precision of this {@code BigDecimal} value as well
2947 * as return a result with the opposite sign.
2949 * @return this {@code BigDecimal} converted to a {@code long}.
2951 public long longValue(){
2952 return (intCompact != INFLATED && scale == 0) ?
2954 toBigInteger().longValue();
2958 * Converts this {@code BigDecimal} to a {@code long}, checking
2959 * for lost information. If this {@code BigDecimal} has a
2960 * nonzero fractional part or is out of the possible range for a
2961 * {@code long} result then an {@code ArithmeticException} is
2964 * @return this {@code BigDecimal} converted to a {@code long}.
2965 * @throws ArithmeticException if {@code this} has a nonzero
2966 * fractional part, or will not fit in a {@code long}.
2969 public long longValueExact() {
2970 if (intCompact != INFLATED && scale == 0)
2972 // If more than 19 digits in integer part it cannot possibly fit
2973 if ((precision() - scale) > 19) // [OK for negative scale too]
2974 throw new java.lang.ArithmeticException("Overflow");
2975 // Fastpath zero and < 1.0 numbers (the latter can be very slow
2976 // to round if very small)
2977 if (this.signum() == 0)
2979 if ((this.precision() - this.scale) <= 0)
2980 throw new ArithmeticException("Rounding necessary");
2981 // round to an integer, with Exception if decimal part non-0
2982 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
2983 if (num.precision() >= 19) // need to check carefully
2984 LongOverflow.check(num);
2985 return num.inflate().longValue();
2988 private static class LongOverflow {
2989 /** BigInteger equal to Long.MIN_VALUE. */
2990 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
2992 /** BigInteger equal to Long.MAX_VALUE. */
2993 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
2995 public static void check(BigDecimal num) {
2997 if ((num.intVal.compareTo(LONGMIN) < 0) ||
2998 (num.intVal.compareTo(LONGMAX) > 0))
2999 throw new java.lang.ArithmeticException("Overflow");
3004 * Converts this {@code BigDecimal} to an {@code int}.
3005 * This conversion is analogous to the
3006 * <i>narrowing primitive conversion</i> from {@code double} to
3007 * {@code short} as defined in section 5.1.3 of
3008 * <cite>The Java™ Language Specification</cite>:
3009 * any fractional part of this
3010 * {@code BigDecimal} will be discarded, and if the resulting
3011 * "{@code BigInteger}" is too big to fit in an
3012 * {@code int}, only the low-order 32 bits are returned.
3013 * Note that this conversion can lose information about the
3014 * overall magnitude and precision of this {@code BigDecimal}
3015 * value as well as return a result with the opposite sign.
3017 * @return this {@code BigDecimal} converted to an {@code int}.
3019 public int intValue() {
3020 return (intCompact != INFLATED && scale == 0) ?
3022 toBigInteger().intValue();
3026 * Converts this {@code BigDecimal} to an {@code int}, checking
3027 * for lost information. If this {@code BigDecimal} has a
3028 * nonzero fractional part or is out of the possible range for an
3029 * {@code int} result then an {@code ArithmeticException} is
3032 * @return this {@code BigDecimal} converted to an {@code int}.
3033 * @throws ArithmeticException if {@code this} has a nonzero
3034 * fractional part, or will not fit in an {@code int}.
3037 public int intValueExact() {
3039 num = this.longValueExact(); // will check decimal part
3040 if ((int)num != num)
3041 throw new java.lang.ArithmeticException("Overflow");
3046 * Converts this {@code BigDecimal} to a {@code short}, checking
3047 * for lost information. If this {@code BigDecimal} has a
3048 * nonzero fractional part or is out of the possible range for a
3049 * {@code short} result then an {@code ArithmeticException} is
3052 * @return this {@code BigDecimal} converted to a {@code short}.
3053 * @throws ArithmeticException if {@code this} has a nonzero
3054 * fractional part, or will not fit in a {@code short}.
3057 public short shortValueExact() {
3059 num = this.longValueExact(); // will check decimal part
3060 if ((short)num != num)
3061 throw new java.lang.ArithmeticException("Overflow");
3066 * Converts this {@code BigDecimal} to a {@code byte}, checking
3067 * for lost information. If this {@code BigDecimal} has a
3068 * nonzero fractional part or is out of the possible range for a
3069 * {@code byte} result then an {@code ArithmeticException} is
3072 * @return this {@code BigDecimal} converted to a {@code byte}.
3073 * @throws ArithmeticException if {@code this} has a nonzero
3074 * fractional part, or will not fit in a {@code byte}.
3077 public byte byteValueExact() {
3079 num = this.longValueExact(); // will check decimal part
3080 if ((byte)num != num)
3081 throw new java.lang.ArithmeticException("Overflow");
3086 * Converts this {@code BigDecimal} to a {@code float}.
3087 * This conversion is similar to the
3088 * <i>narrowing primitive conversion</i> from {@code double} to
3089 * {@code float} as defined in section 5.1.3 of
3090 * <cite>The Java™ Language Specification</cite>:
3091 * if this {@code BigDecimal} has too great a
3092 * magnitude to represent as a {@code float}, it will be
3093 * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3094 * Float#POSITIVE_INFINITY} as appropriate. Note that even when
3095 * the return value is finite, this conversion can lose
3096 * information about the precision of the {@code BigDecimal}
3099 * @return this {@code BigDecimal} converted to a {@code float}.
3101 public float floatValue(){
3102 if (scale == 0 && intCompact != INFLATED)
3103 return (float)intCompact;
3104 // Somewhat inefficient, but guaranteed to work.
3105 return Float.parseFloat(this.toString());
3109 * Converts this {@code BigDecimal} to a {@code double}.
3110 * This conversion is similar to the
3111 * <i>narrowing primitive conversion</i> from {@code double} to
3112 * {@code float} as defined in section 5.1.3 of
3113 * <cite>The Java™ Language Specification</cite>:
3114 * if this {@code BigDecimal} has too great a
3115 * magnitude represent as a {@code double}, it will be
3116 * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3117 * Double#POSITIVE_INFINITY} as appropriate. Note that even when
3118 * the return value is finite, this conversion can lose
3119 * information about the precision of the {@code BigDecimal}
3122 * @return this {@code BigDecimal} converted to a {@code double}.
3124 public double doubleValue(){
3125 if (scale == 0 && intCompact != INFLATED)
3126 return (double)intCompact;
3127 // Somewhat inefficient, but guaranteed to work.
3128 return Double.parseDouble(this.toString());
3132 * Returns the size of an ulp, a unit in the last place, of this
3133 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
3134 * value is the positive distance between this value and the
3135 * {@code BigDecimal} value next larger in magnitude with the
3136 * same number of digits. An ulp of a zero value is numerically
3137 * equal to 1 with the scale of {@code this}. The result is
3138 * stored with the same scale as {@code this} so the result
3139 * for zero and nonzero values is equal to {@code [1,
3142 * @return the size of an ulp of {@code this}
3145 public BigDecimal ulp() {
3146 return BigDecimal.valueOf(1, this.scale());
3150 // Private class to build a string representation for BigDecimal object.
3151 // "StringBuilderHelper" is constructed as a thread local variable so it is
3152 // thread safe. The StringBuilder field acts as a buffer to hold the temporary
3153 // representation of BigDecimal. The cmpCharArray holds all the characters for
3154 // the compact representation of BigDecimal (except for '-' sign' if it is
3155 // negative) if its intCompact field is not INFLATED. It is shared by all
3156 // calls to toString() and its variants in that particular thread.
3157 static class StringBuilderHelper {
3158 private static StringBuilderHelper INSTANCE = new StringBuilderHelper();
3159 final StringBuilder sb; // Placeholder for BigDecimal string
3160 final char[] cmpCharArray; // character array to place the intCompact
3162 StringBuilderHelper() {
3163 sb = new StringBuilder();
3164 // All non negative longs can be made to fit into 19 character array.
3165 cmpCharArray = new char[19];
3169 StringBuilder getStringBuilder() {
3174 char[] getCompactCharArray() {
3175 return cmpCharArray;
3179 * Places characters representing the intCompact in {@code long} into
3180 * cmpCharArray and returns the offset to the array where the
3181 * representation starts.
3183 * @param intCompact the number to put into the cmpCharArray.
3184 * @return offset to the array where the representation starts.
3185 * Note: intCompact must be greater or equal to zero.
3187 int putIntCompact(long intCompact) {
3188 assert intCompact >= 0;
3192 // since we start from the least significant digit, charPos points to
3193 // the last character in cmpCharArray.
3194 int charPos = cmpCharArray.length;
3196 // Get 2 digits/iteration using longs until quotient fits into an int
3197 while (intCompact > Integer.MAX_VALUE) {
3198 q = intCompact / 100;
3199 r = (int)(intCompact - q * 100);
3201 cmpCharArray[--charPos] = DIGIT_ONES[r];
3202 cmpCharArray[--charPos] = DIGIT_TENS[r];
3205 // Get 2 digits/iteration using ints when i2 >= 100
3207 int i2 = (int)intCompact;
3212 cmpCharArray[--charPos] = DIGIT_ONES[r];
3213 cmpCharArray[--charPos] = DIGIT_TENS[r];
3216 cmpCharArray[--charPos] = DIGIT_ONES[i2];
3218 cmpCharArray[--charPos] = DIGIT_TENS[i2];
3223 final static char[] DIGIT_TENS = {
3224 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
3225 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
3226 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
3227 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
3228 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
3229 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
3230 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
3231 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
3232 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
3233 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
3236 final static char[] DIGIT_ONES = {
3237 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3238 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3239 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3240 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3241 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3242 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3243 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3244 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3245 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3246 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
3251 * Lay out this {@code BigDecimal} into a {@code char[]} array.
3252 * The Java 1.2 equivalent to this was called {@code getValueString}.
3254 * @param sci {@code true} for Scientific exponential notation;
3255 * {@code false} for Engineering
3256 * @return string with canonical string representation of this
3257 * {@code BigDecimal}
3259 private String layoutChars(boolean sci) {
3260 if (scale == 0) // zero scale is trivial
3261 return (intCompact != INFLATED) ?
3262 Long.toString(intCompact):
3265 StringBuilderHelper sbHelper = StringBuilderHelper.INSTANCE;
3267 int offset; // offset is the starting index for coeff array
3268 // Get the significand as an absolute value
3269 if (intCompact != INFLATED) {
3270 offset = sbHelper.putIntCompact(Math.abs(intCompact));
3271 coeff = sbHelper.getCompactCharArray();
3274 coeff = intVal.abs().toString().toCharArray();
3277 // Construct a buffer, with sufficient capacity for all cases.
3278 // If E-notation is needed, length will be: +1 if negative, +1
3279 // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent.
3280 // Otherwise it could have +1 if negative, plus leading "0.00000"
3281 StringBuilder buf = sbHelper.getStringBuilder();
3282 if (signum() < 0) // prefix '-' if negative
3284 int coeffLen = coeff.length - offset;
3285 long adjusted = -(long)scale + (coeffLen -1);
3286 if ((scale >= 0) && (adjusted >= -6)) { // plain number
3287 int pad = scale - coeffLen; // count of padding zeros
3288 if (pad >= 0) { // 0.xxx form
3291 for (; pad>0; pad--) {
3294 buf.append(coeff, offset, coeffLen);
3295 } else { // xx.xx form
3296 buf.append(coeff, offset, -pad);
3298 buf.append(coeff, -pad + offset, scale);
3300 } else { // E-notation is needed
3301 if (sci) { // Scientific notation
3302 buf.append(coeff[offset]); // first character
3303 if (coeffLen > 1) { // more to come
3305 buf.append(coeff, offset + 1, coeffLen - 1);
3307 } else { // Engineering notation
3308 int sig = (int)(adjusted % 3);
3310 sig += 3; // [adjusted was negative]
3311 adjusted -= sig; // now a multiple of 3
3313 if (signum() == 0) {
3316 buf.append('0'); // exponent is a multiple of three
3327 throw new AssertionError("Unexpected sig value " + sig);
3329 } else if (sig >= coeffLen) { // significand all in integer
3330 buf.append(coeff, offset, coeffLen);
3331 // may need some zeros, too
3332 for (int i = sig - coeffLen; i > 0; i--)
3334 } else { // xx.xxE form
3335 buf.append(coeff, offset, sig);
3337 buf.append(coeff, offset + sig, coeffLen - sig);
3340 if (adjusted != 0) { // [!sci could have made 0]
3342 if (adjusted > 0) // force sign for positive
3344 buf.append(adjusted);
3347 return buf.toString();
3351 * Return 10 to the power n, as a {@code BigInteger}.
3353 * @param n the power of ten to be returned (>=0)
3354 * @return a {@code BigInteger} with the value (10<sup>n</sup>)
3356 private static BigInteger bigTenToThe(int n) {
3358 return BigInteger.ZERO;
3360 if (n < BIG_TEN_POWERS_TABLE_MAX) {
3361 BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3362 if (n < pows.length)
3365 return expandBigIntegerTenPowers(n);
3367 // BigInteger.pow is slow, so make 10**n by constructing a
3368 // BigInteger from a character string (still not very fast)
3369 char tenpow[] = new char[n + 1];
3371 for (int i = 1; i <= n; i++)
3373 return new BigInteger(tenpow);
3377 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3379 * @param n the power of ten to be returned (>=0)
3380 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3381 * in the meantime, the BIG_TEN_POWERS_TABLE array gets
3382 * expanded to the size greater than n.
3384 private static BigInteger expandBigIntegerTenPowers(int n) {
3385 synchronized(BigDecimal.class) {
3386 BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3387 int curLen = pows.length;
3388 // The following comparison and the above synchronized statement is
3389 // to prevent multiple threads from expanding the same array.
3391 int newLen = curLen << 1;
3394 pows = Arrays.copyOf(pows, newLen);
3395 for (int i = curLen; i < newLen; i++)
3396 pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3397 // Based on the following facts:
3398 // 1. pows is a private local varible;
3399 // 2. the following store is a volatile store.
3400 // the newly created array elements can be safely published.
3401 BIG_TEN_POWERS_TABLE = pows;
3407 private static final long[] LONG_TEN_POWERS_TABLE = {
3414 1000000, // 6 / 10^6
3415 10000000, // 7 / 10^7
3416 100000000, // 8 / 10^8
3417 1000000000, // 9 / 10^9
3418 10000000000L, // 10 / 10^10
3419 100000000000L, // 11 / 10^11
3420 1000000000000L, // 12 / 10^12
3421 10000000000000L, // 13 / 10^13
3422 100000000000000L, // 14 / 10^14
3423 1000000000000000L, // 15 / 10^15
3424 10000000000000000L, // 16 / 10^16
3425 100000000000000000L, // 17 / 10^17
3426 1000000000000000000L // 18 / 10^18
3429 private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE,
3430 BigInteger.valueOf(10), BigInteger.valueOf(100),
3431 BigInteger.valueOf(1000), BigInteger.valueOf(10000),
3432 BigInteger.valueOf(100000), BigInteger.valueOf(1000000),
3433 BigInteger.valueOf(10000000), BigInteger.valueOf(100000000),
3434 BigInteger.valueOf(1000000000),
3435 BigInteger.valueOf(10000000000L),
3436 BigInteger.valueOf(100000000000L),
3437 BigInteger.valueOf(1000000000000L),
3438 BigInteger.valueOf(10000000000000L),
3439 BigInteger.valueOf(100000000000000L),
3440 BigInteger.valueOf(1000000000000000L),
3441 BigInteger.valueOf(10000000000000000L),
3442 BigInteger.valueOf(100000000000000000L),
3443 BigInteger.valueOf(1000000000000000000L)
3446 private static final int BIG_TEN_POWERS_TABLE_INITLEN =
3447 BIG_TEN_POWERS_TABLE.length;
3448 private static final int BIG_TEN_POWERS_TABLE_MAX =
3449 16 * BIG_TEN_POWERS_TABLE_INITLEN;
3451 private static final long THRESHOLDS_TABLE[] = {
3452 Long.MAX_VALUE, // 0
3453 Long.MAX_VALUE/10L, // 1
3454 Long.MAX_VALUE/100L, // 2
3455 Long.MAX_VALUE/1000L, // 3
3456 Long.MAX_VALUE/10000L, // 4
3457 Long.MAX_VALUE/100000L, // 5
3458 Long.MAX_VALUE/1000000L, // 6
3459 Long.MAX_VALUE/10000000L, // 7
3460 Long.MAX_VALUE/100000000L, // 8
3461 Long.MAX_VALUE/1000000000L, // 9
3462 Long.MAX_VALUE/10000000000L, // 10
3463 Long.MAX_VALUE/100000000000L, // 11
3464 Long.MAX_VALUE/1000000000000L, // 12
3465 Long.MAX_VALUE/10000000000000L, // 13
3466 Long.MAX_VALUE/100000000000000L, // 14
3467 Long.MAX_VALUE/1000000000000000L, // 15
3468 Long.MAX_VALUE/10000000000000000L, // 16
3469 Long.MAX_VALUE/100000000000000000L, // 17
3470 Long.MAX_VALUE/1000000000000000000L // 18
3474 * Compute val * 10 ^ n; return this product if it is
3475 * representable as a long, INFLATED otherwise.
3477 private static long longMultiplyPowerTen(long val, int n) {
3478 if (val == 0 || n <= 0)
3480 long[] tab = LONG_TEN_POWERS_TABLE;
3481 long[] bounds = THRESHOLDS_TABLE;
3482 if (n < tab.length && n < bounds.length) {
3483 long tenpower = tab[n];
3486 if (Math.abs(val) <= bounds[n])
3487 return val * tenpower;
3493 * Compute this * 10 ^ n.
3494 * Needed mainly to allow special casing to trap zero value
3496 private BigInteger bigMultiplyPowerTen(int n) {
3498 return this.inflate();
3500 if (intCompact != INFLATED)
3501 return bigTenToThe(n).multiply(intCompact);
3503 return intVal.multiply(bigTenToThe(n));
3507 * Assign appropriate BigInteger to intVal field if intVal is
3508 * null, i.e. the compact representation is in use.
3510 private BigInteger inflate() {
3512 intVal = BigInteger.valueOf(intCompact);
3517 * Match the scales of two {@code BigDecimal}s to align their
3518 * least significant digits.
3520 * <p>If the scales of val[0] and val[1] differ, rescale
3521 * (non-destructively) the lower-scaled {@code BigDecimal} so
3522 * they match. That is, the lower-scaled reference will be
3523 * replaced by a reference to a new object with the same scale as
3524 * the other {@code BigDecimal}.
3526 * @param val array of two elements referring to the two
3527 * {@code BigDecimal}s to be aligned.
3529 private static void matchScale(BigDecimal[] val) {
3530 if (val[0].scale == val[1].scale) {
3532 } else if (val[0].scale < val[1].scale) {
3533 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3534 } else if (val[1].scale < val[0].scale) {
3535 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3540 * Reconstitute the {@code BigDecimal} instance from a stream (that is,
3543 * @param s the stream being read.
3545 private void readObject(java.io.ObjectInputStream s)
3546 throws java.io.IOException, ClassNotFoundException {
3547 // Read in all fields
3548 s.defaultReadObject();
3549 // validate possibly bad fields
3550 if (intVal == null) {
3551 String message = "BigDecimal: null intVal in stream";
3552 throw new java.io.StreamCorruptedException(message);
3553 // [all values of scale are now allowed]
3555 intCompact = compactValFor(intVal);
3559 * Serialize this {@code BigDecimal} to the stream in question
3561 * @param s the stream to serialize to.
3563 private void writeObject(java.io.ObjectOutputStream s)
3564 throws java.io.IOException {
3565 // Must inflate to maintain compatible serial form.
3568 // Write proper fields
3569 s.defaultWriteObject();
3574 * Returns the length of the absolute value of a {@code long}, in decimal
3577 * @param x the {@code long}
3578 * @return the length of the unscaled value, in deciaml digits.
3580 private static int longDigitLength(long x) {
3582 * As described in "Bit Twiddling Hacks" by Sean Anderson,
3583 * (http://graphics.stanford.edu/~seander/bithacks.html)
3584 * integer log 10 of x is within 1 of
3585 * (1233/4096)* (1 + integer log 2 of x).
3586 * The fraction 1233/4096 approximates log10(2). So we first
3587 * do a version of log2 (a variant of Long class with
3588 * pre-checks and opposite directionality) and then scale and
3589 * check against powers table. This is a little simpler in
3590 * present context than the version in Hacker's Delight sec
3591 * 11-4. Adding one to bit length allows comparing downward
3592 * from the LONG_TEN_POWERS_TABLE that we need anyway.
3594 assert x != INFLATED;
3597 if (x < 10) // must screen for 0, might as well 10
3599 int n = 64; // not 63, to avoid needing to add 1 later
3600 int y = (int)(x >>> 32);
3601 if (y == 0) { n -= 32; y = (int)x; }
3602 if (y >>> 16 == 0) { n -= 16; y <<= 16; }
3603 if (y >>> 24 == 0) { n -= 8; y <<= 8; }
3604 if (y >>> 28 == 0) { n -= 4; y <<= 4; }
3605 if (y >>> 30 == 0) { n -= 2; y <<= 2; }
3606 int r = (((y >>> 31) + n) * 1233) >>> 12;
3607 long[] tab = LONG_TEN_POWERS_TABLE;
3608 // if r >= length, must have max possible digits for long
3609 return (r >= tab.length || x < tab[r])? r : r+1;
3613 * Returns the length of the absolute value of a BigInteger, in
3616 * @param b the BigInteger
3617 * @return the length of the unscaled value, in decimal digits
3619 private static int bigDigitLength(BigInteger b) {
3621 * Same idea as the long version, but we need a better
3622 * approximation of log10(2). Using 646456993/2^31
3623 * is accurate up to max possible reported bitLength.
3627 int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31);
3628 return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1;
3633 * Remove insignificant trailing zeros from this
3634 * {@code BigDecimal} until the preferred scale is reached or no
3635 * more zeros can be removed. If the preferred scale is less than
3636 * Integer.MIN_VALUE, all the trailing zeros will be removed.
3638 * {@code BigInteger} assistance could help, here?
3640 * <p>WARNING: This method should only be called on new objects as
3641 * it mutates the value fields.
3643 * @return this {@code BigDecimal} with a scale possibly reduced
3644 * to be closed to the preferred scale.
3646 private BigDecimal stripZerosToMatchScale(long preferredScale) {
3648 BigInteger qr[]; // quotient-remainder pair
3649 while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 &&
3650 scale > preferredScale) {
3651 if (intVal.testBit(0))
3652 break; // odd number cannot end in 0
3653 qr = intVal.divideAndRemainder(BigInteger.TEN);
3654 if (qr[1].signum() != 0)
3655 break; // non-0 remainder
3657 scale = checkScale((long)scale-1); // could Overflow
3658 if (precision > 0) // adjust precision if known
3662 intCompact = compactValFor(intVal);
3667 * Check a scale for Underflow or Overflow. If this BigDecimal is
3668 * nonzero, throw an exception if the scale is outof range. If this
3669 * is zero, saturate the scale to the extreme value of the right
3670 * sign if the scale is out of range.
3672 * @param val The new scale.
3673 * @throws ArithmeticException (overflow or underflow) if the new
3674 * scale is out of range.
3675 * @return validated scale as an int.
3677 private int checkScale(long val) {
3678 int asInt = (int)val;
3680 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE;
3682 if (intCompact != 0 &&
3683 ((b = intVal) == null || b.signum() != 0))
3684 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow");
3690 * Round an operand; used only if digits > 0. Does not change
3691 * {@code this}; if rounding is needed a new {@code BigDecimal}
3692 * is created and returned.
3694 * @param mc the context to use.
3695 * @throws ArithmeticException if the result is inexact but the
3696 * rounding mode is {@code UNNECESSARY}.
3698 private BigDecimal roundOp(MathContext mc) {
3699 BigDecimal rounded = doRound(this, mc);
3703 /** Round this BigDecimal according to the MathContext settings;
3704 * used only if precision {@literal >} 0.
3706 * <p>WARNING: This method should only be called on new objects as
3707 * it mutates the value fields.
3709 * @param mc the context to use.
3710 * @throws ArithmeticException if the rounding mode is
3711 * {@code RoundingMode.UNNECESSARY} and the
3712 * {@code BigDecimal} operation would require rounding.
3714 private void roundThis(MathContext mc) {
3715 BigDecimal rounded = doRound(this, mc);
3716 if (rounded == this) // wasn't rounded
3718 this.intVal = rounded.intVal;
3719 this.intCompact = rounded.intCompact;
3720 this.scale = rounded.scale;
3721 this.precision = rounded.precision;
3725 * Returns a {@code BigDecimal} rounded according to the
3726 * MathContext settings; used only if {@code mc.precision > 0}.
3727 * Does not change {@code this}; if rounding is needed a new
3728 * {@code BigDecimal} is created and returned.
3730 * @param mc the context to use.
3731 * @return a {@code BigDecimal} rounded according to the MathContext
3732 * settings. May return this, if no rounding needed.
3733 * @throws ArithmeticException if the rounding mode is
3734 * {@code RoundingMode.UNNECESSARY} and the
3735 * result is inexact.
3737 private static BigDecimal doRound(BigDecimal d, MathContext mc) {
3738 int mcp = mc.precision;
3740 // This might (rarely) iterate to cover the 999=>1000 case
3741 while ((drop = d.precision() - mcp) > 0) {
3742 int newScale = d.checkScale((long)d.scale - drop);
3743 int mode = mc.roundingMode.oldMode;
3744 if (drop < LONG_TEN_POWERS_TABLE.length)
3745 d = divideAndRound(d.intCompact, d.intVal,
3746 LONG_TEN_POWERS_TABLE[drop], null,
3747 newScale, mode, newScale);
3749 d = divideAndRound(d.intCompact, d.intVal,
3750 INFLATED, bigTenToThe(drop),
3751 newScale, mode, newScale);
3757 * Returns the compact value for given {@code BigInteger}, or
3758 * INFLATED if too big. Relies on internal representation of
3759 * {@code BigInteger}.
3761 private static long compactValFor(BigInteger b) {
3767 if (len > 2 || (len == 2 && d < 0))
3770 long u = (len == 2)?
3771 (((long) m[1] & LONG_MASK) + (((long)d) << 32)) :
3772 (((long)d) & LONG_MASK);
3773 return (b.signum < 0)? -u : u;
3776 private static int longCompareMagnitude(long x, long y) {
3781 return (x < y) ? -1 : ((x == y) ? 0 : 1);
3784 private static int saturateLong(long s) {
3786 return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE);
3790 * Internal printing routine
3792 private static void print(String name, BigDecimal bd) {
3796 * Check internal invariants of this BigDecimal. These invariants
3801 * <li>The object must be initialized; either intCompact must not be
3802 * INFLATED or intVal is non-null. Both of these conditions may
3805 * <li>If both intCompact and intVal and set, their values must be
3808 * <li>If precision is nonzero, it must have the right value.
3811 * Note: Since this is an audit method, we are not supposed to change the
3812 * state of this BigDecimal object.
3814 private BigDecimal audit() {
3815 if (intCompact == INFLATED) {
3816 if (intVal == null) {
3817 print("audit", this);
3818 throw new AssertionError("null intVal");
3821 if (precision > 0 && precision != bigDigitLength(intVal)) {
3822 print("audit", this);
3823 throw new AssertionError("precision mismatch");
3826 if (intVal != null) {
3827 long val = intVal.longValue();
3828 if (val != intCompact) {
3829 print("audit", this);
3830 throw new AssertionError("Inconsistent state, intCompact=" +
3831 intCompact + "\t intVal=" + val);
3835 if (precision > 0 && precision != longDigitLength(intCompact)) {
3836 print("audit", this);
3837 throw new AssertionError("precision mismatch");