38 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
39 * or positive, the scale is the number of digits to the right of the
40 * decimal point. If negative, the unscaled value of the number is
41 * multiplied by ten to the power of the negation of the scale. The
42 * value of the number represented by the {@code BigDecimal} is
43 * therefore <code>(unscaledValue × 10<sup>-scale</sup>)</code>.
44 *
45 * <p>The {@code BigDecimal} class provides operations for
46 * arithmetic, scale manipulation, rounding, comparison, hashing, and
47 * format conversion. The {@link #toString} method provides a
48 * canonical representation of a {@code BigDecimal}.
49 *
50 * <p>The {@code BigDecimal} class gives its user complete control
51 * over rounding behavior. If no rounding mode is specified and the
52 * exact result cannot be represented, an exception is thrown;
53 * otherwise, calculations can be carried out to a chosen precision
54 * and rounding mode by supplying an appropriate {@link MathContext}
55 * object to the operation. In either case, eight <em>rounding
56 * modes</em> are provided for the control of rounding. Using the
57 * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
58 * represent rounding mode is largely obsolete; the enumeration values
59 * of the {@code RoundingMode} {@code enum}, (such as {@link
60 * RoundingMode#HALF_UP}) should be used instead.
61 *
62 * <p>When a {@code MathContext} object is supplied with a precision
63 * setting of 0 (for example, {@link MathContext#UNLIMITED}),
64 * arithmetic operations are exact, as are the arithmetic methods
65 * which take no {@code MathContext} object. (This is the only
66 * behavior that was supported in releases prior to 5.) As a
67 * corollary of computing the exact result, the rounding mode setting
68 * of a {@code MathContext} object with a precision setting of 0 is
69 * not used and thus irrelevant. In the case of divide, the exact
70 * quotient could have an infinitely long decimal expansion; for
71 * example, 1 divided by 3. If the quotient has a nonterminating
72 * decimal expansion and the operation is specified to return an exact
73 * result, an {@code ArithmeticException} is thrown. Otherwise, the
74 * exact result of the division is returned, as done for other
75 * operations.
76 *
77 * <p>When the precision setting is not 0, the rules of
78 * {@code BigDecimal} arithmetic are broadly compatible with selected
79 * modes of operation of the arithmetic defined in ANSI X3.274-1996
80 * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
81 * standards, {@code BigDecimal} includes many rounding modes, which
82 * were mandatory for division in {@code BigDecimal} releases prior
83 * to 5. Any conflicts between these ANSI standards and the
84 * {@code BigDecimal} specification are resolved in favor of
85 * {@code BigDecimal}.
86 *
87 * <p>Since the same numerical value can have different
88 * representations (with different scales), the rules of arithmetic
89 * and rounding must specify both the numerical result and the scale
90 * used in the result's representation.
91 *
92 *
93 * <p>In general the rounding modes and precision setting determine
94 * how operations return results with a limited number of digits when
95 * the exact result has more digits (perhaps infinitely many in the
96 * case of division) than the number of digits returned.
97 *
98 * First, the
99 * total number of digits to return is specified by the
100 * {@code MathContext}'s {@code precision} setting; this determines
101 * the result's <i>precision</i>. The digit count starts from the
102 * leftmost nonzero digit of the exact result. The rounding mode
103 * determines how any discarded trailing digits affect the returned
104 * result.
105 *
106 * <p>For all arithmetic operators , the operation is carried out as
107 * though an exact intermediate result were first calculated and then
108 * rounded to the number of digits specified by the precision setting
109 * (if necessary), using the selected rounding mode. If the exact
110 * result is not returned, some digit positions of the exact result
111 * are discarded. When rounding increases the magnitude of the
112 * returned result, it is possible for a new digit position to be
113 * created by a carry propagating to a leading {@literal "9"} digit.
114 * For example, rounding the value 999.9 to three digits rounding up
115 * would be numerically equal to one thousand, represented as
116 * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
179 * of the stored number with minimal effect on its value. Decimal
180 * point motion operations ({@link #movePointLeft movePointLeft} and
181 * {@link #movePointRight movePointRight}) return a
182 * {@code BigDecimal} created from the operand by moving the decimal
183 * point a specified distance in the specified direction.
184 *
185 * <p>For the sake of brevity and clarity, pseudo-code is used
186 * throughout the descriptions of {@code BigDecimal} methods. The
187 * pseudo-code expression {@code (i + j)} is shorthand for "a
188 * {@code BigDecimal} whose value is that of the {@code BigDecimal}
189 * {@code i} added to that of the {@code BigDecimal}
190 * {@code j}." The pseudo-code expression {@code (i == j)} is
191 * shorthand for "{@code true} if and only if the
192 * {@code BigDecimal} {@code i} represents the same value as the
193 * {@code BigDecimal} {@code j}." Other pseudo-code expressions
194 * are interpreted similarly. Square brackets are used to represent
195 * the particular {@code BigInteger} and scale pair defining a
196 * {@code BigDecimal} value; for example [19, 2] is the
197 * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
198 *
199 * <p>Note: care should be exercised if {@code BigDecimal} objects
200 * are used as keys in a {@link java.util.SortedMap SortedMap} or
201 * elements in a {@link java.util.SortedSet SortedSet} since
202 * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent
203 * with equals</i>. See {@link Comparable}, {@link
204 * java.util.SortedMap} or {@link java.util.SortedSet} for more
205 * information.
206 *
207 * <p>All methods and constructors for this class throw
208 * {@code NullPointerException} when passed a {@code null} object
209 * reference for any input parameter.
210 *
211 * @see BigInteger
212 * @see MathContext
213 * @see RoundingMode
214 * @see java.util.SortedMap
215 * @see java.util.SortedSet
216 * @author Josh Bloch
217 * @author Mike Cowlishaw
218 * @author Joseph D. Darcy
219 * @author Sergey V. Kuksenko
220 */
221 public class BigDecimal extends Number implements Comparable<BigDecimal> {
222 /**
223 * The unscaled value of this BigDecimal, as returned by {@link
224 * #unscaledValue}.
225 *
226 * @serial
227 * @see #unscaledValue
228 */
229 private final BigInteger intVal;
230
360 // Constructors
361
362 /**
363 * Trusted package private constructor.
364 * Trusted simply means if val is INFLATED, intVal could not be null and
365 * if intVal is null, val could not be INFLATED.
366 */
367 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
368 this.scale = scale;
369 this.precision = prec;
370 this.intCompact = val;
371 this.intVal = intVal;
372 }
373
374 /**
375 * Translates a character array representation of a
376 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
377 * same sequence of characters as the {@link #BigDecimal(String)}
378 * constructor, while allowing a sub-array to be specified.
379 *
380 * <p>Note that if the sequence of characters is already available
381 * within a character array, using this constructor is faster than
382 * converting the {@code char} array to string and using the
383 * {@code BigDecimal(String)} constructor .
384 *
385 * @param in {@code char} array that is the source of characters.
386 * @param offset first character in the array to inspect.
387 * @param len number of characters to consider.
388 * @throws NumberFormatException if {@code in} is not a valid
389 * representation of a {@code BigDecimal} or the defined subarray
390 * is not wholly within {@code in}.
391 * @since 1.5
392 */
393 public BigDecimal(char[] in, int offset, int len) {
394 this(in,offset,len,MathContext.UNLIMITED);
395 }
396
397 /**
398 * Translates a character array representation of a
399 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
400 * same sequence of characters as the {@link #BigDecimal(String)}
401 * constructor, while allowing a sub-array to be specified and
402 * with rounding according to the context settings.
403 *
404 * <p>Note that if the sequence of characters is already available
405 * within a character array, using this constructor is faster than
406 * converting the {@code char} array to string and using the
407 * {@code BigDecimal(String)} constructor.
408 *
409 * @param in {@code char} array that is the source of characters.
410 * @param offset first character in the array to inspect.
411 * @param len number of characters to consider..
412 * @param mc the context to use.
413 * @throws ArithmeticException if the result is inexact but the
414 * rounding mode is {@code UNNECESSARY}.
415 * @throws NumberFormatException if {@code in} is not a valid
416 * representation of a {@code BigDecimal} or the defined subarray
417 * is not wholly within {@code in}.
418 * @since 1.5
419 */
420 public BigDecimal(char[] in, int offset, int len, MathContext mc) {
421 // protect against huge length.
422 if (offset + len > in.length || offset < 0)
423 throw new NumberFormatException("Bad offset or len arguments for char[] input.");
424 // This is the primary string to BigDecimal constructor; all
425 // incoming strings end up here; it uses explicit (inline)
426 // parsing for speed and generates at most one intermediate
427 // (temporary) object (a char[] array) for non-compact case.
428
429 // Use locals for all fields values until completion
430 int prec = 0; // record precision value
431 int scl = 0; // record scale value
662 if (v < 0) // not a digit
663 throw new NumberFormatException("Not a digit.");
664 }
665 exp = exp * 10 + v;
666 if (len == 1)
667 break; // that was final character
668 offset++;
669 c = in[offset];
670 }
671 if (negexp) // apply sign
672 exp = -exp;
673 return exp;
674 }
675
676 /**
677 * Translates a character array representation of a
678 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
679 * same sequence of characters as the {@link #BigDecimal(String)}
680 * constructor.
681 *
682 * <p>Note that if the sequence of characters is already available
683 * as a character array, using this constructor is faster than
684 * converting the {@code char} array to string and using the
685 * {@code BigDecimal(String)} constructor .
686 *
687 * @param in {@code char} array that is the source of characters.
688 * @throws NumberFormatException if {@code in} is not a valid
689 * representation of a {@code BigDecimal}.
690 * @since 1.5
691 */
692 public BigDecimal(char[] in) {
693 this(in, 0, in.length);
694 }
695
696 /**
697 * Translates a character array representation of a
698 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
699 * same sequence of characters as the {@link #BigDecimal(String)}
700 * constructor and with rounding according to the context
701 * settings.
702 *
703 * <p>Note that if the sequence of characters is already available
704 * as a character array, using this constructor is faster than
705 * converting the {@code char} array to string and using the
706 * {@code BigDecimal(String)} constructor .
707 *
708 * @param in {@code char} array that is the source of characters.
709 * @param mc the context to use.
710 * @throws ArithmeticException if the result is inexact but the
711 * rounding mode is {@code UNNECESSARY}.
712 * @throws NumberFormatException if {@code in} is not a valid
713 * representation of a {@code BigDecimal}.
714 * @since 1.5
715 */
716 public BigDecimal(char[] in, MathContext mc) {
717 this(in, 0, in.length, mc);
718 }
719
720 /**
721 * Translates the string representation of a {@code BigDecimal}
722 * into a {@code BigDecimal}. The string representation consists
723 * of an optional sign, {@code '+'} (<code> '\u002B'</code>) or
724 * {@code '-'} (<code>'\u002D'</code>), followed by a sequence of
725 * zero or more decimal digits ("the integer"), optionally
726 * followed by a fraction, optionally followed by an exponent.
788 * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
789 * For each string on the left, the resulting representation
790 * [{@code BigInteger}, {@code scale}] is shown on the right.
791 * <pre>
792 * "0" [0,0]
793 * "0.00" [0,2]
794 * "123" [123,0]
795 * "-123" [-123,0]
796 * "1.23E3" [123,-1]
797 * "1.23E+3" [123,-1]
798 * "12.3E+7" [123,-6]
799 * "12.0" [120,1]
800 * "12.3" [123,1]
801 * "0.00123" [123,5]
802 * "-1.23E-12" [-123,14]
803 * "1234.5E-4" [12345,5]
804 * "0E+7" [0,-7]
805 * "-0" [0,0]
806 * </pre>
807 *
808 * <p>Note: For values other than {@code float} and
809 * {@code double} NaN and ±Infinity, this constructor is
810 * compatible with the values returned by {@link Float#toString}
811 * and {@link Double#toString}. This is generally the preferred
812 * way to convert a {@code float} or {@code double} into a
813 * BigDecimal, as it doesn't suffer from the unpredictability of
814 * the {@link #BigDecimal(double)} constructor.
815 *
816 * @param val String representation of {@code BigDecimal}.
817 *
818 * @throws NumberFormatException if {@code val} is not a valid
819 * representation of a {@code BigDecimal}.
820 */
821 public BigDecimal(String val) {
822 this(val.toCharArray(), 0, val.length());
823 }
824
825 /**
826 * Translates the string representation of a {@code BigDecimal}
827 * into a {@code BigDecimal}, accepting the same strings as the
828 * {@link #BigDecimal(String)} constructor, with rounding
842
843 /**
844 * Translates a {@code double} into a {@code BigDecimal} which
845 * is the exact decimal representation of the {@code double}'s
846 * binary floating-point value. The scale of the returned
847 * {@code BigDecimal} is the smallest value such that
848 * <code>(10<sup>scale</sup> × val)</code> is an integer.
849 * <p>
850 * <b>Notes:</b>
851 * <ol>
852 * <li>
853 * The results of this constructor can be somewhat unpredictable.
854 * One might assume that writing {@code new BigDecimal(0.1)} in
855 * Java creates a {@code BigDecimal} which is exactly equal to
856 * 0.1 (an unscaled value of 1, with a scale of 1), but it is
857 * actually equal to
858 * 0.1000000000000000055511151231257827021181583404541015625.
859 * This is because 0.1 cannot be represented exactly as a
860 * {@code double} (or, for that matter, as a binary fraction of
861 * any finite length). Thus, the value that is being passed
862 * <i>in</i> to the constructor is not exactly equal to 0.1,
863 * appearances notwithstanding.
864 *
865 * <li>
866 * The {@code String} constructor, on the other hand, is
867 * perfectly predictable: writing {@code new BigDecimal("0.1")}
868 * creates a {@code BigDecimal} which is <i>exactly</i> equal to
869 * 0.1, as one would expect. Therefore, it is generally
870 * recommended that the {@linkplain #BigDecimal(String)
871 * String constructor} be used in preference to this one.
872 *
873 * <li>
874 * When a {@code double} must be used as a source for a
875 * {@code BigDecimal}, note that this constructor provides an
876 * exact conversion; it does not give the same result as
877 * converting the {@code double} to a {@code String} using the
878 * {@link Double#toString(double)} method and then using the
879 * {@link #BigDecimal(String)} constructor. To get that result,
880 * use the {@code static} {@link #valueOf(double)} method.
881 * </ol>
882 *
883 * @param val {@code double} value to be converted to
884 * {@code BigDecimal}.
885 * @throws NumberFormatException if {@code val} is infinite or NaN.
886 */
887 public BigDecimal(double val) {
888 this(val,MathContext.UNLIMITED);
1182 int drop = prec - mcp;
1183 while (drop > 0) {
1184 scl = checkScaleNonZero((long) scl - drop);
1185 val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1186 prec = longDigitLength(val);
1187 drop = prec - mcp;
1188 }
1189 rb = null;
1190 }
1191 }
1192 this.intVal = rb;
1193 this.intCompact = val;
1194 this.scale = scl;
1195 this.precision = prec;
1196 }
1197
1198 // Static Factory Methods
1199
1200 /**
1201 * Translates a {@code long} unscaled value and an
1202 * {@code int} scale into a {@code BigDecimal}. This
1203 * {@literal "static factory method"} is provided in preference to
1204 * a ({@code long}, {@code int}) constructor because it
1205 * allows for reuse of frequently used {@code BigDecimal} values..
1206 *
1207 * @param unscaledVal unscaled value of the {@code BigDecimal}.
1208 * @param scale scale of the {@code BigDecimal}.
1209 * @return a {@code BigDecimal} whose value is
1210 * <code>(unscaledVal × 10<sup>-scale</sup>)</code>.
1211 */
1212 public static BigDecimal valueOf(long unscaledVal, int scale) {
1213 if (scale == 0)
1214 return valueOf(unscaledVal);
1215 else if (unscaledVal == 0) {
1216 return zeroValueOf(scale);
1217 }
1218 return new BigDecimal(unscaledVal == INFLATED ?
1219 INFLATED_BIGINT : null,
1220 unscaledVal, scale, 0);
1221 }
1222
1223 /**
1224 * Translates a {@code long} value into a {@code BigDecimal}
1225 * with a scale of zero. This {@literal "static factory method"}
1226 * is provided in preference to a ({@code long}) constructor
1227 * because it allows for reuse of frequently used
1228 * {@code BigDecimal} values.
1229 *
1230 * @param val value of the {@code BigDecimal}.
1231 * @return a {@code BigDecimal} whose value is {@code val}.
1232 */
1233 public static BigDecimal valueOf(long val) {
1234 if (val >= 0 && val < ZERO_THROUGH_TEN.length)
1235 return ZERO_THROUGH_TEN[(int)val];
1236 else if (val != INFLATED)
1237 return new BigDecimal(null, val, 0, 0);
1238 return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1239 }
1240
1241 static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1242 if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {
1243 return ZERO_THROUGH_TEN[(int) unscaledVal];
1244 } else if (unscaledVal == 0) {
1245 return zeroValueOf(scale);
1246 }
1247 return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1248 unscaledVal, scale, prec);
1253 if (val == 0) {
1254 return zeroValueOf(scale);
1255 } else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {
1256 return ZERO_THROUGH_TEN[(int) val];
1257 }
1258 return new BigDecimal(intVal, val, scale, prec);
1259 }
1260
1261 static BigDecimal zeroValueOf(int scale) {
1262 if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1263 return ZERO_SCALED_BY[scale];
1264 else
1265 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1266 }
1267
1268 /**
1269 * Translates a {@code double} into a {@code BigDecimal}, using
1270 * the {@code double}'s canonical string representation provided
1271 * by the {@link Double#toString(double)} method.
1272 *
1273 * <p><b>Note:</b> This is generally the preferred way to convert
1274 * a {@code double} (or {@code float}) into a
1275 * {@code BigDecimal}, as the value returned is equal to that
1276 * resulting from constructing a {@code BigDecimal} from the
1277 * result of using {@link Double#toString(double)}.
1278 *
1279 * @param val {@code double} to convert to a {@code BigDecimal}.
1280 * @return a {@code BigDecimal} whose value is equal to or approximately
1281 * equal to the value of {@code val}.
1282 * @throws NumberFormatException if {@code val} is infinite or NaN.
1283 * @since 1.5
1284 */
1285 public static BigDecimal valueOf(double val) {
1286 // Reminder: a zero double returns '0.0', so we cannot fastpath
1287 // to use the constant ZERO. This might be important enough to
1288 // justify a factory approach, a cache, or a few private
1289 // constants, later.
1290 return new BigDecimal(Double.toString(val));
1291 }
1292
1293 // Arithmetic Operations
1294 /**
1295 * Returns a {@code BigDecimal} whose value is {@code (this +
1296 * augend)}, and whose scale is {@code max(this.scale(),
1297 * augend.scale())}.
1879 */
1880 result = result.setScale(0, RoundingMode.DOWN);
1881 }
1882 // else result.scale() == 0;
1883
1884 int precisionDiff;
1885 if ((preferredScale > result.scale()) &&
1886 (precisionDiff = mc.precision - result.precision()) > 0) {
1887 return result.setScale(result.scale() +
1888 Math.min(precisionDiff, preferredScale - result.scale) );
1889 } else {
1890 return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);
1891 }
1892 }
1893
1894 /**
1895 * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1896 *
1897 * <p>The remainder is given by
1898 * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1899 * Note that this is not the modulo operation (the result can be
1900 * negative).
1901 *
1902 * @param divisor value by which this {@code BigDecimal} is to be divided.
1903 * @return {@code this % divisor}.
1904 * @throws ArithmeticException if {@code divisor==0}
1905 * @since 1.5
1906 */
1907 public BigDecimal remainder(BigDecimal divisor) {
1908 BigDecimal divrem[] = this.divideAndRemainder(divisor);
1909 return divrem[1];
1910 }
1911
1912
1913 /**
1914 * Returns a {@code BigDecimal} whose value is {@code (this %
1915 * divisor)}, with rounding according to the context settings.
1916 * The {@code MathContext} settings affect the implicit divide
1917 * used to compute the remainder. The remainder computation
1918 * itself is by definition exact. Therefore, the remainder may
1919 * contain more than {@code mc.getPrecision()} digits.
2020 *
2021 * <p>Special case:
2022 * <ul>
2023 * <li> The square root of a number numerically equal to {@code
2024 * ZERO} is numerically equal to {@code ZERO} with a preferred
2025 * scale according to the general rule above. In particular, for
2026 * {@code ZERO}}, {@code ZERO.sqrt(mc).equals(ZERO)} is true with
2027 * any {@code MathContext} as an argument.
2028 * </ul>
2029 *
2030 * @param mc the context to use.
2031 * @return the square root of {@code this}.
2032 * @throws ArithmeticException if {@code this} is less than zero.
2033 * @throws ArithmeticException if an exact result is requested
2034 * ({@code mc.getPrecision()==0}) and there is no finite decimal
2035 * expansion of the exact result
2036 * @throws ArithmeticException if
2037 * {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and
2038 * the exact result cannot fit in {@code mc.getPrecision()}
2039 * digits.
2040 * @since 9
2041 */
2042 public BigDecimal sqrt(MathContext mc) {
2043 int signum = signum();
2044 if (signum == 1) {
2045 /*
2046 * The following code draws on the algorithm presented in
2047 * "Properly Rounded Variable Precision Square Root," Hull and
2048 * Abrham, ACM Transactions on Mathematical Software, Vol 11,
2049 * No. 3, September 1985, Pages 229-237.
2050 *
2051 * The BigDecimal computational model differs from the one
2052 * presented in the paper in several ways: first BigDecimal
2053 * numbers aren't necessarily normalized, second many more
2054 * rounding modes are supported, including UNNECESSARY, and
2055 * exact results can be requested.
2056 *
2057 * The main steps of the algorithm below are as follows,
2058 * first argument reduce the value to the numerical range
2059 * [1, 10) using the following relations:
2677 * @throws ArithmeticException if the rounding mode is
2678 * {@code UNNECESSARY} and the
2679 * {@code BigDecimal} operation would require rounding.
2680 * @see #plus(MathContext)
2681 * @since 1.5
2682 */
2683 public BigDecimal round(MathContext mc) {
2684 return plus(mc);
2685 }
2686
2687 /**
2688 * Returns a {@code BigDecimal} whose scale is the specified
2689 * value, and whose unscaled value is determined by multiplying or
2690 * dividing this {@code BigDecimal}'s unscaled value by the
2691 * appropriate power of ten to maintain its overall value. If the
2692 * scale is reduced by the operation, the unscaled value must be
2693 * divided (rather than multiplied), and the value may be changed;
2694 * in this case, the specified rounding mode is applied to the
2695 * division.
2696 *
2697 * <p>Note that since BigDecimal objects are immutable, calls of
2698 * this method do <i>not</i> result in the original object being
2699 * modified, contrary to the usual convention of having methods
2700 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2701 * Instead, {@code setScale} returns an object with the proper
2702 * scale; the returned object may or may not be newly allocated.
2703 *
2704 * @param newScale scale of the {@code BigDecimal} value to be returned.
2705 * @param roundingMode The rounding mode to apply.
2706 * @return a {@code BigDecimal} whose scale is the specified value,
2707 * and whose unscaled value is determined by multiplying or
2708 * dividing this {@code BigDecimal}'s unscaled value by the
2709 * appropriate power of ten to maintain its overall value.
2710 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2711 * and the specified scaling operation would require
2712 * rounding.
2713 * @see RoundingMode
2714 * @since 1.5
2715 */
2716 public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2717 return setScale(newScale, roundingMode.oldMode);
2718 }
2719
2720 /**
2721 * Returns a {@code BigDecimal} whose scale is the specified
2722 * value, and whose unscaled value is determined by multiplying or
2723 * dividing this {@code BigDecimal}'s unscaled value by the
2724 * appropriate power of ten to maintain its overall value. If the
2725 * scale is reduced by the operation, the unscaled value must be
2726 * divided (rather than multiplied), and the value may be changed;
2727 * in this case, the specified rounding mode is applied to the
2728 * division.
2729 *
2730 * <p>Note that since BigDecimal objects are immutable, calls of
2731 * this method do <i>not</i> result in the original object being
2732 * modified, contrary to the usual convention of having methods
2733 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2734 * Instead, {@code setScale} returns an object with the proper
2735 * scale; the returned object may or may not be newly allocated.
2736 *
2737 * @deprecated The method {@link #setScale(int, RoundingMode)} should
2738 * be used in preference to this legacy method.
2739 *
2740 * @param newScale scale of the {@code BigDecimal} value to be returned.
2741 * @param roundingMode The rounding mode to apply.
2742 * @return a {@code BigDecimal} whose scale is the specified value,
2743 * and whose unscaled value is determined by multiplying or
2744 * dividing this {@code BigDecimal}'s unscaled value by the
2745 * appropriate power of ten to maintain its overall value.
2746 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2747 * and the specified scaling operation would require
2748 * rounding.
2749 * @throws IllegalArgumentException if {@code roundingMode} does not
2750 * represent a valid rounding mode.
2751 * @see #ROUND_UP
2805 }
2806
2807 /**
2808 * Returns a {@code BigDecimal} whose scale is the specified
2809 * value, and whose value is numerically equal to this
2810 * {@code BigDecimal}'s. Throws an {@code ArithmeticException}
2811 * if this is not possible.
2812 *
2813 * <p>This call is typically used to increase the scale, in which
2814 * case it is guaranteed that there exists a {@code BigDecimal}
2815 * of the specified scale and the correct value. The call can
2816 * also be used to reduce the scale if the caller knows that the
2817 * {@code BigDecimal} has sufficiently many zeros at the end of
2818 * its fractional part (i.e., factors of ten in its integer value)
2819 * to allow for the rescaling without changing its value.
2820 *
2821 * <p>This method returns the same result as the two-argument
2822 * versions of {@code setScale}, but saves the caller the trouble
2823 * of specifying a rounding mode in cases where it is irrelevant.
2824 *
2825 * <p>Note that since {@code BigDecimal} objects are immutable,
2826 * calls of this method do <i>not</i> result in the original
2827 * object being modified, contrary to the usual convention of
2828 * having methods named <code>set<i>X</i></code> mutate field
2829 * <i>{@code X}</i>. Instead, {@code setScale} returns an
2830 * object with the proper scale; the returned object may or may
2831 * not be newly allocated.
2832 *
2833 * @param newScale scale of the {@code BigDecimal} value to be returned.
2834 * @return a {@code BigDecimal} whose scale is the specified value, and
2835 * whose unscaled value is determined by multiplying or dividing
2836 * this {@code BigDecimal}'s unscaled value by the appropriate
2837 * power of ten to maintain its overall value.
2838 * @throws ArithmeticException if the specified scaling operation would
2839 * require rounding.
2840 * @see #setScale(int, int)
2841 * @see #setScale(int, RoundingMode)
2842 */
2843 public BigDecimal setScale(int newScale) {
2844 return setScale(newScale, ROUND_UNNECESSARY);
2845 }
2846
3074
3075 /**
3076 * Returns the maximum of this {@code BigDecimal} and {@code val}.
3077 *
3078 * @param val value with which the maximum is to be computed.
3079 * @return the {@code BigDecimal} whose value is the greater of this
3080 * {@code BigDecimal} and {@code val}. If they are equal,
3081 * as defined by the {@link #compareTo(BigDecimal) compareTo}
3082 * method, {@code this} is returned.
3083 * @see #compareTo(java.math.BigDecimal)
3084 */
3085 public BigDecimal max(BigDecimal val) {
3086 return (compareTo(val) >= 0 ? this : val);
3087 }
3088
3089 // Hash Function
3090
3091 /**
3092 * Returns the hash code for this {@code BigDecimal}. Note that
3093 * two {@code BigDecimal} objects that are numerically equal but
3094 * differ in scale (like 2.0 and 2.00) will generally <i>not</i>
3095 * have the same hash code.
3096 *
3097 * @return hash code for this {@code BigDecimal}.
3098 * @see #equals(Object)
3099 */
3100 @Override
3101 public int hashCode() {
3102 if (intCompact != INFLATED) {
3103 long val2 = (intCompact < 0)? -intCompact : intCompact;
3104 int temp = (int)( ((int)(val2 >>> 32)) * 31 +
3105 (val2 & LONG_MASK));
3106 return 31*((intCompact < 0) ?-temp:temp) + scale;
3107 } else
3108 return 31*intVal.hashCode() + scale;
3109 }
3110
3111 // Format Converters
3112
3113 /**
3114 * Returns the string representation of this {@code BigDecimal},
3325 } else if (insertionPoint > 0) { /* Point goes inside intVal */
3326 buf = new StringBuilder(intString);
3327 buf.insert(insertionPoint, '.');
3328 if (signum < 0)
3329 buf.insert(0, '-');
3330 } else { /* We must insert zeros between point and intVal */
3331 buf = new StringBuilder(3-insertionPoint + intString.length());
3332 buf.append(signum<0 ? "-0." : "0.");
3333 for (int i=0; i<-insertionPoint; i++) {
3334 buf.append('0');
3335 }
3336 buf.append(intString);
3337 }
3338 return buf.toString();
3339 }
3340
3341 /**
3342 * Converts this {@code BigDecimal} to a {@code BigInteger}.
3343 * This conversion is analogous to the
3344 * <i>narrowing primitive conversion</i> from {@code double} to
3345 * {@code long} as defined in section 5.1.3 of
3346 * <cite>The Java™ Language Specification</cite>:
3347 * any fractional part of this
3348 * {@code BigDecimal} will be discarded. Note that this
3349 * conversion can lose information about the precision of the
3350 * {@code BigDecimal} value.
3351 * <p>
3352 * To have an exception thrown if the conversion is inexact (in
3353 * other words if a nonzero fractional part is discarded), use the
3354 * {@link #toBigIntegerExact()} method.
3355 *
3356 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3357 */
3358 public BigInteger toBigInteger() {
3359 // force to an integer, quietly
3360 return this.setScale(0, ROUND_DOWN).inflated();
3361 }
3362
3363 /**
3364 * Converts this {@code BigDecimal} to a {@code BigInteger},
3365 * checking for lost information. An exception is thrown if this
3366 * {@code BigDecimal} has a nonzero fractional part.
3367 *
3368 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3369 * @throws ArithmeticException if {@code this} has a nonzero
3370 * fractional part.
3371 * @since 1.5
3372 */
3373 public BigInteger toBigIntegerExact() {
3374 // round to an integer, with Exception if decimal part non-0
3375 return this.setScale(0, ROUND_UNNECESSARY).inflated();
3376 }
3377
3378 /**
3379 * Converts this {@code BigDecimal} to a {@code long}.
3380 * This conversion is analogous to the
3381 * <i>narrowing primitive conversion</i> from {@code double} to
3382 * {@code short} as defined in section 5.1.3 of
3383 * <cite>The Java™ Language Specification</cite>:
3384 * any fractional part of this
3385 * {@code BigDecimal} will be discarded, and if the resulting
3386 * "{@code BigInteger}" is too big to fit in a
3387 * {@code long}, only the low-order 64 bits are returned.
3388 * Note that this conversion can lose information about the
3389 * overall magnitude and precision of this {@code BigDecimal} value as well
3390 * as return a result with the opposite sign.
3391 *
3392 * @return this {@code BigDecimal} converted to a {@code long}.
3393 */
3394 @Override
3395 public long longValue(){
3396 return (intCompact != INFLATED && scale == 0) ?
3397 intCompact:
3398 toBigInteger().longValue();
3399 }
3400
3401 /**
3402 * Converts this {@code BigDecimal} to a {@code long}, checking
3403 * for lost information. If this {@code BigDecimal} has a
3404 * nonzero fractional part or is out of the possible range for a
3405 * {@code long} result then an {@code ArithmeticException} is
3406 * thrown.
3407 *
3408 * @return this {@code BigDecimal} converted to a {@code long}.
3409 * @throws ArithmeticException if {@code this} has a nonzero
3410 * fractional part, or will not fit in a {@code long}.
3411 * @since 1.5
3412 */
3431
3432 private static class LongOverflow {
3433 /** BigInteger equal to Long.MIN_VALUE. */
3434 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3435
3436 /** BigInteger equal to Long.MAX_VALUE. */
3437 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3438
3439 public static void check(BigDecimal num) {
3440 BigInteger intVal = num.inflated();
3441 if (intVal.compareTo(LONGMIN) < 0 ||
3442 intVal.compareTo(LONGMAX) > 0)
3443 throw new java.lang.ArithmeticException("Overflow");
3444 }
3445 }
3446
3447 /**
3448 * Converts this {@code BigDecimal} to an {@code int}.
3449 * This conversion is analogous to the
3450 * <i>narrowing primitive conversion</i> from {@code double} to
3451 * {@code short} as defined in section 5.1.3 of
3452 * <cite>The Java™ Language Specification</cite>:
3453 * any fractional part of this
3454 * {@code BigDecimal} will be discarded, and if the resulting
3455 * "{@code BigInteger}" is too big to fit in an
3456 * {@code int}, only the low-order 32 bits are returned.
3457 * Note that this conversion can lose information about the
3458 * overall magnitude and precision of this {@code BigDecimal}
3459 * value as well as return a result with the opposite sign.
3460 *
3461 * @return this {@code BigDecimal} converted to an {@code int}.
3462 */
3463 @Override
3464 public int intValue() {
3465 return (intCompact != INFLATED && scale == 0) ?
3466 (int)intCompact :
3467 toBigInteger().intValue();
3468 }
3469
3470 /**
3471 * Converts this {@code BigDecimal} to an {@code int}, checking
3472 * for lost information. If this {@code BigDecimal} has a
3473 * nonzero fractional part or is out of the possible range for an
3474 * {@code int} result then an {@code ArithmeticException} is
3475 * thrown.
3476 *
3477 * @return this {@code BigDecimal} converted to an {@code int}.
3478 * @throws ArithmeticException if {@code this} has a nonzero
3479 * fractional part, or will not fit in an {@code int}.
3480 * @since 1.5
3481 */
3514 * {@code byte} result then an {@code ArithmeticException} is
3515 * thrown.
3516 *
3517 * @return this {@code BigDecimal} converted to a {@code byte}.
3518 * @throws ArithmeticException if {@code this} has a nonzero
3519 * fractional part, or will not fit in a {@code byte}.
3520 * @since 1.5
3521 */
3522 public byte byteValueExact() {
3523 long num;
3524 num = this.longValueExact(); // will check decimal part
3525 if ((byte)num != num)
3526 throw new java.lang.ArithmeticException("Overflow");
3527 return (byte)num;
3528 }
3529
3530 /**
3531 * Converts this {@code BigDecimal} to a {@code float}.
3532 * This conversion is similar to the
3533 * <i>narrowing primitive conversion</i> from {@code double} to
3534 * {@code float} as defined in section 5.1.3 of
3535 * <cite>The Java™ Language Specification</cite>:
3536 * if this {@code BigDecimal} has too great a
3537 * magnitude to represent as a {@code float}, it will be
3538 * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3539 * Float#POSITIVE_INFINITY} as appropriate. Note that even when
3540 * the return value is finite, this conversion can lose
3541 * information about the precision of the {@code BigDecimal}
3542 * value.
3543 *
3544 * @return this {@code BigDecimal} converted to a {@code float}.
3545 */
3546 @Override
3547 public float floatValue(){
3548 if(intCompact != INFLATED) {
3549 if (scale == 0) {
3550 return (float)intCompact;
3551 } else {
3552 /*
3553 * If both intCompact and the scale can be exactly
3554 * represented as float values, perform a single float
3555 * multiply or divide to compute the (properly
3556 * rounded) result.
3557 */
3558 if (Math.abs(intCompact) < 1L<<22 ) {
3559 // Don't have too guard against
3560 // Math.abs(MIN_VALUE) because of outer check
3561 // against INFLATED.
3562 if (scale > 0 && scale < FLOAT_10_POW.length) {
3563 return (float)intCompact / FLOAT_10_POW[scale];
3564 } else if (scale < 0 && scale > -FLOAT_10_POW.length) {
3565 return (float)intCompact * FLOAT_10_POW[-scale];
3566 }
3567 }
3568 }
3569 }
3570 // Somewhat inefficient, but guaranteed to work.
3571 return Float.parseFloat(this.toString());
3572 }
3573
3574 /**
3575 * Converts this {@code BigDecimal} to a {@code double}.
3576 * This conversion is similar to the
3577 * <i>narrowing primitive conversion</i> from {@code double} to
3578 * {@code float} as defined in section 5.1.3 of
3579 * <cite>The Java™ Language Specification</cite>:
3580 * if this {@code BigDecimal} has too great a
3581 * magnitude represent as a {@code double}, it will be
3582 * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3583 * Double#POSITIVE_INFINITY} as appropriate. Note that even when
3584 * the return value is finite, this conversion can lose
3585 * information about the precision of the {@code BigDecimal}
3586 * value.
3587 *
3588 * @return this {@code BigDecimal} converted to a {@code double}.
3589 */
3590 @Override
3591 public double doubleValue(){
3592 if(intCompact != INFLATED) {
3593 if (scale == 0) {
3594 return (double)intCompact;
3595 } else {
3596 /*
3597 * If both intCompact and the scale can be exactly
3598 * represented as double values, perform a single
3599 * double multiply or divide to compute the (properly
3600 * rounded) result.
3601 */
3602 if (Math.abs(intCompact) < 1L<<52 ) {
3603 // Don't have too guard against
3604 // Math.abs(MIN_VALUE) because of outer check
3605 // against INFLATED.
3606 if (scale > 0 && scale < DOUBLE_10_POW.length) {
3607 return (double)intCompact / DOUBLE_10_POW[scale];
3608 } else if (scale < 0 && scale > -DOUBLE_10_POW.length) {
|
38 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
39 * or positive, the scale is the number of digits to the right of the
40 * decimal point. If negative, the unscaled value of the number is
41 * multiplied by ten to the power of the negation of the scale. The
42 * value of the number represented by the {@code BigDecimal} is
43 * therefore <code>(unscaledValue × 10<sup>-scale</sup>)</code>.
44 *
45 * <p>The {@code BigDecimal} class provides operations for
46 * arithmetic, scale manipulation, rounding, comparison, hashing, and
47 * format conversion. The {@link #toString} method provides a
48 * canonical representation of a {@code BigDecimal}.
49 *
50 * <p>The {@code BigDecimal} class gives its user complete control
51 * over rounding behavior. If no rounding mode is specified and the
52 * exact result cannot be represented, an exception is thrown;
53 * otherwise, calculations can be carried out to a chosen precision
54 * and rounding mode by supplying an appropriate {@link MathContext}
55 * object to the operation. In either case, eight <em>rounding
56 * modes</em> are provided for the control of rounding. Using the
57 * integer fields in this class (such as {@link #ROUND_HALF_UP}) to
58 * represent rounding mode is deprecated; the enumeration values
59 * of the {@code RoundingMode} {@code enum}, (such as {@link
60 * RoundingMode#HALF_UP}) should be used instead.
61 *
62 * <p>When a {@code MathContext} object is supplied with a precision
63 * setting of 0 (for example, {@link MathContext#UNLIMITED}),
64 * arithmetic operations are exact, as are the arithmetic methods
65 * which take no {@code MathContext} object. (This is the only
66 * behavior that was supported in releases prior to 5.) As a
67 * corollary of computing the exact result, the rounding mode setting
68 * of a {@code MathContext} object with a precision setting of 0 is
69 * not used and thus irrelevant. In the case of divide, the exact
70 * quotient could have an infinitely long decimal expansion; for
71 * example, 1 divided by 3. If the quotient has a nonterminating
72 * decimal expansion and the operation is specified to return an exact
73 * result, an {@code ArithmeticException} is thrown. Otherwise, the
74 * exact result of the division is returned, as done for other
75 * operations.
76 *
77 * <p>When the precision setting is not 0, the rules of
78 * {@code BigDecimal} arithmetic are broadly compatible with selected
79 * modes of operation of the arithmetic defined in ANSI X3.274-1996
80 * and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those
81 * standards, {@code BigDecimal} includes many rounding modes, which
82 * were mandatory for division in {@code BigDecimal} releases prior
83 * to 5. Any conflicts between these ANSI standards and the
84 * {@code BigDecimal} specification are resolved in favor of
85 * {@code BigDecimal}.
86 *
87 * <p>Since the same numerical value can have different
88 * representations (with different scales), the rules of arithmetic
89 * and rounding must specify both the numerical result and the scale
90 * used in the result's representation.
91 *
92 *
93 * <p>In general the rounding modes and precision setting determine
94 * how operations return results with a limited number of digits when
95 * the exact result has more digits (perhaps infinitely many in the
96 * case of division and square root) than the number of digits returned.
97 *
98 * First, the
99 * total number of digits to return is specified by the
100 * {@code MathContext}'s {@code precision} setting; this determines
101 * the result's <i>precision</i>. The digit count starts from the
102 * leftmost nonzero digit of the exact result. The rounding mode
103 * determines how any discarded trailing digits affect the returned
104 * result.
105 *
106 * <p>For all arithmetic operators , the operation is carried out as
107 * though an exact intermediate result were first calculated and then
108 * rounded to the number of digits specified by the precision setting
109 * (if necessary), using the selected rounding mode. If the exact
110 * result is not returned, some digit positions of the exact result
111 * are discarded. When rounding increases the magnitude of the
112 * returned result, it is possible for a new digit position to be
113 * created by a carry propagating to a leading {@literal "9"} digit.
114 * For example, rounding the value 999.9 to three digits rounding up
115 * would be numerically equal to one thousand, represented as
116 * 100×10<sup>1</sup>. In such cases, the new {@literal "1"} is
179 * of the stored number with minimal effect on its value. Decimal
180 * point motion operations ({@link #movePointLeft movePointLeft} and
181 * {@link #movePointRight movePointRight}) return a
182 * {@code BigDecimal} created from the operand by moving the decimal
183 * point a specified distance in the specified direction.
184 *
185 * <p>For the sake of brevity and clarity, pseudo-code is used
186 * throughout the descriptions of {@code BigDecimal} methods. The
187 * pseudo-code expression {@code (i + j)} is shorthand for "a
188 * {@code BigDecimal} whose value is that of the {@code BigDecimal}
189 * {@code i} added to that of the {@code BigDecimal}
190 * {@code j}." The pseudo-code expression {@code (i == j)} is
191 * shorthand for "{@code true} if and only if the
192 * {@code BigDecimal} {@code i} represents the same value as the
193 * {@code BigDecimal} {@code j}." Other pseudo-code expressions
194 * are interpreted similarly. Square brackets are used to represent
195 * the particular {@code BigInteger} and scale pair defining a
196 * {@code BigDecimal} value; for example [19, 2] is the
197 * {@code BigDecimal} numerically equal to 0.19 having a scale of 2.
198 *
199 *
200 * <p>All methods and constructors for this class throw
201 * {@code NullPointerException} when passed a {@code null} object
202 * reference for any input parameter.
203 *
204 * @apiNote Care should be exercised if {@code BigDecimal} objects
205 * are used as keys in a {@link java.util.SortedMap SortedMap} or
206 * elements in a {@link java.util.SortedSet SortedSet} since
207 * {@code BigDecimal}'s <i>natural ordering</i> is <em>inconsistent
208 * with equals</em>. See {@link Comparable}, {@link
209 * java.util.SortedMap} or {@link java.util.SortedSet} for more
210 * information.
211 *
212 * @see BigInteger
213 * @see MathContext
214 * @see RoundingMode
215 * @see java.util.SortedMap
216 * @see java.util.SortedSet
217 * @author Josh Bloch
218 * @author Mike Cowlishaw
219 * @author Joseph D. Darcy
220 * @author Sergey V. Kuksenko
221 */
222 public class BigDecimal extends Number implements Comparable<BigDecimal> {
223 /**
224 * The unscaled value of this BigDecimal, as returned by {@link
225 * #unscaledValue}.
226 *
227 * @serial
228 * @see #unscaledValue
229 */
230 private final BigInteger intVal;
231
361 // Constructors
362
363 /**
364 * Trusted package private constructor.
365 * Trusted simply means if val is INFLATED, intVal could not be null and
366 * if intVal is null, val could not be INFLATED.
367 */
368 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
369 this.scale = scale;
370 this.precision = prec;
371 this.intCompact = val;
372 this.intVal = intVal;
373 }
374
375 /**
376 * Translates a character array representation of a
377 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
378 * same sequence of characters as the {@link #BigDecimal(String)}
379 * constructor, while allowing a sub-array to be specified.
380 *
381 * @implNote If the sequence of characters is already available
382 * within a character array, using this constructor is faster than
383 * converting the {@code char} array to string and using the
384 * {@code BigDecimal(String)} constructor.
385 *
386 * @param in {@code char} array that is the source of characters.
387 * @param offset first character in the array to inspect.
388 * @param len number of characters to consider.
389 * @throws NumberFormatException if {@code in} is not a valid
390 * representation of a {@code BigDecimal} or the defined subarray
391 * is not wholly within {@code in}.
392 * @since 1.5
393 */
394 public BigDecimal(char[] in, int offset, int len) {
395 this(in,offset,len,MathContext.UNLIMITED);
396 }
397
398 /**
399 * Translates a character array representation of a
400 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
401 * same sequence of characters as the {@link #BigDecimal(String)}
402 * constructor, while allowing a sub-array to be specified and
403 * with rounding according to the context settings.
404 *
405 * @implNote If the sequence of characters is already available
406 * within a character array, using this constructor is faster than
407 * converting the {@code char} array to string and using the
408 * {@code BigDecimal(String)} constructor.
409 *
410 * @param in {@code char} array that is the source of characters.
411 * @param offset first character in the array to inspect.
412 * @param len number of characters to consider.
413 * @param mc the context to use.
414 * @throws ArithmeticException if the result is inexact but the
415 * rounding mode is {@code UNNECESSARY}.
416 * @throws NumberFormatException if {@code in} is not a valid
417 * representation of a {@code BigDecimal} or the defined subarray
418 * is not wholly within {@code in}.
419 * @since 1.5
420 */
421 public BigDecimal(char[] in, int offset, int len, MathContext mc) {
422 // protect against huge length.
423 if (offset + len > in.length || offset < 0)
424 throw new NumberFormatException("Bad offset or len arguments for char[] input.");
425 // This is the primary string to BigDecimal constructor; all
426 // incoming strings end up here; it uses explicit (inline)
427 // parsing for speed and generates at most one intermediate
428 // (temporary) object (a char[] array) for non-compact case.
429
430 // Use locals for all fields values until completion
431 int prec = 0; // record precision value
432 int scl = 0; // record scale value
663 if (v < 0) // not a digit
664 throw new NumberFormatException("Not a digit.");
665 }
666 exp = exp * 10 + v;
667 if (len == 1)
668 break; // that was final character
669 offset++;
670 c = in[offset];
671 }
672 if (negexp) // apply sign
673 exp = -exp;
674 return exp;
675 }
676
677 /**
678 * Translates a character array representation of a
679 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
680 * same sequence of characters as the {@link #BigDecimal(String)}
681 * constructor.
682 *
683 * @implNote If the sequence of characters is already available
684 * as a character array, using this constructor is faster than
685 * converting the {@code char} array to string and using the
686 * {@code BigDecimal(String)} constructor.
687 *
688 * @param in {@code char} array that is the source of characters.
689 * @throws NumberFormatException if {@code in} is not a valid
690 * representation of a {@code BigDecimal}.
691 * @since 1.5
692 */
693 public BigDecimal(char[] in) {
694 this(in, 0, in.length);
695 }
696
697 /**
698 * Translates a character array representation of a
699 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
700 * same sequence of characters as the {@link #BigDecimal(String)}
701 * constructor and with rounding according to the context
702 * settings.
703 *
704 * @implNote If the sequence of characters is already available
705 * as a character array, using this constructor is faster than
706 * converting the {@code char} array to string and using the
707 * {@code BigDecimal(String)} constructor.
708 *
709 * @param in {@code char} array that is the source of characters.
710 * @param mc the context to use.
711 * @throws ArithmeticException if the result is inexact but the
712 * rounding mode is {@code UNNECESSARY}.
713 * @throws NumberFormatException if {@code in} is not a valid
714 * representation of a {@code BigDecimal}.
715 * @since 1.5
716 */
717 public BigDecimal(char[] in, MathContext mc) {
718 this(in, 0, in.length, mc);
719 }
720
721 /**
722 * Translates the string representation of a {@code BigDecimal}
723 * into a {@code BigDecimal}. The string representation consists
724 * of an optional sign, {@code '+'} (<code> '\u002B'</code>) or
725 * {@code '-'} (<code>'\u002D'</code>), followed by a sequence of
726 * zero or more decimal digits ("the integer"), optionally
727 * followed by a fraction, optionally followed by an exponent.
789 * <i>significand</i> × 10<sup> <i>exponent</i></sup>.
790 * For each string on the left, the resulting representation
791 * [{@code BigInteger}, {@code scale}] is shown on the right.
792 * <pre>
793 * "0" [0,0]
794 * "0.00" [0,2]
795 * "123" [123,0]
796 * "-123" [-123,0]
797 * "1.23E3" [123,-1]
798 * "1.23E+3" [123,-1]
799 * "12.3E+7" [123,-6]
800 * "12.0" [120,1]
801 * "12.3" [123,1]
802 * "0.00123" [123,5]
803 * "-1.23E-12" [-123,14]
804 * "1234.5E-4" [12345,5]
805 * "0E+7" [0,-7]
806 * "-0" [0,0]
807 * </pre>
808 *
809 * @apiNote For values other than {@code float} and
810 * {@code double} NaN and ±Infinity, this constructor is
811 * compatible with the values returned by {@link Float#toString}
812 * and {@link Double#toString}. This is generally the preferred
813 * way to convert a {@code float} or {@code double} into a
814 * BigDecimal, as it doesn't suffer from the unpredictability of
815 * the {@link #BigDecimal(double)} constructor.
816 *
817 * @param val String representation of {@code BigDecimal}.
818 *
819 * @throws NumberFormatException if {@code val} is not a valid
820 * representation of a {@code BigDecimal}.
821 */
822 public BigDecimal(String val) {
823 this(val.toCharArray(), 0, val.length());
824 }
825
826 /**
827 * Translates the string representation of a {@code BigDecimal}
828 * into a {@code BigDecimal}, accepting the same strings as the
829 * {@link #BigDecimal(String)} constructor, with rounding
843
844 /**
845 * Translates a {@code double} into a {@code BigDecimal} which
846 * is the exact decimal representation of the {@code double}'s
847 * binary floating-point value. The scale of the returned
848 * {@code BigDecimal} is the smallest value such that
849 * <code>(10<sup>scale</sup> × val)</code> is an integer.
850 * <p>
851 * <b>Notes:</b>
852 * <ol>
853 * <li>
854 * The results of this constructor can be somewhat unpredictable.
855 * One might assume that writing {@code new BigDecimal(0.1)} in
856 * Java creates a {@code BigDecimal} which is exactly equal to
857 * 0.1 (an unscaled value of 1, with a scale of 1), but it is
858 * actually equal to
859 * 0.1000000000000000055511151231257827021181583404541015625.
860 * This is because 0.1 cannot be represented exactly as a
861 * {@code double} (or, for that matter, as a binary fraction of
862 * any finite length). Thus, the value that is being passed
863 * <em>in</em> to the constructor is not exactly equal to 0.1,
864 * appearances notwithstanding.
865 *
866 * <li>
867 * The {@code String} constructor, on the other hand, is
868 * perfectly predictable: writing {@code new BigDecimal("0.1")}
869 * creates a {@code BigDecimal} which is <em>exactly</em> equal to
870 * 0.1, as one would expect. Therefore, it is generally
871 * recommended that the {@linkplain #BigDecimal(String)
872 * String constructor} be used in preference to this one.
873 *
874 * <li>
875 * When a {@code double} must be used as a source for a
876 * {@code BigDecimal}, note that this constructor provides an
877 * exact conversion; it does not give the same result as
878 * converting the {@code double} to a {@code String} using the
879 * {@link Double#toString(double)} method and then using the
880 * {@link #BigDecimal(String)} constructor. To get that result,
881 * use the {@code static} {@link #valueOf(double)} method.
882 * </ol>
883 *
884 * @param val {@code double} value to be converted to
885 * {@code BigDecimal}.
886 * @throws NumberFormatException if {@code val} is infinite or NaN.
887 */
888 public BigDecimal(double val) {
889 this(val,MathContext.UNLIMITED);
1183 int drop = prec - mcp;
1184 while (drop > 0) {
1185 scl = checkScaleNonZero((long) scl - drop);
1186 val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1187 prec = longDigitLength(val);
1188 drop = prec - mcp;
1189 }
1190 rb = null;
1191 }
1192 }
1193 this.intVal = rb;
1194 this.intCompact = val;
1195 this.scale = scl;
1196 this.precision = prec;
1197 }
1198
1199 // Static Factory Methods
1200
1201 /**
1202 * Translates a {@code long} unscaled value and an
1203 * {@code int} scale into a {@code BigDecimal}.
1204 *
1205 * @apiNote This static factory method is provided in preference
1206 * to a ({@code long}, {@code int}) constructor because it allows
1207 * for reuse of frequently used {@code BigDecimal} values.
1208 *
1209 * @param unscaledVal unscaled value of the {@code BigDecimal}.
1210 * @param scale scale of the {@code BigDecimal}.
1211 * @return a {@code BigDecimal} whose value is
1212 * <code>(unscaledVal × 10<sup>-scale</sup>)</code>.
1213 */
1214 public static BigDecimal valueOf(long unscaledVal, int scale) {
1215 if (scale == 0)
1216 return valueOf(unscaledVal);
1217 else if (unscaledVal == 0) {
1218 return zeroValueOf(scale);
1219 }
1220 return new BigDecimal(unscaledVal == INFLATED ?
1221 INFLATED_BIGINT : null,
1222 unscaledVal, scale, 0);
1223 }
1224
1225 /**
1226 * Translates a {@code long} value into a {@code BigDecimal}
1227 * with a scale of zero.
1228 *
1229 * @apiNote This static factory method is provided in preference
1230 * to a ({@code long}) constructor because it allows for reuse of
1231 * frequently used {@code BigDecimal} values.
1232 *
1233 * @param val value of the {@code BigDecimal}.
1234 * @return a {@code BigDecimal} whose value is {@code val}.
1235 */
1236 public static BigDecimal valueOf(long val) {
1237 if (val >= 0 && val < ZERO_THROUGH_TEN.length)
1238 return ZERO_THROUGH_TEN[(int)val];
1239 else if (val != INFLATED)
1240 return new BigDecimal(null, val, 0, 0);
1241 return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1242 }
1243
1244 static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1245 if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {
1246 return ZERO_THROUGH_TEN[(int) unscaledVal];
1247 } else if (unscaledVal == 0) {
1248 return zeroValueOf(scale);
1249 }
1250 return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1251 unscaledVal, scale, prec);
1256 if (val == 0) {
1257 return zeroValueOf(scale);
1258 } else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {
1259 return ZERO_THROUGH_TEN[(int) val];
1260 }
1261 return new BigDecimal(intVal, val, scale, prec);
1262 }
1263
1264 static BigDecimal zeroValueOf(int scale) {
1265 if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1266 return ZERO_SCALED_BY[scale];
1267 else
1268 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1269 }
1270
1271 /**
1272 * Translates a {@code double} into a {@code BigDecimal}, using
1273 * the {@code double}'s canonical string representation provided
1274 * by the {@link Double#toString(double)} method.
1275 *
1276 * @apiNote This is generally the preferred way to convert a
1277 * {@code double} (or {@code float}) into a {@code BigDecimal}, as
1278 * the value returned is equal to that resulting from constructing
1279 * a {@code BigDecimal} from the result of using {@link
1280 * Double#toString(double)}.
1281 *
1282 * @param val {@code double} to convert to a {@code BigDecimal}.
1283 * @return a {@code BigDecimal} whose value is equal to or approximately
1284 * equal to the value of {@code val}.
1285 * @throws NumberFormatException if {@code val} is infinite or NaN.
1286 * @since 1.5
1287 */
1288 public static BigDecimal valueOf(double val) {
1289 // Reminder: a zero double returns '0.0', so we cannot fastpath
1290 // to use the constant ZERO. This might be important enough to
1291 // justify a factory approach, a cache, or a few private
1292 // constants, later.
1293 return new BigDecimal(Double.toString(val));
1294 }
1295
1296 // Arithmetic Operations
1297 /**
1298 * Returns a {@code BigDecimal} whose value is {@code (this +
1299 * augend)}, and whose scale is {@code max(this.scale(),
1300 * augend.scale())}.
1882 */
1883 result = result.setScale(0, RoundingMode.DOWN);
1884 }
1885 // else result.scale() == 0;
1886
1887 int precisionDiff;
1888 if ((preferredScale > result.scale()) &&
1889 (precisionDiff = mc.precision - result.precision()) > 0) {
1890 return result.setScale(result.scale() +
1891 Math.min(precisionDiff, preferredScale - result.scale) );
1892 } else {
1893 return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale);
1894 }
1895 }
1896
1897 /**
1898 * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
1899 *
1900 * <p>The remainder is given by
1901 * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
1902 * Note that this is <em>not</em> the modulo operation (the result can be
1903 * negative).
1904 *
1905 * @param divisor value by which this {@code BigDecimal} is to be divided.
1906 * @return {@code this % divisor}.
1907 * @throws ArithmeticException if {@code divisor==0}
1908 * @since 1.5
1909 */
1910 public BigDecimal remainder(BigDecimal divisor) {
1911 BigDecimal divrem[] = this.divideAndRemainder(divisor);
1912 return divrem[1];
1913 }
1914
1915
1916 /**
1917 * Returns a {@code BigDecimal} whose value is {@code (this %
1918 * divisor)}, with rounding according to the context settings.
1919 * The {@code MathContext} settings affect the implicit divide
1920 * used to compute the remainder. The remainder computation
1921 * itself is by definition exact. Therefore, the remainder may
1922 * contain more than {@code mc.getPrecision()} digits.
2023 *
2024 * <p>Special case:
2025 * <ul>
2026 * <li> The square root of a number numerically equal to {@code
2027 * ZERO} is numerically equal to {@code ZERO} with a preferred
2028 * scale according to the general rule above. In particular, for
2029 * {@code ZERO}}, {@code ZERO.sqrt(mc).equals(ZERO)} is true with
2030 * any {@code MathContext} as an argument.
2031 * </ul>
2032 *
2033 * @param mc the context to use.
2034 * @return the square root of {@code this}.
2035 * @throws ArithmeticException if {@code this} is less than zero.
2036 * @throws ArithmeticException if an exact result is requested
2037 * ({@code mc.getPrecision()==0}) and there is no finite decimal
2038 * expansion of the exact result
2039 * @throws ArithmeticException if
2040 * {@code (mc.getRoundingMode()==RoundingMode.UNNECESSARY}) and
2041 * the exact result cannot fit in {@code mc.getPrecision()}
2042 * digits.
2043 * @see BigInteger#sqrt()
2044 * @since 9
2045 */
2046 public BigDecimal sqrt(MathContext mc) {
2047 int signum = signum();
2048 if (signum == 1) {
2049 /*
2050 * The following code draws on the algorithm presented in
2051 * "Properly Rounded Variable Precision Square Root," Hull and
2052 * Abrham, ACM Transactions on Mathematical Software, Vol 11,
2053 * No. 3, September 1985, Pages 229-237.
2054 *
2055 * The BigDecimal computational model differs from the one
2056 * presented in the paper in several ways: first BigDecimal
2057 * numbers aren't necessarily normalized, second many more
2058 * rounding modes are supported, including UNNECESSARY, and
2059 * exact results can be requested.
2060 *
2061 * The main steps of the algorithm below are as follows,
2062 * first argument reduce the value to the numerical range
2063 * [1, 10) using the following relations:
2681 * @throws ArithmeticException if the rounding mode is
2682 * {@code UNNECESSARY} and the
2683 * {@code BigDecimal} operation would require rounding.
2684 * @see #plus(MathContext)
2685 * @since 1.5
2686 */
2687 public BigDecimal round(MathContext mc) {
2688 return plus(mc);
2689 }
2690
2691 /**
2692 * Returns a {@code BigDecimal} whose scale is the specified
2693 * value, and whose unscaled value is determined by multiplying or
2694 * dividing this {@code BigDecimal}'s unscaled value by the
2695 * appropriate power of ten to maintain its overall value. If the
2696 * scale is reduced by the operation, the unscaled value must be
2697 * divided (rather than multiplied), and the value may be changed;
2698 * in this case, the specified rounding mode is applied to the
2699 * division.
2700 *
2701 * @apiNote Since BigDecimal objects are immutable, calls of
2702 * this method do <em>not</em> result in the original object being
2703 * modified, contrary to the usual convention of having methods
2704 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2705 * Instead, {@code setScale} returns an object with the proper
2706 * scale; the returned object may or may not be newly allocated.
2707 *
2708 * @param newScale scale of the {@code BigDecimal} value to be returned.
2709 * @param roundingMode The rounding mode to apply.
2710 * @return a {@code BigDecimal} whose scale is the specified value,
2711 * and whose unscaled value is determined by multiplying or
2712 * dividing this {@code BigDecimal}'s unscaled value by the
2713 * appropriate power of ten to maintain its overall value.
2714 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY}
2715 * and the specified scaling operation would require
2716 * rounding.
2717 * @see RoundingMode
2718 * @since 1.5
2719 */
2720 public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
2721 return setScale(newScale, roundingMode.oldMode);
2722 }
2723
2724 /**
2725 * Returns a {@code BigDecimal} whose scale is the specified
2726 * value, and whose unscaled value is determined by multiplying or
2727 * dividing this {@code BigDecimal}'s unscaled value by the
2728 * appropriate power of ten to maintain its overall value. If the
2729 * scale is reduced by the operation, the unscaled value must be
2730 * divided (rather than multiplied), and the value may be changed;
2731 * in this case, the specified rounding mode is applied to the
2732 * division.
2733 *
2734 * @apiNote Since BigDecimal objects are immutable, calls of
2735 * this method do <em>not</em> result in the original object being
2736 * modified, contrary to the usual convention of having methods
2737 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>.
2738 * Instead, {@code setScale} returns an object with the proper
2739 * scale; the returned object may or may not be newly allocated.
2740 *
2741 * @deprecated The method {@link #setScale(int, RoundingMode)} should
2742 * be used in preference to this legacy method.
2743 *
2744 * @param newScale scale of the {@code BigDecimal} value to be returned.
2745 * @param roundingMode The rounding mode to apply.
2746 * @return a {@code BigDecimal} whose scale is the specified value,
2747 * and whose unscaled value is determined by multiplying or
2748 * dividing this {@code BigDecimal}'s unscaled value by the
2749 * appropriate power of ten to maintain its overall value.
2750 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY}
2751 * and the specified scaling operation would require
2752 * rounding.
2753 * @throws IllegalArgumentException if {@code roundingMode} does not
2754 * represent a valid rounding mode.
2755 * @see #ROUND_UP
2809 }
2810
2811 /**
2812 * Returns a {@code BigDecimal} whose scale is the specified
2813 * value, and whose value is numerically equal to this
2814 * {@code BigDecimal}'s. Throws an {@code ArithmeticException}
2815 * if this is not possible.
2816 *
2817 * <p>This call is typically used to increase the scale, in which
2818 * case it is guaranteed that there exists a {@code BigDecimal}
2819 * of the specified scale and the correct value. The call can
2820 * also be used to reduce the scale if the caller knows that the
2821 * {@code BigDecimal} has sufficiently many zeros at the end of
2822 * its fractional part (i.e., factors of ten in its integer value)
2823 * to allow for the rescaling without changing its value.
2824 *
2825 * <p>This method returns the same result as the two-argument
2826 * versions of {@code setScale}, but saves the caller the trouble
2827 * of specifying a rounding mode in cases where it is irrelevant.
2828 *
2829 * @apiNote Since {@code BigDecimal} objects are immutable,
2830 * calls of this method do <em>not</em> result in the original
2831 * object being modified, contrary to the usual convention of
2832 * having methods named <code>set<i>X</i></code> mutate field
2833 * <i>{@code X}</i>. Instead, {@code setScale} returns an
2834 * object with the proper scale; the returned object may or may
2835 * not be newly allocated.
2836 *
2837 * @param newScale scale of the {@code BigDecimal} value to be returned.
2838 * @return a {@code BigDecimal} whose scale is the specified value, and
2839 * whose unscaled value is determined by multiplying or dividing
2840 * this {@code BigDecimal}'s unscaled value by the appropriate
2841 * power of ten to maintain its overall value.
2842 * @throws ArithmeticException if the specified scaling operation would
2843 * require rounding.
2844 * @see #setScale(int, int)
2845 * @see #setScale(int, RoundingMode)
2846 */
2847 public BigDecimal setScale(int newScale) {
2848 return setScale(newScale, ROUND_UNNECESSARY);
2849 }
2850
3078
3079 /**
3080 * Returns the maximum of this {@code BigDecimal} and {@code val}.
3081 *
3082 * @param val value with which the maximum is to be computed.
3083 * @return the {@code BigDecimal} whose value is the greater of this
3084 * {@code BigDecimal} and {@code val}. If they are equal,
3085 * as defined by the {@link #compareTo(BigDecimal) compareTo}
3086 * method, {@code this} is returned.
3087 * @see #compareTo(java.math.BigDecimal)
3088 */
3089 public BigDecimal max(BigDecimal val) {
3090 return (compareTo(val) >= 0 ? this : val);
3091 }
3092
3093 // Hash Function
3094
3095 /**
3096 * Returns the hash code for this {@code BigDecimal}. Note that
3097 * two {@code BigDecimal} objects that are numerically equal but
3098 * differ in scale (like 2.0 and 2.00) will generally <em>not</em>
3099 * have the same hash code.
3100 *
3101 * @return hash code for this {@code BigDecimal}.
3102 * @see #equals(Object)
3103 */
3104 @Override
3105 public int hashCode() {
3106 if (intCompact != INFLATED) {
3107 long val2 = (intCompact < 0)? -intCompact : intCompact;
3108 int temp = (int)( ((int)(val2 >>> 32)) * 31 +
3109 (val2 & LONG_MASK));
3110 return 31*((intCompact < 0) ?-temp:temp) + scale;
3111 } else
3112 return 31*intVal.hashCode() + scale;
3113 }
3114
3115 // Format Converters
3116
3117 /**
3118 * Returns the string representation of this {@code BigDecimal},
3329 } else if (insertionPoint > 0) { /* Point goes inside intVal */
3330 buf = new StringBuilder(intString);
3331 buf.insert(insertionPoint, '.');
3332 if (signum < 0)
3333 buf.insert(0, '-');
3334 } else { /* We must insert zeros between point and intVal */
3335 buf = new StringBuilder(3-insertionPoint + intString.length());
3336 buf.append(signum<0 ? "-0." : "0.");
3337 for (int i=0; i<-insertionPoint; i++) {
3338 buf.append('0');
3339 }
3340 buf.append(intString);
3341 }
3342 return buf.toString();
3343 }
3344
3345 /**
3346 * Converts this {@code BigDecimal} to a {@code BigInteger}.
3347 * This conversion is analogous to the
3348 * <i>narrowing primitive conversion</i> from {@code double} to
3349 * {@code long} as defined in
3350 * <cite>The Java™ Language Specification</cite>:
3351 * any fractional part of this
3352 * {@code BigDecimal} will be discarded. Note that this
3353 * conversion can lose information about the precision of the
3354 * {@code BigDecimal} value.
3355 * <p>
3356 * To have an exception thrown if the conversion is inexact (in
3357 * other words if a nonzero fractional part is discarded), use the
3358 * {@link #toBigIntegerExact()} method.
3359 *
3360 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3361 * @jls 5.1.3 Narrowing Primitive Conversion
3362 */
3363 public BigInteger toBigInteger() {
3364 // force to an integer, quietly
3365 return this.setScale(0, ROUND_DOWN).inflated();
3366 }
3367
3368 /**
3369 * Converts this {@code BigDecimal} to a {@code BigInteger},
3370 * checking for lost information. An exception is thrown if this
3371 * {@code BigDecimal} has a nonzero fractional part.
3372 *
3373 * @return this {@code BigDecimal} converted to a {@code BigInteger}.
3374 * @throws ArithmeticException if {@code this} has a nonzero
3375 * fractional part.
3376 * @since 1.5
3377 */
3378 public BigInteger toBigIntegerExact() {
3379 // round to an integer, with Exception if decimal part non-0
3380 return this.setScale(0, ROUND_UNNECESSARY).inflated();
3381 }
3382
3383 /**
3384 * Converts this {@code BigDecimal} to a {@code long}.
3385 * This conversion is analogous to the
3386 * <i>narrowing primitive conversion</i> from {@code double} to
3387 * {@code short} as defined in
3388 * <cite>The Java™ Language Specification</cite>:
3389 * any fractional part of this
3390 * {@code BigDecimal} will be discarded, and if the resulting
3391 * "{@code BigInteger}" is too big to fit in a
3392 * {@code long}, only the low-order 64 bits are returned.
3393 * Note that this conversion can lose information about the
3394 * overall magnitude and precision of this {@code BigDecimal} value as well
3395 * as return a result with the opposite sign.
3396 *
3397 * @return this {@code BigDecimal} converted to a {@code long}.
3398 * @jls 5.1.3 Narrowing Primitive Conversion
3399 */
3400 @Override
3401 public long longValue(){
3402 return (intCompact != INFLATED && scale == 0) ?
3403 intCompact:
3404 toBigInteger().longValue();
3405 }
3406
3407 /**
3408 * Converts this {@code BigDecimal} to a {@code long}, checking
3409 * for lost information. If this {@code BigDecimal} has a
3410 * nonzero fractional part or is out of the possible range for a
3411 * {@code long} result then an {@code ArithmeticException} is
3412 * thrown.
3413 *
3414 * @return this {@code BigDecimal} converted to a {@code long}.
3415 * @throws ArithmeticException if {@code this} has a nonzero
3416 * fractional part, or will not fit in a {@code long}.
3417 * @since 1.5
3418 */
3437
3438 private static class LongOverflow {
3439 /** BigInteger equal to Long.MIN_VALUE. */
3440 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE);
3441
3442 /** BigInteger equal to Long.MAX_VALUE. */
3443 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE);
3444
3445 public static void check(BigDecimal num) {
3446 BigInteger intVal = num.inflated();
3447 if (intVal.compareTo(LONGMIN) < 0 ||
3448 intVal.compareTo(LONGMAX) > 0)
3449 throw new java.lang.ArithmeticException("Overflow");
3450 }
3451 }
3452
3453 /**
3454 * Converts this {@code BigDecimal} to an {@code int}.
3455 * This conversion is analogous to the
3456 * <i>narrowing primitive conversion</i> from {@code double} to
3457 * {@code short} as defined in
3458 * <cite>The Java™ Language Specification</cite>:
3459 * any fractional part of this
3460 * {@code BigDecimal} will be discarded, and if the resulting
3461 * "{@code BigInteger}" is too big to fit in an
3462 * {@code int}, only the low-order 32 bits are returned.
3463 * Note that this conversion can lose information about the
3464 * overall magnitude and precision of this {@code BigDecimal}
3465 * value as well as return a result with the opposite sign.
3466 *
3467 * @return this {@code BigDecimal} converted to an {@code int}.
3468 * @jls 5.1.3 Narrowing Primitive Conversion
3469 */
3470 @Override
3471 public int intValue() {
3472 return (intCompact != INFLATED && scale == 0) ?
3473 (int)intCompact :
3474 toBigInteger().intValue();
3475 }
3476
3477 /**
3478 * Converts this {@code BigDecimal} to an {@code int}, checking
3479 * for lost information. If this {@code BigDecimal} has a
3480 * nonzero fractional part or is out of the possible range for an
3481 * {@code int} result then an {@code ArithmeticException} is
3482 * thrown.
3483 *
3484 * @return this {@code BigDecimal} converted to an {@code int}.
3485 * @throws ArithmeticException if {@code this} has a nonzero
3486 * fractional part, or will not fit in an {@code int}.
3487 * @since 1.5
3488 */
3521 * {@code byte} result then an {@code ArithmeticException} is
3522 * thrown.
3523 *
3524 * @return this {@code BigDecimal} converted to a {@code byte}.
3525 * @throws ArithmeticException if {@code this} has a nonzero
3526 * fractional part, or will not fit in a {@code byte}.
3527 * @since 1.5
3528 */
3529 public byte byteValueExact() {
3530 long num;
3531 num = this.longValueExact(); // will check decimal part
3532 if ((byte)num != num)
3533 throw new java.lang.ArithmeticException("Overflow");
3534 return (byte)num;
3535 }
3536
3537 /**
3538 * Converts this {@code BigDecimal} to a {@code float}.
3539 * This conversion is similar to the
3540 * <i>narrowing primitive conversion</i> from {@code double} to
3541 * {@code float} as defined in
3542 * <cite>The Java™ Language Specification</cite>:
3543 * if this {@code BigDecimal} has too great a
3544 * magnitude to represent as a {@code float}, it will be
3545 * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3546 * Float#POSITIVE_INFINITY} as appropriate. Note that even when
3547 * the return value is finite, this conversion can lose
3548 * information about the precision of the {@code BigDecimal}
3549 * value.
3550 *
3551 * @return this {@code BigDecimal} converted to a {@code float}.
3552 * @jls 5.1.3 Narrowing Primitive Conversion
3553 */
3554 @Override
3555 public float floatValue(){
3556 if(intCompact != INFLATED) {
3557 if (scale == 0) {
3558 return (float)intCompact;
3559 } else {
3560 /*
3561 * If both intCompact and the scale can be exactly
3562 * represented as float values, perform a single float
3563 * multiply or divide to compute the (properly
3564 * rounded) result.
3565 */
3566 if (Math.abs(intCompact) < 1L<<22 ) {
3567 // Don't have too guard against
3568 // Math.abs(MIN_VALUE) because of outer check
3569 // against INFLATED.
3570 if (scale > 0 && scale < FLOAT_10_POW.length) {
3571 return (float)intCompact / FLOAT_10_POW[scale];
3572 } else if (scale < 0 && scale > -FLOAT_10_POW.length) {
3573 return (float)intCompact * FLOAT_10_POW[-scale];
3574 }
3575 }
3576 }
3577 }
3578 // Somewhat inefficient, but guaranteed to work.
3579 return Float.parseFloat(this.toString());
3580 }
3581
3582 /**
3583 * Converts this {@code BigDecimal} to a {@code double}.
3584 * This conversion is similar to the
3585 * <i>narrowing primitive conversion</i> from {@code double} to
3586 * {@code float} as defined
3587 * <cite>The Java™ Language Specification</cite>:
3588 * if this {@code BigDecimal} has too great a
3589 * magnitude represent as a {@code double}, it will be
3590 * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3591 * Double#POSITIVE_INFINITY} as appropriate. Note that even when
3592 * the return value is finite, this conversion can lose
3593 * information about the precision of the {@code BigDecimal}
3594 * value.
3595 *
3596 * @return this {@code BigDecimal} converted to a {@code double}.
3597 * @jls 5.1.3 Narrowing Primitive Conversion
3598 */
3599 @Override
3600 public double doubleValue(){
3601 if(intCompact != INFLATED) {
3602 if (scale == 0) {
3603 return (double)intCompact;
3604 } else {
3605 /*
3606 * If both intCompact and the scale can be exactly
3607 * represented as double values, perform a single
3608 * double multiply or divide to compute the (properly
3609 * rounded) result.
3610 */
3611 if (Math.abs(intCompact) < 1L<<52 ) {
3612 // Don't have too guard against
3613 // Math.abs(MIN_VALUE) because of outer check
3614 // against INFLATED.
3615 if (scale > 0 && scale < DOUBLE_10_POW.length) {
3616 return (double)intCompact / DOUBLE_10_POW[scale];
3617 } else if (scale < 0 && scale > -DOUBLE_10_POW.length) {
|