BigDecimal.java revision 2362
2362N/A * Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. 0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 0N/A * This code is free software; you can redistribute it and/or modify it 0N/A * under the terms of the GNU General Public License version 2 only, as 2362N/A * published by the Free Software Foundation. Oracle designates this 0N/A * particular file as subject to the "Classpath" exception as provided 2362N/A * by Oracle in the LICENSE file that accompanied this code. 0N/A * This code is distributed in the hope that it will be useful, but WITHOUT 0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 0N/A * version 2 for more details (a copy is included in the LICENSE file that 0N/A * accompanied this code). 0N/A * You should have received a copy of the GNU General Public License version 0N/A * 2 along with this work; if not, write to the Free Software Foundation, 0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 2362N/A * or visit www.oracle.com if you need additional information or have any 0N/A * Portions Copyright IBM Corporation, 2001. All Rights Reserved. 0N/A * Immutable, arbitrary-precision signed decimal numbers. A 0N/A * {@code BigDecimal} consists of an arbitrary precision integer 0N/A * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero 0N/A * or positive, the scale is the number of digits to the right of the 0N/A * decimal point. If negative, the unscaled value of the number is 0N/A * multiplied by ten to the power of the negation of the scale. The 0N/A * value of the number represented by the {@code BigDecimal} is 0N/A * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>. 0N/A * <p>The {@code BigDecimal} class provides operations for 0N/A * arithmetic, scale manipulation, rounding, comparison, hashing, and 0N/A * format conversion. The {@link #toString} method provides a 0N/A * canonical representation of a {@code BigDecimal}. 0N/A * <p>The {@code BigDecimal} class gives its user complete control 0N/A * over rounding behavior. If no rounding mode is specified and the 0N/A * exact result cannot be represented, an exception is thrown; 0N/A * otherwise, calculations can be carried out to a chosen precision 0N/A * and rounding mode by supplying an appropriate {@link MathContext} 0N/A * object to the operation. In either case, eight <em>rounding 0N/A * modes</em> are provided for the control of rounding. Using the 0N/A * integer fields in this class (such as {@link #ROUND_HALF_UP}) to 0N/A * represent rounding mode is largely obsolete; the enumeration values 0N/A * of the {@code RoundingMode} {@code enum}, (such as {@link 0N/A * RoundingMode#HALF_UP}) should be used instead. 0N/A * <p>When a {@code MathContext} object is supplied with a precision 0N/A * setting of 0 (for example, {@link MathContext#UNLIMITED}), 0N/A * arithmetic operations are exact, as are the arithmetic methods 0N/A * which take no {@code MathContext} object. (This is the only 0N/A * behavior that was supported in releases prior to 5.) As a 0N/A * corollary of computing the exact result, the rounding mode setting 0N/A * of a {@code MathContext} object with a precision setting of 0 is 0N/A * not used and thus irrelevant. In the case of divide, the exact 0N/A * quotient could have an infinitely long decimal expansion; for 0N/A * example, 1 divided by 3. If the quotient has a nonterminating 0N/A * decimal expansion and the operation is specified to return an exact 0N/A * result, an {@code ArithmeticException} is thrown. Otherwise, the 0N/A * exact result of the division is returned, as done for other 0N/A * <p>When the precision setting is not 0, the rules of 0N/A * {@code BigDecimal} arithmetic are broadly compatible with selected 0N/A * modes of operation of the arithmetic defined in ANSI X3.274-1996 0N/A * standards, {@code BigDecimal} includes many rounding modes, which 0N/A * were mandatory for division in {@code BigDecimal} releases prior 0N/A * to 5. Any conflicts between these ANSI standards and the 0N/A * {@code BigDecimal} specification are resolved in favor of 0N/A * {@code BigDecimal}. 0N/A * <p>Since the same numerical value can have different 0N/A * representations (with different scales), the rules of arithmetic 0N/A * and rounding must specify both the numerical result and the scale 0N/A * used in the result's representation. 0N/A * <p>In general the rounding modes and precision setting determine 0N/A * how operations return results with a limited number of digits when 0N/A * the exact result has more digits (perhaps infinitely many in the 0N/A * case of division) than the number of digits returned. 0N/A * total number of digits to return is specified by the 0N/A * {@code MathContext}'s {@code precision} setting; this determines 0N/A * the result's <i>precision</i>. The digit count starts from the 0N/A * leftmost nonzero digit of the exact result. The rounding mode 0N/A * determines how any discarded trailing digits affect the returned 0N/A * <p>For all arithmetic operators , the operation is carried out as 0N/A * though an exact intermediate result were first calculated and then 0N/A * rounded to the number of digits specified by the precision setting 0N/A * (if necessary), using the selected rounding mode. If the exact 0N/A * result is not returned, some digit positions of the exact result 0N/A * are discarded. When rounding increases the magnitude of the 0N/A * returned result, it is possible for a new digit position to be 0N/A * created by a carry propagating to a leading {@literal "9"} digit. 0N/A * For example, rounding the value 999.9 to three digits rounding up 0N/A * would be numerically equal to one thousand, represented as 0N/A * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is 0N/A * the leading digit position of the returned result. 0N/A * <p>Besides a logical exact result, each arithmetic operation has a 0N/A * preferred scale for representing a result. The preferred 0N/A * scale for each operation is listed in the table below. 0N/A * <caption top><h3>Preferred Scales for Results of Arithmetic Operations 0N/A * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr> 0N/A * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td> 0N/A * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td> 0N/A * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td> 0N/A * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td> 0N/A * These scales are the ones used by the methods which return exact 0N/A * arithmetic results; except that an exact divide may have to use a 0N/A * larger scale since the exact result may have more digits. For 0N/A * example, {@code 1/32} is {@code 0.03125}. 0N/A * <p>Before rounding, the scale of the logical exact intermediate 0N/A * result is the preferred scale for that operation. If the exact 0N/A * numerical result cannot be represented in {@code precision} 0N/A * digits, rounding selects the set of digits to return and the scale 0N/A * of the result is reduced from the scale of the intermediate result 0N/A * to the least scale which can represent the {@code precision} 0N/A * digits actually returned. If the exact result can be represented 0N/A * with at most {@code precision} digits, the representation 0N/A * of the result with the scale closest to the preferred scale is 0N/A * returned. In particular, an exactly representable quotient may be 0N/A * represented in fewer than {@code precision} digits by removing 0N/A * trailing zeros and decreasing the scale. For example, rounding to 0N/A * three digits using the {@linkplain RoundingMode#FLOOR floor} 0N/A * rounding mode, <br> 0N/A * {@code 19/100 = 0.19 // integer=19, scale=2} <br> 0N/A * {@code 21/110 = 0.190 // integer=190, scale=3} <br> 0N/A * <p>Note that for add, subtract, and multiply, the reduction in 0N/A * scale will equal the number of digit positions of the exact result 0N/A * which are discarded. If the rounding causes a carry propagation to 0N/A * create a new high-order digit position, an additional digit of the 0N/A * result is discarded than when no new digit position is created. 0N/A * <p>Other methods may have slightly different rounding semantics. 0N/A * For example, the result of the {@code pow} method using the 0N/A * {@linkplain #pow(int, MathContext) specified algorithm} can 0N/A * occasionally differ from the rounded mathematical result by more 0N/A * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>. 0N/A * <p>Two types of operations are provided for manipulating the scale 0N/A * #setScale setScale} and {@link #round round}) return a 0N/A * {@code BigDecimal} whose value is approximately (or exactly) equal 0N/A * to that of the operand, but whose scale or precision is the 0N/A * specified value; that is, they increase or decrease the precision 0N/A * of the stored number with minimal effect on its value. Decimal 0N/A * point motion operations ({@link #movePointLeft movePointLeft} and 0N/A * {@link #movePointRight movePointRight}) return a 0N/A * {@code BigDecimal} created from the operand by moving the decimal 0N/A * point a specified distance in the specified direction. 0N/A * <p>For the sake of brevity and clarity, pseudo-code is used 0N/A * throughout the descriptions of {@code BigDecimal} methods. The 0N/A * pseudo-code expression {@code (i + j)} is shorthand for "a 0N/A * {@code BigDecimal} whose value is that of the {@code BigDecimal} 0N/A * {@code i} added to that of the {@code BigDecimal} 0N/A * {@code j}." The pseudo-code expression {@code (i == j)} is 0N/A * shorthand for "{@code true} if and only if the 0N/A * {@code BigDecimal} {@code i} represents the same value as the 0N/A * {@code BigDecimal} {@code j}." Other pseudo-code expressions 0N/A * are interpreted similarly. Square brackets are used to represent 0N/A * the particular {@code BigInteger} and scale pair defining a 0N/A * {@code BigDecimal} value; for example [19, 2] is the 0N/A * {@code BigDecimal} numerically equal to 0.19 having a scale of 2. 0N/A * <p>Note: care should be exercised if {@code BigDecimal} objects 0N/A * are used as keys in a {@link java.util.SortedMap SortedMap} or 0N/A * elements in a {@link java.util.SortedSet SortedSet} since 0N/A * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent 0N/A * with equals</i>. See {@link Comparable}, {@link 0N/A * java.util.SortedMap} or {@link java.util.SortedSet} for more 0N/A * <p>All methods and constructors for this class throw 0N/A * {@code NullPointerException} when passed a {@code null} object 0N/A * reference for any input parameter. 0N/A * @see java.util.SortedMap 0N/A * @see java.util.SortedSet 0N/A * @author Josh Bloch 0N/A * @author Mike Cowlishaw 0N/A * @author Joseph D. Darcy 0N/A * The unscaled value of this BigDecimal, as returned by {@link 0N/A * @see #unscaledValue 0N/A * The scale of this BigDecimal, as returned by {@link #scale}. 1246N/A private int scale;
// Note: this may have any value, so 1246N/A // calculations must be done in longs 0N/A * The number of decimal digits in this BigDecimal, or 0 if the 0N/A * number of digits are not known (lookaside information). If 0N/A * nonzero, the value is guaranteed correct. Use the precision() 0N/A * method to obtain and set the value if it might be 0. This 0N/A * field is mutable until set nonzero. 0N/A * Used to store the canonical string representation, if computed. 0N/A * Sentinel value for {@link #intCompact} indicating the 0N/A * significand information is only available from {@code intVal}. 0N/A * If the absolute value of the significand of this BigDecimal is 0N/A * less than or equal to {@code Long.MAX_VALUE}, the value can be 0N/A * compactly stored in this field and used in computations. 0N/A // All 18-digit base ten strings fit into a long; not all 19-digit 0N/A /* Appease the serialization gods */ 0N/A // Cache of common small BigDecimal values. 1246N/A // Cache of zero scaled by 0 - 15 1598N/A // Half of Long.MIN_VALUE & Long.MAX_VALUE. 0N/A * The value 0, with a scale of 0. 0N/A * The value 1, with a scale of 0. 0N/A * The value 10, with a scale of 0. 1246N/A * Trusted package private constructor. 1246N/A * Trusted simply means if val is INFLATED, intVal could not be null and 1246N/A * if intVal is null, val could not be INFLATED. 0N/A * Translates a character array representation of a 0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the 0N/A * same sequence of characters as the {@link #BigDecimal(String)} 0N/A * constructor, while allowing a sub-array to be specified. 0N/A * <p>Note that if the sequence of characters is already available 0N/A * within a character array, using this constructor is faster than 0N/A * converting the {@code char} array to string and using the 0N/A * {@code BigDecimal(String)} constructor . 0N/A * @param in {@code char} array that is the source of characters. 0N/A * @param offset first character in the array to inspect. 0N/A * @param len number of characters to consider. 0N/A * @throws NumberFormatException if {@code in} is not a valid 0N/A * representation of a {@code BigDecimal} or the defined subarray 0N/A * is not wholly within {@code in}. 1246N/A // protect against huge length. 0N/A // This is the primary string to BigDecimal constructor; all 0N/A // incoming strings end up here; it uses explicit (inline) 0N/A // parsing for speed and generates at most one intermediate 1246N/A // (temporary) object (a char[] array) for non-compact case. 1246N/A // Use locals for all fields values until completion 1246N/A long rs =
0;
// the compact value in long 0N/A // use array bounds checking to handle too-long, len == 0, 0N/A boolean isneg =
false;
// assume positive 0N/A isneg =
true;
// leading minus means negative 0N/A // should now be at numeric part of the significand 1246N/A boolean dot =
false;
// true when there is a '.' 1246N/A char c;
// current character 1246N/A // integer significand array & idx is the index to it. The array 1246N/A // is ONLY used when we can't use a compact representation. 1246N/A // First compact case, we need not to preserve the character 1246N/A // and we can just compute the value in place. 1246N/A }
// else digit is a redundant leading zero 1246N/A }
else {
// the unscaled value is likely a BigInteger object. 1246N/A }
// else c must be a redundant leading zero 0N/A // exponent expected 0N/A if ((c !=
'e') && (c !=
'E'))
0N/A if (
len <=
0)
// no exponent digits 0N/A // skip leading zeros in the exponent 0N/A if (
len >
10)
// too many nonzero exponent digits 0N/A // c now holds first digit of exponent 0N/A if (c >=
'0' && c <=
'9') {
0N/A if (v <
0)
// not a digit 0N/A break;
// that was final character 0N/A // Next test is required for backwards compatibility 0N/A break;
// [saves a test] 0N/A // here when no characters left 1246N/A // Adjust scale if exp is not zero. 0N/A if (
exp !=
0) {
// had significant exponent 1246N/A // Can't call checkScale which relies on proper fields value 0N/A // Remove leading zeros from precision (digits count) 0N/A * Translates a character array representation of a 0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the 0N/A * same sequence of characters as the {@link #BigDecimal(String)} 0N/A * constructor, while allowing a sub-array to be specified and 0N/A * with rounding according to the context settings. 0N/A * <p>Note that if the sequence of characters is already available 0N/A * within a character array, using this constructor is faster than 0N/A * converting the {@code char} array to string and using the 0N/A * {@code BigDecimal(String)} constructor . 0N/A * @param in {@code char} array that is the source of characters. 0N/A * @param offset first character in the array to inspect. 0N/A * @param len number of characters to consider.. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * @throws NumberFormatException if {@code in} is not a valid 0N/A * representation of a {@code BigDecimal} or the defined subarray 0N/A * is not wholly within {@code in}. 0N/A * Translates a character array representation of a 0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the 0N/A * same sequence of characters as the {@link #BigDecimal(String)} 0N/A * <p>Note that if the sequence of characters is already available 0N/A * as a character array, using this constructor is faster than 0N/A * converting the {@code char} array to string and using the 0N/A * {@code BigDecimal(String)} constructor . 0N/A * @param in {@code char} array that is the source of characters. 0N/A * @throws NumberFormatException if {@code in} is not a valid 0N/A * representation of a {@code BigDecimal}. 0N/A * Translates a character array representation of a 0N/A * {@code BigDecimal} into a {@code BigDecimal}, accepting the 0N/A * same sequence of characters as the {@link #BigDecimal(String)} 0N/A * constructor and with rounding according to the context 0N/A * <p>Note that if the sequence of characters is already available 0N/A * as a character array, using this constructor is faster than 0N/A * converting the {@code char} array to string and using the 0N/A * {@code BigDecimal(String)} constructor . 0N/A * @param in {@code char} array that is the source of characters. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * @throws NumberFormatException if {@code in} is not a valid 0N/A * representation of a {@code BigDecimal}. 0N/A * Translates the string representation of a {@code BigDecimal} 0N/A * into a {@code BigDecimal}. The string representation consists 0N/A * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or 0N/A * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of 0N/A * zero or more decimal digits ("the integer"), optionally 0N/A * followed by a fraction, optionally followed by an exponent. 0N/A * <p>The fraction consists of a decimal point followed by zero 0N/A * or more decimal digits. The string must contain at least one 0N/A * digit in either the integer or the fraction. The number formed 0N/A * by the sign, the integer and the fraction is referred to as the 0N/A * <i>significand</i>. 0N/A * <p>The exponent consists of the character {@code 'e'} 0N/A * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>) 0N/A * followed by one or more decimal digits. The value of the 0N/A * exponent must lie between -{@link Integer#MAX_VALUE} ({@link 0N/A * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive. 0N/A * <p>More formally, the strings this constructor accepts are 0N/A * described by the following grammar: 0N/A * <dt><i>BigDecimalString:</i> 0N/A * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i> 0N/A * <dt><i>Significand:</i> 0N/A * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i> 0N/A * <dd>{@code .} <i>FractionPart</i> 0N/A * <dd><i>IntegerPart</i> 0N/A * <dt><i>IntegerPart: 0N/A * <dt><i>FractionPart: 0N/A * <dd>ExponentIndicator SignedInteger</i> 0N/A * <dt><i>ExponentIndicator:</i> 0N/A * <dt><i>SignedInteger: 0N/A * <dd>Sign<sub>opt</sub> Digits</i> 0N/A * <dd>Digits Digit</i> 0N/A * <dd>any character for which {@link Character#isDigit} 0N/A * returns {@code true}, including 0, 1, 2 ... 0N/A * <p>The scale of the returned {@code BigDecimal} will be the 0N/A * number of digits in the fraction, or zero if the string 0N/A * contains no decimal point, subject to adjustment for any 0N/A * exponent; if the string contains an exponent, the exponent is 0N/A * subtracted from the scale. The value of the resulting scale 0N/A * must lie between {@code Integer.MIN_VALUE} and 0N/A * {@code Integer.MAX_VALUE}, inclusive. 0N/A * <p>The character-to-digit mapping is provided by {@link 0N/A * java.lang.Character#digit} set to convert to radix 10. The 0N/A * String may not contain any extraneous characters (whitespace, 0N/A * <p><b>Examples:</b><br> 0N/A * The value of the returned {@code BigDecimal} is equal to 0N/A * <i>significand</i> × 10<sup> <i>exponent</i></sup>. 0N/A * For each string on the left, the resulting representation 0N/A * [{@code BigInteger}, {@code scale}] is shown on the right. 0N/A * "1.23E+3" [123,-1] 0N/A * "12.3E+7" [123,-6] 0N/A * "-1.23E-12" [-123,14] 0N/A * "1234.5E-4" [12345,5] 0N/A * <p>Note: For values other than {@code float} and 0N/A * {@code double} NaN and ±Infinity, this constructor is 0N/A * compatible with the values returned by {@link Float#toString} 0N/A * and {@link Double#toString}. This is generally the preferred 0N/A * way to convert a {@code float} or {@code double} into a 0N/A * BigDecimal, as it doesn't suffer from the unpredictability of 0N/A * the {@link #BigDecimal(double)} constructor. 0N/A * @param val String representation of {@code BigDecimal}. 0N/A * @throws NumberFormatException if {@code val} is not a valid 0N/A * representation of a {@code BigDecimal}. 0N/A * Translates the string representation of a {@code BigDecimal} 0N/A * into a {@code BigDecimal}, accepting the same strings as the 0N/A * {@link #BigDecimal(String)} constructor, with rounding 0N/A * according to the context settings. 0N/A * @param val string representation of a {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * @throws NumberFormatException if {@code val} is not a valid 0N/A * representation of a BigDecimal. 0N/A * Translates a {@code double} into a {@code BigDecimal} which 0N/A * is the exact decimal representation of the {@code double}'s 0N/A * binary floating-point value. The scale of the returned 0N/A * {@code BigDecimal} is the smallest value such that 0N/A * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 0N/A * The results of this constructor can be somewhat unpredictable. 0N/A * One might assume that writing {@code new BigDecimal(0.1)} in 0N/A * Java creates a {@code BigDecimal} which is exactly equal to 0N/A * 0.1 (an unscaled value of 1, with a scale of 1), but it is 0N/A * 0.1000000000000000055511151231257827021181583404541015625. 0N/A * This is because 0.1 cannot be represented exactly as a 0N/A * {@code double} (or, for that matter, as a binary fraction of 0N/A * any finite length). Thus, the value that is being passed 0N/A * <i>in</i> to the constructor is not exactly equal to 0.1, 0N/A * appearances notwithstanding. 0N/A * The {@code String} constructor, on the other hand, is 0N/A * perfectly predictable: writing {@code new BigDecimal("0.1")} 0N/A * creates a {@code BigDecimal} which is <i>exactly</i> equal to 0N/A * 0.1, as one would expect. Therefore, it is generally 0N/A * recommended that the {@linkplain #BigDecimal(String) 0N/A * <tt>String</tt> constructor} be used in preference to this one. 0N/A * When a {@code double} must be used as a source for a 0N/A * {@code BigDecimal}, note that this constructor provides an 0N/A * exact conversion; it does not give the same result as 0N/A * converting the {@code double} to a {@code String} using the 0N/A * {@link Double#toString(double)} method and then using the 0N/A * {@link #BigDecimal(String)} constructor. To get that result, 0N/A * use the {@code static} {@link #valueOf(double)} method. 0N/A * @param val {@code double} value to be converted to 0N/A * {@code BigDecimal}. 0N/A * @throws NumberFormatException if {@code val} is infinite or NaN. 0N/A // Translate the double into sign, exponent and significand, according 0N/A // to the formulae in JLS, Section 20.10.22. 0N/A // At this point, val == sign * significand * 2**exponent. 0N/A * Special case zero to supress nonterminating normalization 0N/A * and bogus scale calculation. 0N/A // Calculate intVal and scale 0N/A * Translates a {@code double} into a {@code BigDecimal}, with 0N/A * rounding according to the context settings. The scale of the 0N/A * {@code BigDecimal} is the smallest value such that 0N/A * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 0N/A * <p>The results of this constructor can be somewhat unpredictable 0N/A * and its use is generally not recommended; see the notes under 0N/A * the {@link #BigDecimal(double)} constructor. 0N/A * @param val {@code double} value to be converted to 0N/A * {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * RoundingMode is UNNECESSARY. 0N/A * @throws NumberFormatException if {@code val} is infinite or NaN. 0N/A * Translates a {@code BigInteger} into a {@code BigDecimal}. 0N/A * The scale of the {@code BigDecimal} is zero. 0N/A * @param val {@code BigInteger} value to be converted to 0N/A * {@code BigDecimal}. 0N/A * Translates a {@code BigInteger} into a {@code BigDecimal} 0N/A * rounding according to the context settings. The scale of the 0N/A * {@code BigDecimal} is zero. 0N/A * @param val {@code BigInteger} value to be converted to 0N/A * {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Translates a {@code BigInteger} unscaled value and an 0N/A * {@code int} scale into a {@code BigDecimal}. The value of 0N/A * the {@code BigDecimal} is 0N/A * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}. 0N/A * @param scale scale of the {@code BigDecimal}. 0N/A // Negative scales are now allowed 0N/A * Translates a {@code BigInteger} unscaled value and an 0N/A * {@code int} scale into a {@code BigDecimal}, with rounding 0N/A * according to the context settings. The value of the 0N/A * {@code BigDecimal} is <tt>(unscaledVal × 0N/A * 10<sup>-scale</sup>)</tt>, rounded according to the 0N/A * {@code precision} and rounding mode settings. 0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}. 0N/A * @param scale scale of the {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Translates an {@code int} into a {@code BigDecimal}. The 0N/A * scale of the {@code BigDecimal} is zero. 0N/A * @param val {@code int} value to be converted to 0N/A * {@code BigDecimal}. 0N/A * Translates an {@code int} into a {@code BigDecimal}, with 0N/A * rounding according to the context settings. The scale of the 0N/A * {@code BigDecimal}, before any rounding, is zero. 0N/A * @param val {@code int} value to be converted to {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Translates a {@code long} into a {@code BigDecimal}. The 0N/A * scale of the {@code BigDecimal} is zero. 0N/A * @param val {@code long} value to be converted to {@code BigDecimal}. 0N/A * Translates a {@code long} into a {@code BigDecimal}, with 0N/A * rounding according to the context settings. The scale of the 0N/A * {@code BigDecimal}, before any rounding, is zero. 0N/A * @param val {@code long} value to be converted to {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A // Static Factory Methods 0N/A * Translates a {@code long} unscaled value and an 0N/A * {@code int} scale into a {@code BigDecimal}. This 0N/A * {@literal "static factory method"} is provided in preference to 0N/A * a ({@code long}, {@code int}) constructor because it 0N/A * allows for reuse of frequently used {@code BigDecimal} values.. 0N/A * @param unscaledVal unscaled value of the {@code BigDecimal}. 0N/A * @param scale scale of the {@code BigDecimal}. 0N/A * @return a {@code BigDecimal} whose value is 0N/A * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 0N/A * Translates a {@code long} value into a {@code BigDecimal} 0N/A * with a scale of zero. This {@literal "static factory method"} 0N/A * is provided in preference to a ({@code long}) constructor 0N/A * because it allows for reuse of frequently used 0N/A * {@code BigDecimal} values. 0N/A * @param val value of the {@code BigDecimal}. 0N/A * @return a {@code BigDecimal} whose value is {@code val}. 0N/A * Translates a {@code double} into a {@code BigDecimal}, using 0N/A * the {@code double}'s canonical string representation provided 0N/A * by the {@link Double#toString(double)} method. 0N/A * <p><b>Note:</b> This is generally the preferred way to convert 0N/A * a {@code double} (or {@code float}) into a 0N/A * {@code BigDecimal}, as the value returned is equal to that 0N/A * resulting from constructing a {@code BigDecimal} from the 0N/A * result of using {@link Double#toString(double)}. 0N/A * @param val {@code double} to convert to a {@code BigDecimal}. 0N/A * @return a {@code BigDecimal} whose value is equal to or approximately 0N/A * equal to the value of {@code val}. 0N/A * @throws NumberFormatException if {@code val} is infinite or NaN. 0N/A // Reminder: a zero double returns '0.0', so we cannot fastpath 0N/A // to use the constant ZERO. This might be important enough to 0N/A // justify a factory approach, a cache, or a few private 0N/A // constants, later. 0N/A // Arithmetic Operations 0N/A * Returns a {@code BigDecimal} whose value is {@code (this + 0N/A * augend)}, and whose scale is {@code max(this.scale(), 0N/A * @param augend value to be added to this {@code BigDecimal}. 0N/A * @return {@code this + augend} 1246N/A // See "Hacker's Delight" section 2-12 for explanation of 0N/A * Returns a {@code BigDecimal} whose value is {@code (this + augend)}, 0N/A * with rounding according to the context settings. 0N/A * If either number is zero and the precision setting is nonzero then 0N/A * the other number, rounded if necessary, is used as the result. 0N/A * @param augend value to be added to this {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @return {@code this + augend}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A // Could optimize if values are compact 0N/A // If either number is zero then the other number, rounded and 0N/A // scaled if necessary, is used as the result. 0N/A // Could use a factory for zero instead of a new object 1246N/A }
else {
// result.scale < preferredScale 0N/A if (
padding !=
0) {
// scales differ; alignment needed 0N/A * Returns an array of length two, the sum of whose entries is 0N/A * equal to the rounded sum of the {@code BigDecimal} arguments. 0N/A * <p>If the digit positions of the arguments have a sufficient 0N/A * gap between them, the value smaller in magnitude can be 0N/A * condensed into a {@literal "sticky bit"} and the end result will 0N/A * round the same way <em>if</em> the precision of the final 0N/A * result does not include the high order digit of the small 0N/A * magnitude operand. 0N/A * <p>Note that while strictly speaking this is an optimization, 0N/A * it makes a much wider range of additions practical. 0N/A * <p>This corresponds to a pre-shift operation in a fixed 0N/A * precision floating-point adder; this method is complicated by 0N/A * variable precision of the result as determined by the 0N/A * MathContext. A more nuanced operation could implement a 0N/A * {@literal "right shift"} on the smaller magnitude operand so 0N/A * that the number of digits of the smaller operand could be 0N/A * reduced even though the significands partially overlapped. 0N/A }
else {
// lhs is small; augend is big 0N/A * This is the estimated scale of an ulp of the result; it 0N/A * assumes that the result doesn't have a carry-out on a true 0N/A * add (e.g. 999 + 1 => 1000) or any subtractive cancellation 0N/A * on borrowing (e.g. 100 - 1.2 => 98.8) 0N/A * The low-order digit position of big is big.scale(). This 0N/A * is true regardless of whether big has a positive or 0N/A * negative scale. The high-order digit position of small is 0N/A * small.scale - (small.precision() - 1). To do the full 0N/A * condensation, the digit positions of big and small must be 0N/A * disjoint *and* the digit positions of small should not be 0N/A * directly visible in the result. 0N/A // Since addition is symmetric, preserving input order in 0N/A // returned operands doesn't matter 0N/A * Returns a {@code BigDecimal} whose value is {@code (this - 0N/A * subtrahend)}, and whose scale is {@code max(this.scale(), 0N/A * subtrahend.scale())}. 0N/A * @param subtrahend value to be subtracted from this {@code BigDecimal}. 0N/A * @return {@code this - subtrahend} 0N/A * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)}, 0N/A * with rounding according to the context settings. 0N/A * If {@code subtrahend} is zero then this, rounded if necessary, is used as the 0N/A * result. If this is zero then the result is {@code subtrahend.negate(mc)}. 0N/A * @param subtrahend value to be subtracted from this {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @return {@code this - subtrahend}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A // share the special rounding code in add() 0N/A * Returns a {@code BigDecimal} whose value is <tt>(this × 0N/A * multiplicand)</tt>, and whose scale is {@code (this.scale() + 0N/A * multiplicand.scale())}. 0N/A * @param multiplicand value to be multiplied by this {@code BigDecimal}. 0N/A * @return {@code this * multiplicand} 0N/A // Might be able to do a more clever check incorporating the 0N/A // inflated check into the overflow computation. 0N/A * If the product is not an overflowed value, continue 0N/A * to use the compact representation. if either of x or y 0N/A * is INFLATED, the product should also be regarded as 1246N/A * an overflow. Before using the overflow test suggested in 1246N/A * "Hacker's Delight" section 2-12, we perform quick checks 1246N/A * using the precision information to see whether the overflow 1246N/A * would occur since division is expensive on most CPUs. 0N/A * Returns a {@code BigDecimal} whose value is <tt>(this × 0N/A * multiplicand)</tt>, with rounding according to the context settings. 0N/A * @param multiplicand value to be multiplied by this {@code BigDecimal}. 0N/A * @param mc the context to use. 0N/A * @return {@code this * multiplicand}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, and whose scale is as specified. If rounding must 0N/A * be performed to generate a result with the specified scale, the 0N/A * specified rounding mode is applied. 0N/A * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method 0N/A * should be used in preference to this legacy method. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param scale scale of the {@code BigDecimal} quotient to be returned. 0N/A * @param roundingMode rounding mode to apply. 0N/A * @return {@code this / divisor} 0N/A * @throws ArithmeticException if {@code divisor} is zero, 0N/A * {@code roundingMode==ROUND_UNNECESSARY} and 0N/A * the specified scale is insufficient to represent the result 0N/A * of the division exactly. 0N/A * @throws IllegalArgumentException if {@code roundingMode} does not 0N/A * represent a valid rounding mode. 0N/A * @see #ROUND_CEILING 0N/A * @see #ROUND_HALF_UP 0N/A * @see #ROUND_HALF_DOWN 0N/A * @see #ROUND_HALF_EVEN 0N/A * @see #ROUND_UNNECESSARY 0N/A * IMPLEMENTATION NOTE: This method *must* return a new object 1246N/A * since divideAndRound uses divide to generate a value whose 0N/A * scale is then modified. 0N/A * Rescale dividend or divisor (whichever can be "upscaled" to 0N/A * produce correctly scaled quotient). 0N/A * Take care to detect out-of-range scales 1246N/A * Internally used for division operation. The dividend and divisor are 1246N/A * passed both in {@code long} format and {@code BigInteger} format. The 1246N/A * returned {@code BigDecimal} object is the quotient whose scale is set to 1246N/A * the passed in scale. If the remainder is not zero, it will be rounded 1246N/A * based on the passed in roundingMode. Also, if the remainder is zero and 1246N/A * the last parameter, i.e. preferredScale is NOT equal to scale, the 1246N/A * trailing zeros of the result is stripped to match the preferredScale. 1246N/A long q =
0, r =
0;
// store quotient & remainder in long 1246N/A // Descend into mutables for faster remainder checks 1246N/A else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, and whose scale is as specified. If rounding must 0N/A * be performed to generate a result with the specified scale, the 0N/A * specified rounding mode is applied. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param scale scale of the {@code BigDecimal} quotient to be returned. 0N/A * @param roundingMode rounding mode to apply. 0N/A * @return {@code this / divisor} 0N/A * @throws ArithmeticException if {@code divisor} is zero, 0N/A * {@code roundingMode==RoundingMode.UNNECESSARY} and 0N/A * the specified scale is insufficient to represent the result 0N/A * of the division exactly. 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, and whose scale is {@code this.scale()}. If 0N/A * rounding must be performed to generate a result with the given 0N/A * scale, the specified rounding mode is applied. 0N/A * <p>The new {@link #divide(BigDecimal, RoundingMode)} method 0N/A * should be used in preference to this legacy method. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param roundingMode rounding mode to apply. 0N/A * @return {@code this / divisor} 0N/A * @throws ArithmeticException if {@code divisor==0}, or 0N/A * {@code roundingMode==ROUND_UNNECESSARY} and 0N/A * {@code this.scale()} is insufficient to represent the result 0N/A * of the division exactly. 0N/A * @throws IllegalArgumentException if {@code roundingMode} does not 0N/A * represent a valid rounding mode. 0N/A * @see #ROUND_CEILING 0N/A * @see #ROUND_HALF_UP 0N/A * @see #ROUND_HALF_DOWN 0N/A * @see #ROUND_HALF_EVEN 0N/A * @see #ROUND_UNNECESSARY 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, and whose scale is {@code this.scale()}. If 0N/A * rounding must be performed to generate a result with the given 0N/A * scale, the specified rounding mode is applied. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param roundingMode rounding mode to apply. 0N/A * @return {@code this / divisor} 0N/A * @throws ArithmeticException if {@code divisor==0}, or 0N/A * {@code roundingMode==RoundingMode.UNNECESSARY} and 0N/A * {@code this.scale()} is insufficient to represent the result 0N/A * of the division exactly. 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, and whose preferred scale is {@code (this.scale() - 0N/A * divisor.scale())}; if the exact quotient cannot be 0N/A * represented (because it has a non-terminating decimal 0N/A * expansion) an {@code ArithmeticException} is thrown. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @throws ArithmeticException if the exact quotient does not have a 0N/A * terminating decimal expansion 0N/A * @return {@code this / divisor} 0N/A * @author Joseph D. Darcy 0N/A * Handle zero cases first. 0N/A // Calculate preferred scale 0N/A * expansion, the expansion can have no more than 0N/A * (a.precision() + ceil(10*b.precision)/3) digits. 0N/A * Therefore, create a MathContext object with this 0N/A * precision and do a divide with the UNNECESSARY rounding 0N/A "no exact representable decimal result.");
0N/A // divide(BigDecimal, mc) tries to adjust the quotient to 0N/A // the desired one by removing trailing zeros; since the 0N/A // exact divide method does not have an explicit digit 0N/A // limit, we can add zeros too. 0N/A * Returns a {@code BigDecimal} whose value is {@code (this / 0N/A * divisor)}, with rounding according to the context settings. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param mc the context to use. 0N/A * @return {@code this / divisor}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY} or 0N/A * {@code mc.precision == 0} and the quotient has a 0N/A * non-terminating decimal expansion. 0N/A // Now calculate the answer. We use the existing 0N/A // divide-and-round method, but as this rounds to scale we have 0N/A // to normalize the values here to achieve the desired result. 0N/A // For x/y we first handle y=0 and x=0, and then normalize x and 0N/A // y to give x' and y' with the following constraints: 0N/A // (a) 0.1 <= x' < 1 0N/A // (b) x' <= y' < 10*x' 0N/A // Dividing x'/y' with the required scale set to mc.precision then 0N/A // will give a result in the range 0.1 to 1 rounded to exactly 0N/A // the right number of digits (except in the case of a result of 0N/A // 1.000... which can arise when x=y, or when rounding overflows 0N/A // The 1.000... case will reduce properly to 1. 1246N/A // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 1246N/A // In order to find out whether the divide generates the exact result, 1246N/A // we avoid calling the above divide method. 'quotient' holds the 1246N/A // return BigDecimal object whose scale will be set to 'scl'. 1246N/A // doRound, here, only affects 1000000000 case. 0N/A * Returns a {@code BigDecimal} whose value is the integer part 0N/A * of the quotient {@code (this / divisor)} rounded down. The 0N/A * preferred scale of the result is {@code (this.scale() - 0N/A * divisor.scale())}. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @return The integer part of {@code this / divisor}. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A // Calculate preferred scale 0N/A // much faster when this << divisor 0N/A // Perform a divide with enough digits to round to a correct 0N/A // integer value; then remove any fractional digits 0N/A // pad with zeros if necessary 0N/A * Returns a {@code BigDecimal} whose value is the integer part 0N/A * of {@code (this / divisor)}. Since the integer part of the 0N/A * exact quotient does not depend on the rounding mode, the 0N/A * rounding mode does not affect the values returned by this 0N/A * method. The preferred scale of the result is 0N/A * {@code (this.scale() - divisor.scale())}. An 0N/A * {@code ArithmeticException} is thrown if the integer part of 0N/A * the exact quotient needs more than {@code mc.precision} 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param mc the context to use. 0N/A * @return The integer part of {@code this / divisor}. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result 0N/A * requires a precision of more than {@code mc.precision} digits. 0N/A * @author Joseph D. Darcy 0N/A // Calculate preferred scale 0N/A * Perform a normal divide to mc.precision digits. If the 0N/A * remainder has absolute value less than the divisor, the 0N/A * integer portion of the quotient fits into mc.precision 0N/A * digits. Next, remove any fractional digits from the 0N/A * quotient and adjust the scale to the preferred value. 0N/A * Result is an integer. See if quotient represents the 0N/A * full integer portion of the exact quotient; if it does, 0N/A * the computed remainder will be less than the divisor. 0N/A // If the quotient is the full integer value, 0N/A // |dividend-product| < |divisor|. 0N/A * Integer portion of quotient will fit into precision 0N/A * digits; recompute quotient to scale 0 to avoid double 0N/A * rounding and then try to adjust, if necessary. 0N/A // else result.scale() == 0; 0N/A * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}. 0N/A * <p>The remainder is given by 0N/A * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. 0N/A * Note that this is not the modulo operation (the result can be 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @return {@code this % divisor}. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A * Returns a {@code BigDecimal} whose value is {@code (this % 0N/A * divisor)}, with rounding according to the context settings. 0N/A * The {@code MathContext} settings affect the implicit divide 0N/A * used to compute the remainder. The remainder computation 0N/A * itself is by definition exact. Therefore, the remainder may 0N/A * contain more than {@code mc.getPrecision()} digits. 0N/A * <p>The remainder is given by 0N/A * {@code this.subtract(this.divideToIntegralValue(divisor, 0N/A * mc).multiply(divisor))}. Note that this is not the modulo 0N/A * operation (the result can be negative). 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided. 0N/A * @param mc the context to use. 0N/A * @return {@code this % divisor}, rounded as necessary. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 0N/A * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 0N/A * require a precision of more than {@code mc.precision} digits. 0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 0N/A * Returns a two-element {@code BigDecimal} array containing the 0N/A * result of {@code divideToIntegralValue} followed by the result of 0N/A * {@code remainder} on the two operands. 0N/A * <p>Note that if both the integer quotient and remainder are 0N/A * needed, this method is faster than using the 0N/A * {@code divideToIntegralValue} and {@code remainder} methods 0N/A * separately because the division need only be carried out once. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided, 0N/A * and the remainder computed. 0N/A * @return a two element {@code BigDecimal} array: the quotient 0N/A * (the result of {@code divideToIntegralValue}) is the initial element 0N/A * and the remainder is the final element. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 0N/A * @see #remainder(java.math.BigDecimal, java.math.MathContext) 0N/A // we use the identity x = i * y + r to determine r 0N/A * Returns a two-element {@code BigDecimal} array containing the 0N/A * result of {@code divideToIntegralValue} followed by the result of 0N/A * {@code remainder} on the two operands calculated with rounding 0N/A * according to the context settings. 0N/A * <p>Note that if both the integer quotient and remainder are 0N/A * needed, this method is faster than using the 0N/A * {@code divideToIntegralValue} and {@code remainder} methods 0N/A * separately because the division need only be carried out once. 0N/A * @param divisor value by which this {@code BigDecimal} is to be divided, 0N/A * and the remainder computed. 0N/A * @param mc the context to use. 0N/A * @return a two element {@code BigDecimal} array: the quotient 0N/A * (the result of {@code divideToIntegralValue}) is the 0N/A * initial element and the remainder is the final element. 0N/A * @throws ArithmeticException if {@code divisor==0} 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 0N/A * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 0N/A * require a precision of more than {@code mc.precision} digits. 0N/A * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 0N/A * @see #remainder(java.math.BigDecimal, java.math.MathContext) 0N/A * Returns a {@code BigDecimal} whose value is 0N/A * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to 0N/A * unlimited precision. 0N/A * <p>The parameter {@code n} must be in the range 0 through 0N/A * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link 0N/A * Note that future releases may expand the allowable exponent 0N/A * range of this method. 0N/A * @param n power to raise this {@code BigDecimal} to. 0N/A * @return <tt>this<sup>n</sup></tt> 0N/A * @throws ArithmeticException if {@code n} is out of range. 0N/A if (n <
0 || n >
999999999)
0N/A // Don't attempt to support "supernormal" numbers. 0N/A * Returns a {@code BigDecimal} whose value is 0N/A * <tt>(this<sup>n</sup>)</tt>. The current implementation uses 0N/A * the core algorithm defined in ANSI standard X3.274-1996 with 0N/A * rounding according to the context settings. In general, the 0N/A * returned numerical value is within two ulps of the exact 0N/A * numerical value for the chosen precision. Note that future 0N/A * releases may use a different algorithm with a decreased 0N/A * allowable error bound and increased allowable exponent range. 0N/A * <p>The X3.274-1996 algorithm is: 0N/A * <li> An {@code ArithmeticException} exception is thrown if 0N/A * <li>{@code abs(n) > 999999999} 0N/A * <li>{@code mc.precision == 0} and {@code n < 0} 0N/A * <li>{@code mc.precision > 0} and {@code n} has more than 0N/A * {@code mc.precision} decimal digits 0N/A * <li> if {@code n} is zero, {@link #ONE} is returned even if 0N/A * {@code this} is zero, otherwise 0N/A * <li> if {@code n} is positive, the result is calculated via 0N/A * the repeated squaring technique into a single accumulator. 0N/A * The individual multiplications with the accumulator use the 0N/A * same math context settings as in {@code mc} except for a 0N/A * precision increased to {@code mc.precision + elength + 1} 0N/A * where {@code elength} is the number of decimal digits in 0N/A * <li> if {@code n} is negative, the result is calculated as if 0N/A * {@code n} were positive; this value is then divided into one 0N/A * using the working precision specified above. 0N/A * <li> The final value from either the positive or negative case 0N/A * is then rounded to the destination precision. 0N/A * @param n power to raise this {@code BigDecimal} to. 0N/A * @param mc the context to use. 0N/A * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}, or {@code n} is out 0N/A if (n < -
999999999 || n >
999999999)
0N/A return ONE;
// x**0 == 1 in X3.274 0N/A // ready to carry out power calculation... 0N/A boolean seenbit =
false;
// set once we've seen a 1-bit 0N/A for (
int i=
1;;i++) {
// for each bit [top bit ignored] 0N/A if (
mag <
0) {
// top bit is set 0N/A break;
// that was the last bit 0N/A // else (!seenbit) no point in squaring ONE 0N/A // if negative n, calculate the reciprocal using working precision 0N/A if (n<
0)
// [hence mc.precision>0] 0N/A // round to final precision and strip zeros 0N/A * Returns a {@code BigDecimal} whose value is the absolute value 0N/A * of this {@code BigDecimal}, and whose scale is 0N/A * {@code this.scale()}. 0N/A * @return {@code abs(this)} 0N/A * Returns a {@code BigDecimal} whose value is the absolute value 0N/A * of this {@code BigDecimal}, with rounding according to the 0N/A * @param mc the context to use. 0N/A * @return {@code abs(this)}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Returns a {@code BigDecimal} whose value is {@code (-this)}, 0N/A * and whose scale is {@code this.scale()}. 0N/A * @return {@code -this}. 0N/A * Returns a {@code BigDecimal} whose value is {@code (-this)}, 0N/A * with rounding according to the context settings. 0N/A * @param mc the context to use. 0N/A * @return {@code -this}, rounded as necessary. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose 0N/A * scale is {@code this.scale()}. 0N/A * <p>This method, which simply returns this {@code BigDecimal} 0N/A * is included for symmetry with the unary minus method {@link 0N/A * @return {@code this}. 0N/A * Returns a {@code BigDecimal} whose value is {@code (+this)}, 0N/A * with rounding according to the context settings. 0N/A * <p>The effect of this method is identical to that of the {@link 0N/A * #round(MathContext)} method. 0N/A * @param mc the context to use. 0N/A * @return {@code this}, rounded as necessary. A zero result will 0N/A * have a scale of 0. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A * @see #round(MathContext) 0N/A * Returns the signum function of this {@code BigDecimal}. 0N/A * @return -1, 0, or 1 as the value of this {@code BigDecimal} 0N/A * is negative, zero, or positive. 0N/A * Returns the <i>scale</i> of this {@code BigDecimal}. If zero 0N/A * or positive, the scale is the number of digits to the right of 0N/A * the decimal point. If negative, the unscaled value of the 0N/A * number is multiplied by ten to the power of the negation of the 0N/A * scale. For example, a scale of {@code -3} means the unscaled 0N/A * value is multiplied by 1000. 0N/A * @return the scale of this {@code BigDecimal}. 0N/A * Returns the <i>precision</i> of this {@code BigDecimal}. (The 0N/A * precision is the number of digits in the unscaled value.) 0N/A * <p>The precision of a zero value is 1. 0N/A * @return the precision of this {@code BigDecimal}. 0N/A * Returns a {@code BigInteger} whose value is the <i>unscaled 0N/A * value</i> of this {@code BigDecimal}. (Computes <tt>(this * 0N/A * 10<sup>this.scale()</sup>)</tt>.) 0N/A * @return the unscaled value of this {@code BigDecimal}. 0N/A * Rounding mode to round away from zero. Always increments the 0N/A * digit prior to a nonzero discarded fraction. Note that this rounding 0N/A * mode never decreases the magnitude of the calculated value. 0N/A * Rounding mode to round towards zero. Never increments the digit 0N/A * prior to a discarded fraction (i.e., truncates). Note that this 0N/A * rounding mode never increases the magnitude of the calculated value. 0N/A * Rounding mode to round towards positive infinity. If the 0N/A * {@code BigDecimal} is positive, behaves as for 0N/A * {@code ROUND_UP}; if negative, behaves as for 0N/A * {@code ROUND_DOWN}. Note that this rounding mode never 0N/A * decreases the calculated value. 0N/A * Rounding mode to round towards negative infinity. If the 0N/A * {@code BigDecimal} is positive, behave as for 0N/A * {@code ROUND_DOWN}; if negative, behave as for 0N/A * {@code ROUND_UP}. Note that this rounding mode never 0N/A * increases the calculated value. 0N/A * Rounding mode to round towards {@literal "nearest neighbor"} 0N/A * unless both neighbors are equidistant, in which case round up. 0N/A * Behaves as for {@code ROUND_UP} if the discarded fraction is 0N/A * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note 0N/A * that this is the rounding mode that most of us were taught in 0N/A * Rounding mode to round towards {@literal "nearest neighbor"} 0N/A * unless both neighbors are equidistant, in which case round 0N/A * down. Behaves as for {@code ROUND_UP} if the discarded 0N/A * fraction is {@literal >} 0.5; otherwise, behaves as for 0N/A * {@code ROUND_DOWN}. 0N/A * Rounding mode to round towards the {@literal "nearest neighbor"} 0N/A * unless both neighbors are equidistant, in which case, round 0N/A * towards the even neighbor. Behaves as for 0N/A * {@code ROUND_HALF_UP} if the digit to the left of the 0N/A * discarded fraction is odd; behaves as for 0N/A * {@code ROUND_HALF_DOWN} if it's even. Note that this is the 0N/A * rounding mode that minimizes cumulative error when applied 0N/A * repeatedly over a sequence of calculations. 0N/A * Rounding mode to assert that the requested operation has an exact 0N/A * result, hence no rounding is necessary. If this rounding mode is 0N/A * specified on an operation that yields an inexact result, an 0N/A * {@code ArithmeticException} is thrown. 0N/A * Returns a {@code BigDecimal} rounded according to the 0N/A * {@code MathContext} settings. If the precision setting is 0 then 0N/A * no rounding takes place. 0N/A * <p>The effect of this method is identical to that of the 0N/A * {@link #plus(MathContext)} method. 0N/A * @param mc the context to use. 0N/A * @return a {@code BigDecimal} rounded according to the 0N/A * {@code MathContext} settings. 0N/A * @throws ArithmeticException if the rounding mode is 0N/A * {@code UNNECESSARY} and the 0N/A * {@code BigDecimal} operation would require rounding. 0N/A * @see #plus(MathContext) 0N/A * Returns a {@code BigDecimal} whose scale is the specified 0N/A * value, and whose unscaled value is determined by multiplying or 0N/A * dividing this {@code BigDecimal}'s unscaled value by the 0N/A * appropriate power of ten to maintain its overall value. If the 0N/A * scale is reduced by the operation, the unscaled value must be 0N/A * divided (rather than multiplied), and the value may be changed; 0N/A * in this case, the specified rounding mode is applied to the 0N/A * <p>Note that since BigDecimal objects are immutable, calls of 0N/A * this method do <i>not</i> result in the original object being 0N/A * modified, contrary to the usual convention of having methods 0N/A * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 0N/A * Instead, {@code setScale} returns an object with the proper 0N/A * scale; the returned object may or may not be newly allocated. 0N/A * @param newScale scale of the {@code BigDecimal} value to be returned. 0N/A * @param roundingMode The rounding mode to apply. 0N/A * @return a {@code BigDecimal} whose scale is the specified value, 0N/A * and whose unscaled value is determined by multiplying or 0N/A * dividing this {@code BigDecimal}'s unscaled value by the 0N/A * appropriate power of ten to maintain its overall value. 0N/A * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} 0N/A * and the specified scaling operation would require 0N/A * Returns a {@code BigDecimal} whose scale is the specified 0N/A * value, and whose unscaled value is determined by multiplying or 0N/A * dividing this {@code BigDecimal}'s unscaled value by the 0N/A * appropriate power of ten to maintain its overall value. If the 0N/A * scale is reduced by the operation, the unscaled value must be 0N/A * divided (rather than multiplied), and the value may be changed; 0N/A * in this case, the specified rounding mode is applied to the 0N/A * <p>Note that since BigDecimal objects are immutable, calls of 0N/A * this method do <i>not</i> result in the original object being 0N/A * modified, contrary to the usual convention of having methods 0N/A * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 0N/A * Instead, {@code setScale} returns an object with the proper 0N/A * scale; the returned object may or may not be newly allocated. 0N/A * <p>The new {@link #setScale(int, RoundingMode)} method should 0N/A * be used in preference to this legacy method. 0N/A * @param newScale scale of the {@code BigDecimal} value to be returned. 0N/A * @param roundingMode The rounding mode to apply. 0N/A * @return a {@code BigDecimal} whose scale is the specified value, 0N/A * and whose unscaled value is determined by multiplying or 0N/A * dividing this {@code BigDecimal}'s unscaled value by the 0N/A * appropriate power of ten to maintain its overall value. 0N/A * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} 0N/A * and the specified scaling operation would require 0N/A * @throws IllegalArgumentException if {@code roundingMode} does not 0N/A * represent a valid rounding mode. 0N/A * @see #ROUND_CEILING 0N/A * @see #ROUND_HALF_UP 0N/A * @see #ROUND_HALF_DOWN 0N/A * @see #ROUND_HALF_EVEN 0N/A * @see #ROUND_UNNECESSARY 0N/A if (
this.
signum() ==
0)
// zero can have any scale 1246N/A // newScale < oldScale -- drop some digits 1246N/A // Can't predict the precision due to the effect of rounding. 0N/A * Returns a {@code BigDecimal} whose scale is the specified 0N/A * value, and whose value is numerically equal to this 0N/A * {@code BigDecimal}'s. Throws an {@code ArithmeticException} 0N/A * if this is not possible. 0N/A * <p>This call is typically used to increase the scale, in which 0N/A * case it is guaranteed that there exists a {@code BigDecimal} 0N/A * of the specified scale and the correct value. The call can 0N/A * also be used to reduce the scale if the caller knows that the 0N/A * {@code BigDecimal} has sufficiently many zeros at the end of 0N/A * its fractional part (i.e., factors of ten in its integer value) 0N/A * to allow for the rescaling without changing its value. 0N/A * <p>This method returns the same result as the two-argument 0N/A * versions of {@code setScale}, but saves the caller the trouble 0N/A * of specifying a rounding mode in cases where it is irrelevant. 0N/A * <p>Note that since {@code BigDecimal} objects are immutable, 0N/A * calls of this method do <i>not</i> result in the original 0N/A * object being modified, contrary to the usual convention of 0N/A * having methods named <tt>set<i>X</i></tt> mutate field 0N/A * <i>{@code X}</i>. Instead, {@code setScale} returns an 0N/A * object with the proper scale; the returned object may or may 0N/A * not be newly allocated. 0N/A * @param newScale scale of the {@code BigDecimal} value to be returned. 0N/A * @return a {@code BigDecimal} whose scale is the specified value, and 0N/A * whose unscaled value is determined by multiplying or dividing 0N/A * this {@code BigDecimal}'s unscaled value by the appropriate 0N/A * power of ten to maintain its overall value. 0N/A * @throws ArithmeticException if the specified scaling operation would 0N/A * @see #setScale(int, int) 0N/A * @see #setScale(int, RoundingMode) 0N/A // Decimal Point Motion Operations 0N/A * Returns a {@code BigDecimal} which is equivalent to this one 0N/A * with the decimal point moved {@code n} places to the left. If 0N/A * {@code n} is non-negative, the call merely adds {@code n} to 0N/A * the scale. If {@code n} is negative, the call is equivalent 0N/A * to {@code movePointRight(-n)}. The {@code BigDecimal} 0N/A * returned by this call has value <tt>(this × 0N/A * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, 0N/A * @param n number of places to move the decimal point to the left. 0N/A * @return a {@code BigDecimal} which is equivalent to this one with the 0N/A * decimal point moved {@code n} places to the left. 0N/A * @throws ArithmeticException if scale overflows. 0N/A // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE 0N/A * Returns a {@code BigDecimal} which is equivalent to this one 0N/A * with the decimal point moved {@code n} places to the right. 0N/A * If {@code n} is non-negative, the call merely subtracts 0N/A * {@code n} from the scale. If {@code n} is negative, the call 0N/A * is equivalent to {@code movePointLeft(-n)}. The 0N/A * {@code BigDecimal} returned by this call has value <tt>(this 0N/A * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n, 0N/A * @param n number of places to move the decimal point to the right. 0N/A * @return a {@code BigDecimal} which is equivalent to this one 0N/A * with the decimal point moved {@code n} places to the right. 0N/A * @throws ArithmeticException if scale overflows. 0N/A // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE 0N/A * Returns a BigDecimal whose numerical value is equal to 0N/A * ({@code this} * 10<sup>n</sup>). The scale of 0N/A * the result is {@code (this.scale() - n)}. 0N/A * @throws ArithmeticException if the scale would be 0N/A * outside the range of a 32-bit integer. 0N/A * Returns a {@code BigDecimal} which is numerically equal to 0N/A * this one but with any trailing zeros removed from the 0N/A * representation. For example, stripping the trailing zeros from 0N/A * the {@code BigDecimal} value {@code 600.0}, which has 0N/A * [{@code BigInteger}, {@code scale}] components equals to 0N/A * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, 0N/A * {@code scale}] components equals to [6, -2] 0N/A * @return a numerically equal {@code BigDecimal} with any 0N/A * trailing zeros removed. 0N/A // Comparison Operations 0N/A * Compares this {@code BigDecimal} with the specified 0N/A * {@code BigDecimal}. Two {@code BigDecimal} objects that are 0N/A * equal in value but have a different scale (like 2.0 and 2.00) 0N/A * are considered equal by this method. This method is provided 0N/A * in preference to individual methods for each of the six boolean 0N/A * comparison operators ({@literal <}, ==, 0N/A * {@literal >}, {@literal >=}, !=, {@literal <=}). The 0N/A * suggested idiom for performing these comparisons is: 0N/A * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 0N/A * <<i>op</i>> is one of the six comparison operators. 0N/A * @param val {@code BigDecimal} to which this {@code BigDecimal} is 0N/A * @return -1, 0, or 1 as this {@code BigDecimal} is numerically 0N/A * less than, equal to, or greater than {@code val}. 1246N/A // Quick path for equal scale and non-inflated case. 1246N/A * Version of compareTo that ignores sign. 1246N/A // Match scales, avoid unnecessary inflation 1246N/A // Avoid matching scales if the (adjusted) exponents differ 0N/A * Compares this {@code BigDecimal} with the specified 0N/A * {@code Object} for equality. Unlike {@link 0N/A * #compareTo(BigDecimal) compareTo}, this method considers two 0N/A * {@code BigDecimal} objects equal only if they are equal in 0N/A * value and scale (thus 2.0 is not equal to 2.00 when compared by 0N/A * @param x {@code Object} to which this {@code BigDecimal} is 0N/A * @return {@code true} if and only if the specified {@code Object} is a 0N/A * {@code BigDecimal} whose value and scale are equal to this 0N/A * {@code BigDecimal}'s. 0N/A * @see #compareTo(java.math.BigDecimal) 0N/A * Returns the minimum of this {@code BigDecimal} and 0N/A * @param val value with which the minimum is to be computed. 0N/A * @return the {@code BigDecimal} whose value is the lesser of this 0N/A * {@code BigDecimal} and {@code val}. If they are equal, 0N/A * as defined by the {@link #compareTo(BigDecimal) compareTo} 0N/A * method, {@code this} is returned. 0N/A * @see #compareTo(java.math.BigDecimal) 0N/A * Returns the maximum of this {@code BigDecimal} and {@code val}. 0N/A * @param val value with which the maximum is to be computed. 0N/A * @return the {@code BigDecimal} whose value is the greater of this 0N/A * {@code BigDecimal} and {@code val}. If they are equal, 0N/A * as defined by the {@link #compareTo(BigDecimal) compareTo} 0N/A * method, {@code this} is returned. 0N/A * @see #compareTo(java.math.BigDecimal) 0N/A * Returns the hash code for this {@code BigDecimal}. Note that 0N/A * two {@code BigDecimal} objects that are numerically equal but 0N/A * differ in scale (like 2.0 and 2.00) will generally <i>not</i> 0N/A * have the same hash code. 0N/A * @return hash code for this {@code BigDecimal}. 0N/A * @see #equals(Object) 0N/A // Format Converters 0N/A * Returns the string representation of this {@code BigDecimal}, 0N/A * using scientific notation if an exponent is needed. 0N/A * <p>A standard canonical string form of the {@code BigDecimal} 0N/A * is created as though by the following steps: first, the 0N/A * absolute value of the unscaled value of the {@code BigDecimal} 0N/A * is converted to a string in base ten using the characters 0N/A * {@code '0'} through {@code '9'} with no leading zeros (except 0N/A * if its value is zero, in which case a single {@code '0'} 0N/A * character is used). 0N/A * <p>Next, an <i>adjusted exponent</i> is calculated; this is the 0N/A * negated scale, plus the number of characters in the converted 0N/A * unscaled value, less one. That is, 0N/A * {@code -scale+(ulength-1)}, where {@code ulength} is the 0N/A * length of the absolute value of the unscaled value in decimal 0N/A * digits (its <i>precision</i>). 0N/A * <p>If the scale is greater than or equal to zero and the 0N/A * adjusted exponent is greater than or equal to {@code -6}, the 0N/A * number will be converted to a character form without using 0N/A * exponential notation. In this case, if the scale is zero then 0N/A * no decimal point is added and if the scale is positive a 0N/A * decimal point will be inserted with the scale specifying the 0N/A * number of characters to the right of the decimal point. 0N/A * {@code '0'} characters are added to the left of the converted 0N/A * unscaled value as necessary. If no character precedes the 0N/A * decimal point after this insertion then a conventional 0N/A * {@code '0'} character is prefixed. 0N/A * <p>Otherwise (that is, if the scale is negative, or the 0N/A * adjusted exponent is less than {@code -6}), the number will be 0N/A * converted to a character form using exponential notation. In 0N/A * this case, if the converted {@code BigInteger} has more than 0N/A * one digit a decimal point is inserted after the first digit. 0N/A * An exponent in character form is then suffixed to the converted 0N/A * unscaled value (perhaps with inserted decimal point); this 0N/A * comprises the letter {@code 'E'} followed immediately by the 0N/A * adjusted exponent converted to a character form. The latter is 0N/A * in base ten, using the characters {@code '0'} through 0N/A * {@code '9'} with no leading zeros, and is always prefixed by a 0N/A * sign character {@code '-'} (<tt>'\u002D'</tt>) if the 0N/A * adjusted exponent is negative, {@code '+'} 0N/A * (<tt>'\u002B'</tt>) otherwise). 0N/A * <p>Finally, the entire string is prefixed by a minus sign 0N/A * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled 0N/A * value is less than zero. No sign character is prefixed if the 0N/A * unscaled value is zero or positive. 0N/A * <p><b>Examples:</b> 0N/A * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] 0N/A * on the left, the resulting string is shown on the right. 0N/A * [123,-1] "1.23E+3" 0N/A * [123,-3] "1.23E+5" 0N/A * [123,10] "1.23E-8" 0N/A * [-123,12] "-1.23E-10" 0N/A * <li>There is a one-to-one mapping between the distinguishable 0N/A * {@code BigDecimal} values and the result of this conversion. 0N/A * That is, every distinguishable {@code BigDecimal} value 0N/A * (unscaled value and scale) has a unique string representation 0N/A * as a result of using {@code toString}. If that string 0N/A * representation is converted back to a {@code BigDecimal} using 0N/A * the {@link #BigDecimal(String)} constructor, then the original 0N/A * value will be recovered. 0N/A * <li>The string produced for a given number is always the same; 0N/A * it is not affected by locale. This means that it can be used 0N/A * as a canonical string representation for exchanging decimal 0N/A * data, or as a key for a Hashtable, etc. Locale-sensitive 0N/A * number formatting and parsing is handled by the {@link 0N/A * java.text.NumberFormat} class and its subclasses. 0N/A * <li>The {@link #toEngineeringString} method may be used for 0N/A * presenting numbers with exponents in engineering notation, and the 0N/A * {@link #setScale(int,RoundingMode) setScale} method may be used for 0N/A * rounding a {@code BigDecimal} so it has a known number of digits after 0N/A * the decimal point. 0N/A * <li>The digit-to-character mapping provided by 0N/A * {@code Character.forDigit} is used. 0N/A * @return string representation of this {@code BigDecimal}. 0N/A * @see Character#forDigit 0N/A * @see #BigDecimal(java.lang.String) 0N/A * Returns a string representation of this {@code BigDecimal}, 0N/A * using engineering notation if an exponent is needed. 0N/A * <p>Returns a string that represents the {@code BigDecimal} as 0N/A * described in the {@link #toString()} method, except that if 0N/A * exponential notation is used, the power of ten is adjusted to 0N/A * be a multiple of three (engineering notation) such that the 0N/A * integer part of nonzero values will be in the range 1 through 0N/A * 999. If exponential notation is used for zero values, a 0N/A * decimal point and one or two fractional zero digits are used so 0N/A * that the scale of the zero value is preserved. Note that 0N/A * unlike the output of {@link #toString()}, the output of this 0N/A * method is <em>not</em> guaranteed to recover the same [integer, 0N/A * scale] pair of this {@code BigDecimal} if the output string is 0N/A * converting back to a {@code BigDecimal} using the {@linkplain 0N/A * #BigDecimal(String) string constructor}. The result of this method meets 0N/A * the weaker constraint of always producing a numerically equal 0N/A * result from applying the string constructor to the method's output. 0N/A * @return string representation of this {@code BigDecimal}, using 0N/A * engineering notation if an exponent is needed. 0N/A * Returns a string representation of this {@code BigDecimal} 0N/A * without an exponent field. For values with a positive scale, 0N/A * the number of digits to the right of the decimal point is used 0N/A * to indicate scale. For values with a zero or negative scale, 0N/A * the resulting string is generated as if the value were 0N/A * converted to a numerically equal value with zero scale and as 0N/A * if all the trailing zeros of the zero scale value were present 0N/A * The entire string is prefixed by a minus sign character '-' 0N/A * (<tt>'\u002D'</tt>) if the unscaled value is less than 0N/A * zero. No sign character is prefixed if the unscaled value is 0N/A * Note that if the result of this method is passed to the 0N/A * {@linkplain #BigDecimal(String) string constructor}, only the 0N/A * numerical value of this {@code BigDecimal} will necessarily be 0N/A * recovered; the representation of the new {@code BigDecimal} 0N/A * may have a different scale. In particular, if this 0N/A * {@code BigDecimal} has a negative scale, the string resulting 0N/A * from this method will have a scale of zero when processed by 0N/A * the string constructor. 0N/A * (This method behaves analogously to the {@code toString} 0N/A * method in 1.4 and earlier releases.) 0N/A * @return a string representation of this {@code BigDecimal} 0N/A * without an exponent field. 0N/A * @see #toEngineeringString() 0N/A /* Returns a digit.digit string */ 0N/A /* Insert decimal point */ 0N/A }
else {
/* We must insert zeros between point and intVal */ 0N/A * Converts this {@code BigDecimal} to a {@code BigInteger}. 0N/A * This conversion is analogous to a <a 0N/A * primitive conversion</i></a> from {@code double} to 0N/A * {@code long} as defined in the <a 0N/A * Specification</a>: any fractional part of this 0N/A * {@code BigDecimal} will be discarded. Note that this 0N/A * conversion can lose information about the precision of the 0N/A * {@code BigDecimal} value. 0N/A * To have an exception thrown if the conversion is inexact (in 0N/A * other words if a nonzero fractional part is discarded), use the 0N/A * {@link #toBigIntegerExact()} method. 0N/A * @return this {@code BigDecimal} converted to a {@code BigInteger}. 0N/A // force to an integer, quietly 0N/A * Converts this {@code BigDecimal} to a {@code BigInteger}, 0N/A * checking for lost information. An exception is thrown if this 0N/A * {@code BigDecimal} has a nonzero fractional part. 0N/A * @return this {@code BigDecimal} converted to a {@code BigInteger}. 0N/A * @throws ArithmeticException if {@code this} has a nonzero 0N/A // round to an integer, with Exception if decimal part non-0 0N/A * Converts this {@code BigDecimal} to a {@code long}. This 0N/A * conversion is analogous to a <a 0N/A * primitive conversion</i></a> from {@code double} to 0N/A * {@code short} as defined in the <a 0N/A * Specification</a>: any fractional part of this 0N/A * {@code BigDecimal} will be discarded, and if the resulting 0N/A * "{@code BigInteger}" is too big to fit in a 0N/A * {@code long}, only the low-order 64 bits are returned. 0N/A * Note that this conversion can lose information about the 0N/A * overall magnitude and precision of this {@code BigDecimal} value as well 0N/A * as return a result with the opposite sign. 0N/A * @return this {@code BigDecimal} converted to a {@code long}. 0N/A * Converts this {@code BigDecimal} to a {@code long}, checking 0N/A * for lost information. If this {@code BigDecimal} has a 0N/A * nonzero fractional part or is out of the possible range for a 0N/A * {@code long} result then an {@code ArithmeticException} is 0N/A * @return this {@code BigDecimal} converted to a {@code long}. 0N/A * @throws ArithmeticException if {@code this} has a nonzero 0N/A * fractional part, or will not fit in a {@code long}. 0N/A // If more than 19 digits in integer part it cannot possibly fit 0N/A // Fastpath zero and < 1.0 numbers (the latter can be very slow 0N/A // to round if very small) 0N/A // round to an integer, with Exception if decimal part non-0 0N/A /** BigInteger equal to Long.MIN_VALUE. */ 0N/A /** BigInteger equal to Long.MAX_VALUE. */ 0N/A * Converts this {@code BigDecimal} to an {@code int}. This 0N/A * conversion is analogous to a <a 0N/A * primitive conversion</i></a> from {@code double} to 0N/A * {@code short} as defined in the <a 0N/A * Specification</a>: any fractional part of this 0N/A * {@code BigDecimal} will be discarded, and if the resulting 0N/A * "{@code BigInteger}" is too big to fit in an 0N/A * {@code int}, only the low-order 32 bits are returned. 0N/A * Note that this conversion can lose information about the 0N/A * overall magnitude and precision of this {@code BigDecimal} 0N/A * value as well as return a result with the opposite sign. 0N/A * @return this {@code BigDecimal} converted to an {@code int}. 0N/A * Converts this {@code BigDecimal} to an {@code int}, checking 0N/A * for lost information. If this {@code BigDecimal} has a 0N/A * nonzero fractional part or is out of the possible range for an 0N/A * {@code int} result then an {@code ArithmeticException} is 0N/A * @return this {@code BigDecimal} converted to an {@code int}. 0N/A * @throws ArithmeticException if {@code this} has a nonzero 0N/A * fractional part, or will not fit in an {@code int}. 0N/A * Converts this {@code BigDecimal} to a {@code short}, checking 0N/A * for lost information. If this {@code BigDecimal} has a 0N/A * nonzero fractional part or is out of the possible range for a 0N/A * {@code short} result then an {@code ArithmeticException} is 0N/A * @return this {@code BigDecimal} converted to a {@code short}. 0N/A * @throws ArithmeticException if {@code this} has a nonzero 0N/A * fractional part, or will not fit in a {@code short}. 0N/A * Converts this {@code BigDecimal} to a {@code byte}, checking 0N/A * for lost information. If this {@code BigDecimal} has a 0N/A * nonzero fractional part or is out of the possible range for a 0N/A * {@code byte} result then an {@code ArithmeticException} is 0N/A * @return this {@code BigDecimal} converted to a {@code byte}. 0N/A * @throws ArithmeticException if {@code this} has a nonzero 0N/A * fractional part, or will not fit in a {@code byte}. 0N/A * Converts this {@code BigDecimal} to a {@code float}. 0N/A * This conversion is similar to the <a 0N/A * primitive conversion</i></a> from {@code double} to 0N/A * {@code float} defined in the <a 0N/A * Specification</a>: if this {@code BigDecimal} has too great a 0N/A * magnitude to represent as a {@code float}, it will be 0N/A * converted to {@link Float#NEGATIVE_INFINITY} or {@link 0N/A * Float#POSITIVE_INFINITY} as appropriate. Note that even when 0N/A * the return value is finite, this conversion can lose 0N/A * information about the precision of the {@code BigDecimal} 0N/A * @return this {@code BigDecimal} converted to a {@code float}. 0N/A // Somewhat inefficient, but guaranteed to work. 0N/A * Converts this {@code BigDecimal} to a {@code double}. 0N/A * This conversion is similar to the <a 0N/A * primitive conversion</i></a> from {@code double} to 0N/A * {@code float} as defined in the <a 0N/A * Specification</a>: if this {@code BigDecimal} has too great a 0N/A * magnitude represent as a {@code double}, it will be 0N/A * converted to {@link Double#NEGATIVE_INFINITY} or {@link 0N/A * Double#POSITIVE_INFINITY} as appropriate. Note that even when 0N/A * the return value is finite, this conversion can lose 0N/A * information about the precision of the {@code BigDecimal} 0N/A * @return this {@code BigDecimal} converted to a {@code double}. 0N/A // Somewhat inefficient, but guaranteed to work. 0N/A * Returns the size of an ulp, a unit in the last place, of this 0N/A * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} 0N/A * value is the positive distance between this value and the 0N/A * {@code BigDecimal} value next larger in magnitude with the 0N/A * same number of digits. An ulp of a zero value is numerically 0N/A * equal to 1 with the scale of {@code this}. The result is 0N/A * stored with the same scale as {@code this} so the result 0N/A * for zero and nonzero values is equal to {@code [1, 0N/A * @return the size of an ulp of {@code this} 1246N/A // Private class to build a string representation for BigDecimal object. 1246N/A // "StringBuilderHelper" is constructed as a thread local variable so it is 1246N/A // thread safe. The StringBuilder field acts as a buffer to hold the temporary 1246N/A // representation of BigDecimal. The cmpCharArray holds all the characters for 1246N/A // the compact representation of BigDecimal (except for '-' sign' if it is 1246N/A // negative) if its intCompact field is not INFLATED. It is shared by all 1246N/A // calls to toString() and its variants in that particular thread. 1246N/A // All non negative longs can be made to fit into 19 character array. 1246N/A * Places characters representing the intCompact in {@code long} into 1246N/A * cmpCharArray and returns the offset to the array where the 1246N/A * @param intCompact the number to put into the cmpCharArray. 1246N/A * @return offset to the array where the representation starts. 1246N/A * Note: intCompact must be greater or equal to zero. 1246N/A // since we start from the least significant digit, charPos points to 1246N/A // the last character in cmpCharArray. 1246N/A '0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
'0',
1246N/A '1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
1246N/A '2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
'2',
1246N/A '3',
'3',
'3',
'3',
'3',
'3',
'3',
'3',
'3',
'3',
1246N/A '4',
'4',
'4',
'4',
'4',
'4',
'4',
'4',
'4',
'4',
1246N/A '5',
'5',
'5',
'5',
'5',
'5',
'5',
'5',
'5',
'5',
1246N/A '6',
'6',
'6',
'6',
'6',
'6',
'6',
'6',
'6',
'6',
1246N/A '7',
'7',
'7',
'7',
'7',
'7',
'7',
'7',
'7',
'7',
1246N/A '8',
'8',
'8',
'8',
'8',
'8',
'8',
'8',
'8',
'8',
1246N/A '9',
'9',
'9',
'9',
'9',
'9',
'9',
'9',
'9',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
1246N/A '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
0N/A * Lay out this {@code BigDecimal} into a {@code char[]} array. 0N/A * The Java 1.2 equivalent to this was called {@code getValueString}. 0N/A * @param sci {@code true} for Scientific exponential notation; 0N/A * {@code false} for Engineering 0N/A * @return string with canonical string representation of this 0N/A * {@code BigDecimal} 0N/A if (
scale ==
0)
// zero scale is trivial 1246N/A int offset;
// offset is the starting index for coeff array 0N/A // Get the significand as an absolute value 0N/A // Construct a buffer, with sufficient capacity for all cases. 0N/A // If E-notation is needed, length will be: +1 if negative, +1 0N/A // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. 0N/A // Otherwise it could have +1 if negative, plus leading "0.00000" 0N/A }
else {
// xx.xx form 0N/A }
else {
// E-notation is needed 0N/A if (
sci) {
// Scientific notation 0N/A }
else {
// Engineering notation 0N/A sig +=
3;
// [adjusted was negative] 0N/A // may need some zeros, too 0N/A }
else {
// xx.xxE form 0N/A * Return 10 to the power n, as a {@code BigInteger}. 0N/A * @param n the power of ten to be returned (>=0) 0N/A * @return a {@code BigInteger} with the value (10<sup>n</sup>) 0N/A // BigInteger.pow is slow, so make 10**n by constructing a 0N/A // BigInteger from a character string (still not very fast) 0N/A for (
int i =
1; i <= n; i++)
1246N/A * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. 1246N/A * @param n the power of ten to be returned (>=0) 1246N/A * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and 1246N/A * in the meantime, the BIG_TEN_POWERS_TABLE array gets 1246N/A * expanded to the size greater than n. 1246N/A // The following comparison and the above synchronized statement is 1246N/A // to prevent multiple threads from expanding the same array. 1246N/A // Based on the following facts: 1246N/A // 1. pows is a private local varible; 1246N/A // 2. the following store is a volatile store. 1246N/A // the newly created array elements can be safely published. 1246N/A 10000000000L,
// 10 / 10^10 1246N/A 100000000000L,
// 11 / 10^11 1246N/A 1000000000000L,
// 12 / 10^12 1246N/A 10000000000000L,
// 13 / 10^13 1246N/A 100000000000000L,
// 14 / 10^14 1246N/A 1000000000000000L,
// 15 / 10^15 1246N/A 10000000000000000L,
// 16 / 10^16 1246N/A 100000000000000000L,
// 17 / 10^17 1246N/A 1000000000000000000L // 18 / 10^18 0N/A * Compute val * 10 ^ n; return this product if it is 0N/A * representable as a long, INFLATED otherwise. 1246N/A * Needed mainly to allow special casing to trap zero value 0N/A * Assign appropriate BigInteger to intVal field if intVal is 0N/A * null, i.e. the compact representation is in use. 0N/A * Match the scales of two {@code BigDecimal}s to align their 0N/A * least significant digits. 0N/A * <p>If the scales of val[0] and val[1] differ, rescale 0N/A * (non-destructively) the lower-scaled {@code BigDecimal} so 0N/A * they match. That is, the lower-scaled reference will be 0N/A * replaced by a reference to a new object with the same scale as 0N/A * the other {@code BigDecimal}. 0N/A * @param val array of two elements referring to the two 0N/A * {@code BigDecimal}s to be aligned. 0N/A * Reconstitute the {@code BigDecimal} instance from a stream (that is, 0N/A * @param s the stream being read. 0N/A // Read in all fields 0N/A // validate possibly bad fields 0N/A // [all values of scale are now allowed] 0N/A * Serialize this {@code BigDecimal} to the stream in question 0N/A * @param s the stream to serialize to. 0N/A // Must inflate to maintain compatible serial form. 0N/A // Write proper fields 1246N/A * Returns the length of the absolute value of a {@code long}, in decimal 1246N/A * @param x the {@code long} 1246N/A * @return the length of the unscaled value, in deciaml digits. 1246N/A * As described in "Bit Twiddling Hacks" by Sean Anderson, 1246N/A * integer log 10 of x is within 1 of 1246N/A * (1233/4096)* (1 + integer log 2 of x). 1246N/A * The fraction 1233/4096 approximates log10(2). So we first 1246N/A * do a version of log2 (a variant of Long class with 1246N/A * pre-checks and opposite directionality) and then scale and 1246N/A * check against powers table. This is a little simpler in 1246N/A * present context than the version in Hacker's Delight sec 1246N/A * 11-4. Adding one to bit length allows comparing downward 1246N/A * from the LONG_TEN_POWERS_TABLE that we need anyway. 1246N/A if (x <
10)
// must screen for 0, might as well 10 1246N/A int n =
64;
// not 63, to avoid needing to add 1 later 1246N/A if (y ==
0) { n -=
32; y = (
int)x; }
1246N/A if (y >>>
16 ==
0) { n -=
16; y <<=
16; }
1246N/A if (y >>>
24 ==
0) { n -=
8; y <<=
8; }
1246N/A if (y >>>
28 ==
0) { n -=
4; y <<=
4; }
1246N/A if (y >>>
30 ==
0) { n -=
2; y <<=
2; }
1246N/A int r = (((y >>>
31) + n) *
1233) >>>
12;
1246N/A // if r >= length, must have max possible digits for long 1246N/A * Returns the length of the absolute value of a BigInteger, in 0N/A * @return the length of the unscaled value, in decimal digits 1246N/A * Same idea as the long version, but we need a better 1246N/A * approximation of log10(2). Using 646456993/2^31 1246N/A * is accurate up to max possible reported bitLength. 0N/A * Remove insignificant trailing zeros from this 0N/A * {@code BigDecimal} until the preferred scale is reached or no 0N/A * more zeros can be removed. If the preferred scale is less than 0N/A * Integer.MIN_VALUE, all the trailing zeros will be removed. 0N/A * {@code BigInteger} assistance could help, here? 0N/A * <p>WARNING: This method should only be called on new objects as 0N/A * it mutates the value fields. 0N/A * @return this {@code BigDecimal} with a scale possibly reduced 0N/A * to be closed to the preferred scale. 0N/A break;
// odd number cannot end in 0 0N/A break;
// non-0 remainder 0N/A * Check a scale for Underflow or Overflow. If this BigDecimal is 1246N/A * nonzero, throw an exception if the scale is outof range. If this 1246N/A * is zero, saturate the scale to the extreme value of the right 1246N/A * sign if the scale is out of range. 0N/A * @param val The new scale. 0N/A * @throws ArithmeticException (overflow or underflow) if the new 0N/A * scale is out of range. 0N/A * @return validated scale as an int. 0N/A * Round an operand; used only if digits > 0. Does not change 0N/A * {@code this}; if rounding is needed a new {@code BigDecimal} 0N/A * is created and returned. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the result is inexact but the 0N/A * rounding mode is {@code UNNECESSARY}. 0N/A /** Round this BigDecimal according to the MathContext settings; 0N/A * used only if precision {@literal >} 0. 0N/A * <p>WARNING: This method should only be called on new objects as 0N/A * it mutates the value fields. 0N/A * @param mc the context to use. 0N/A * @throws ArithmeticException if the rounding mode is 0N/A * {@code RoundingMode.UNNECESSARY} and the 0N/A * {@code BigDecimal} operation would require rounding. 0N/A * Returns a {@code BigDecimal} rounded according to the 0N/A * MathContext settings; used only if {@code mc.precision > 0}. 0N/A * Does not change {@code this}; if rounding is needed a new 0N/A * {@code BigDecimal} is created and returned. 0N/A * @param mc the context to use. 0N/A * @return a {@code BigDecimal} rounded according to the MathContext 0N/A * settings. May return this, if no rounding needed. 0N/A * @throws ArithmeticException if the rounding mode is 0N/A * {@code RoundingMode.UNNECESSARY} and the 0N/A * result is inexact. 1246N/A // This might (rarely) iterate to cover the 999=>1000 case 1246N/A * Returns the compact value for given {@code BigInteger}, or 1246N/A * INFLATED if too big. Relies on internal representation of 1246N/A return (x < y) ? -
1 : ((x == y) ?
0 :
1);
0N/A * Internal printing routine 0N/A * Check internal invariants of this BigDecimal. These invariants 0N/A * <li>The object must be initialized; either intCompact must not be 0N/A * INFLATED or intVal is non-null. Both of these conditions may 0N/A * <li>If both intCompact and intVal and set, their values must be 0N/A * <li>If precision is nonzero, it must have the right value. 1246N/A * Note: Since this is an audit method, we are not supposed to change the 1246N/A * state of this BigDecimal object.