12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 /*
27 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
28 */
29
30 package java.math;
31
32 import java.util.Arrays;
33 import static java.math.BigInteger.LONG_MASK;
34
35 /**
36 * Immutable, arbitrary-precision signed decimal numbers. A
37 * {@code BigDecimal} consists of an arbitrary precision integer
38 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
39 * or positive, the scale is the number of digits to the right of the
40 * decimal point. If negative, the unscaled value of the number is
41 * multiplied by ten to the power of the negation of the scale. The
42 * value of the number represented by the {@code BigDecimal} is
43 * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
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
266 * compactly stored in this field and used in computations.
267 */
268 private final transient long intCompact;
269
270 // All 18-digit base ten strings fit into a long; not all 19-digit
271 // strings will
272 private static final int MAX_COMPACT_DIGITS = 18;
273
274 /* Appease the serialization gods */
275 private static final long serialVersionUID = 6108874887143696463L;
276
277 private static final ThreadLocal<StringBuilderHelper>
278 threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
279 @Override
280 protected StringBuilderHelper initialValue() {
281 return new StringBuilderHelper();
282 }
283 };
284
285 // Cache of common small BigDecimal values.
286 private static final BigDecimal zeroThroughTen[] = {
287 new BigDecimal(BigInteger.ZERO, 0, 0, 1),
288 new BigDecimal(BigInteger.ONE, 1, 0, 1),
289 new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),
290 new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
291 new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
292 new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
293 new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
294 new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
295 new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
296 new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
297 new BigDecimal(BigInteger.TEN, 10, 0, 2),
298 };
299
300 // Cache of zero scaled by 0 - 15
301 private static final BigDecimal[] ZERO_SCALED_BY = {
302 zeroThroughTen[0],
303 new BigDecimal(BigInteger.ZERO, 0, 1, 1),
304 new BigDecimal(BigInteger.ZERO, 0, 2, 1),
305 new BigDecimal(BigInteger.ZERO, 0, 3, 1),
306 new BigDecimal(BigInteger.ZERO, 0, 4, 1),
307 new BigDecimal(BigInteger.ZERO, 0, 5, 1),
308 new BigDecimal(BigInteger.ZERO, 0, 6, 1),
309 new BigDecimal(BigInteger.ZERO, 0, 7, 1),
310 new BigDecimal(BigInteger.ZERO, 0, 8, 1),
311 new BigDecimal(BigInteger.ZERO, 0, 9, 1),
312 new BigDecimal(BigInteger.ZERO, 0, 10, 1),
313 new BigDecimal(BigInteger.ZERO, 0, 11, 1),
314 new BigDecimal(BigInteger.ZERO, 0, 12, 1),
315 new BigDecimal(BigInteger.ZERO, 0, 13, 1),
316 new BigDecimal(BigInteger.ZERO, 0, 14, 1),
317 new BigDecimal(BigInteger.ZERO, 0, 15, 1),
318 };
319
320 // Half of Long.MIN_VALUE & Long.MAX_VALUE.
321 private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
322 private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
323
324 // Constants
325 /**
326 * The value 0, with a scale of 0.
327 *
328 * @since 1.5
329 */
330 public static final BigDecimal ZERO =
331 zeroThroughTen[0];
332
333 /**
334 * The value 1, with a scale of 0.
335 *
336 * @since 1.5
337 */
338 public static final BigDecimal ONE =
339 zeroThroughTen[1];
340
341 /**
342 * The value 10, with a scale of 0.
343 *
344 * @since 1.5
345 */
346 public static final BigDecimal TEN =
347 zeroThroughTen[10];
348
349 // Constructors
350
351 /**
352 * Trusted package private constructor.
353 * Trusted simply means if val is INFLATED, intVal could not be null and
354 * if intVal is null, val could not be INFLATED.
355 */
356 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
357 this.scale = scale;
358 this.precision = prec;
359 this.intCompact = val;
360 this.intVal = intVal;
361 }
362
363 /**
364 * Translates a character array representation of a
365 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
366 * same sequence of characters as the {@link #BigDecimal(String)}
367 * constructor, while allowing a sub-array to be specified.
903 : (valBits & ((1L << 52) - 1)) | (1L << 52));
904 exponent -= 1075;
905 // At this point, val == sign * significand * 2**exponent.
906
907 /*
908 * Special case zero to supress nonterminating normalization and bogus
909 * scale calculation.
910 */
911 if (significand == 0) {
912 this.intVal = BigInteger.ZERO;
913 this.scale = 0;
914 this.intCompact = 0;
915 this.precision = 1;
916 return;
917 }
918 // Normalize
919 while ((significand & 1) == 0) { // i.e., significand is even
920 significand >>= 1;
921 exponent++;
922 }
923 int scale = 0;
924 // Calculate intVal and scale
925 BigInteger intVal;
926 long compactVal = sign * significand;
927 if (exponent == 0) {
928 intVal = (compactVal == INFLATED) ? INFLATED_BIGINT : null;
929 } else {
930 if (exponent < 0) {
931 intVal = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
932 scale = -exponent;
933 } else { // (exponent > 0)
934 intVal = BigInteger.valueOf(2).pow(exponent).multiply(compactVal);
935 }
936 compactVal = compactValFor(intVal);
937 }
938 int prec = 0;
939 int mcp = mc.precision;
940 if (mcp > 0) { // do rounding
941 int mode = mc.roundingMode.oldMode;
942 int drop;
943 if (compactVal == INFLATED) {
944 prec = bigDigitLength(intVal);
945 drop = prec - mcp;
946 while (drop > 0) {
947 scale = checkScaleNonZero((long) scale - drop);
948 intVal = divideAndRoundByTenPow(intVal, drop, mode);
949 compactVal = compactValFor(intVal);
950 if (compactVal != INFLATED) {
951 break;
952 }
953 prec = bigDigitLength(intVal);
954 drop = prec - mcp;
955 }
956 }
957 if (compactVal != INFLATED) {
958 prec = longDigitLength(compactVal);
959 drop = prec - mcp;
960 while (drop > 0) {
961 scale = checkScaleNonZero((long) scale - drop);
962 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
963 prec = longDigitLength(compactVal);
964 drop = prec - mcp;
965 }
966 intVal = null;
967 }
968 }
969 this.intVal = intVal;
970 this.intCompact = compactVal;
971 this.scale = scale;
972 this.precision = prec;
973 }
974
975 /**
976 * Translates a {@code BigInteger} into a {@code BigDecimal}.
977 * The scale of the {@code BigDecimal} is zero.
978 *
979 * @param val {@code BigInteger} value to be converted to
980 * {@code BigDecimal}.
981 */
982 public BigDecimal(BigInteger val) {
983 scale = 0;
984 intVal = val;
985 intCompact = compactValFor(val);
986 }
987
988 /**
989 * Translates a {@code BigInteger} into a {@code BigDecimal}
990 * rounding according to the context settings. The scale of the
991 * {@code BigDecimal} is zero.
1081 public BigDecimal(int val) {
1082 this.intCompact = val;
1083 this.scale = 0;
1084 this.intVal = null;
1085 }
1086
1087 /**
1088 * Translates an {@code int} into a {@code BigDecimal}, with
1089 * rounding according to the context settings. The scale of the
1090 * {@code BigDecimal}, before any rounding, is zero.
1091 *
1092 * @param val {@code int} value to be converted to {@code BigDecimal}.
1093 * @param mc the context to use.
1094 * @throws ArithmeticException if the result is inexact but the
1095 * rounding mode is {@code UNNECESSARY}.
1096 * @since 1.5
1097 */
1098 public BigDecimal(int val, MathContext mc) {
1099 int mcp = mc.precision;
1100 long compactVal = val;
1101 int scale = 0;
1102 int prec = 0;
1103 if (mcp > 0) { // do rounding
1104 prec = longDigitLength(compactVal);
1105 int drop = prec - mcp; // drop can't be more than 18
1106 while (drop > 0) {
1107 scale = checkScaleNonZero((long) scale - drop);
1108 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1109 prec = longDigitLength(compactVal);
1110 drop = prec - mcp;
1111 }
1112 }
1113 this.intVal = null;
1114 this.intCompact = compactVal;
1115 this.scale = scale;
1116 this.precision = prec;
1117 }
1118
1119 /**
1120 * Translates a {@code long} into a {@code BigDecimal}. The
1121 * scale of the {@code BigDecimal} is zero.
1122 *
1123 * @param val {@code long} value to be converted to {@code BigDecimal}.
1124 * @since 1.5
1125 */
1126 public BigDecimal(long val) {
1127 this.intCompact = val;
1128 this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1129 this.scale = 0;
1130 }
1131
1132 /**
1133 * Translates a {@code long} into a {@code BigDecimal}, with
1134 * rounding according to the context settings. The scale of the
1135 * {@code BigDecimal}, before any rounding, is zero.
1136 *
1137 * @param val {@code long} value to be converted to {@code BigDecimal}.
1138 * @param mc the context to use.
1139 * @throws ArithmeticException if the result is inexact but the
1140 * rounding mode is {@code UNNECESSARY}.
1141 * @since 1.5
1142 */
1143 public BigDecimal(long val, MathContext mc) {
1144 int mcp = mc.precision;
1145 int mode = mc.roundingMode.oldMode;
1146 int prec = 0;
1147 int scale = 0;
1148 BigInteger intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1149 if (mcp > 0) { // do rounding
1150 if (val == INFLATED) {
1151 prec = 19;
1152 int drop = prec - mcp;
1153 while (drop > 0) {
1154 scale = checkScaleNonZero((long) scale - drop);
1155 intVal = divideAndRoundByTenPow(intVal, drop, mode);
1156 val = compactValFor(intVal);
1157 if (val != INFLATED) {
1158 break;
1159 }
1160 prec = bigDigitLength(intVal);
1161 drop = prec - mcp;
1162 }
1163 }
1164 if (val != INFLATED) {
1165 prec = longDigitLength(val);
1166 int drop = prec - mcp;
1167 while (drop > 0) {
1168 scale = checkScaleNonZero((long) scale - drop);
1169 val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1170 prec = longDigitLength(val);
1171 drop = prec - mcp;
1172 }
1173 intVal = null;
1174 }
1175 }
1176 this.intVal = intVal;
1177 this.intCompact = val;
1178 this.scale = scale;
1179 this.precision = prec;
1180 }
1181
1182 // Static Factory Methods
1183
1184 /**
1185 * Translates a {@code long} unscaled value and an
1186 * {@code int} scale into a {@code BigDecimal}. This
1187 * {@literal "static factory method"} is provided in preference to
1188 * a ({@code long}, {@code int}) constructor because it
1189 * allows for reuse of frequently used {@code BigDecimal} values..
1190 *
1191 * @param unscaledVal unscaled value of the {@code BigDecimal}.
1192 * @param scale scale of the {@code BigDecimal}.
1193 * @return a {@code BigDecimal} whose value is
1194 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
1195 */
1196 public static BigDecimal valueOf(long unscaledVal, int scale) {
1197 if (scale == 0)
1198 return valueOf(unscaledVal);
1199 else if (unscaledVal == 0) {
1200 return zeroValueOf(scale);
1201 }
1202 return new BigDecimal(unscaledVal == INFLATED ?
1203 INFLATED_BIGINT : null,
1204 unscaledVal, scale, 0);
1205 }
1206
1207 /**
1208 * Translates a {@code long} value into a {@code BigDecimal}
1209 * with a scale of zero. This {@literal "static factory method"}
1210 * is provided in preference to a ({@code long}) constructor
1211 * because it allows for reuse of frequently used
1212 * {@code BigDecimal} values.
1213 *
1214 * @param val value of the {@code BigDecimal}.
1215 * @return a {@code BigDecimal} whose value is {@code val}.
1216 */
1217 public static BigDecimal valueOf(long val) {
1218 if (val >= 0 && val < zeroThroughTen.length)
1219 return zeroThroughTen[(int)val];
1220 else if (val != INFLATED)
1221 return new BigDecimal(null, val, 0, 0);
1222 return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1223 }
1224
1225 static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1226 if (scale == 0 && unscaledVal >= 0 && unscaledVal < zeroThroughTen.length) {
1227 return zeroThroughTen[(int) unscaledVal];
1228 } else if (unscaledVal == 0) {
1229 return zeroValueOf(scale);
1230 }
1231 return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1232 unscaledVal, scale, prec);
1233 }
1234
1235 static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1236 long val = compactValFor(intVal);
1237 if (val == 0) {
1238 return zeroValueOf(scale);
1239 } else if (scale == 0 && val >= 0 && val < zeroThroughTen.length) {
1240 return zeroThroughTen[(int) val];
1241 }
1242 return new BigDecimal(intVal, val, scale, prec);
1243 }
1244
1245 static BigDecimal zeroValueOf(int scale) {
1246 if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1247 return ZERO_SCALED_BY[scale];
1248 else
1249 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1250 }
1251
1252 /**
1253 * Translates a {@code double} into a {@code BigDecimal}, using
1254 * the {@code double}'s canonical string representation provided
1255 * by the {@link Double#toString(double)} method.
1256 *
1257 * <p><b>Note:</b> This is generally the preferred way to convert
1258 * a {@code double} (or {@code float}) into a
1259 * {@code BigDecimal}, as the value returned is equal to that
1260 * resulting from constructing a {@code BigDecimal} from the
2603
2604 // Comparison Operations
2605
2606 /**
2607 * Compares this {@code BigDecimal} with the specified
2608 * {@code BigDecimal}. Two {@code BigDecimal} objects that are
2609 * equal in value but have a different scale (like 2.0 and 2.00)
2610 * are considered equal by this method. This method is provided
2611 * in preference to individual methods for each of the six boolean
2612 * comparison operators ({@literal <}, ==,
2613 * {@literal >}, {@literal >=}, !=, {@literal <=}). The
2614 * suggested idiom for performing these comparisons is:
2615 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
2616 * <<i>op</i>> is one of the six comparison operators.
2617 *
2618 * @param val {@code BigDecimal} to which this {@code BigDecimal} is
2619 * to be compared.
2620 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2621 * less than, equal to, or greater than {@code val}.
2622 */
2623 public int compareTo(BigDecimal val) {
2624 // Quick path for equal scale and non-inflated case.
2625 if (scale == val.scale) {
2626 long xs = intCompact;
2627 long ys = val.intCompact;
2628 if (xs != INFLATED && ys != INFLATED)
2629 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2630 }
2631 int xsign = this.signum();
2632 int ysign = val.signum();
2633 if (xsign != ysign)
2634 return (xsign > ysign) ? 1 : -1;
2635 if (xsign == 0)
2636 return 0;
2637 int cmp = compareMagnitude(val);
2638 return (xsign > 0) ? cmp : -cmp;
2639 }
2640
2641 /**
2642 * Version of compareTo that ignores sign.
2643 */
2644 private int compareMagnitude(BigDecimal val) {
2645 // Match scales, avoid unnecessary inflation
2646 long ys = val.intCompact;
2647 long xs = this.intCompact;
2648 if (xs == 0)
2649 return (ys == 0) ? 0 : -1;
2650 if (ys == 0)
2651 return 1;
2652
2653 long sdiff = (long)this.scale - val.scale;
2654 if (sdiff != 0) {
2655 // Avoid matching scales if the (adjusted) exponents differ
2656 long xae = (long)this.precision() - this.scale; // [-1]
2657 long yae = (long)val.precision() - val.scale; // [-1]
2658 if (xae < yae)
2659 return -1;
2660 if (xae > yae)
2661 return 1;
2662 BigInteger rb = null;
2663 if (sdiff < 0) {
2664 // The cases sdiff <= Integer.MIN_VALUE intentionally fall through.
2665 if ( sdiff > Integer.MIN_VALUE &&
2666 (xs == INFLATED ||
2667 (xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&
2668 ys == INFLATED) {
2669 rb = bigMultiplyPowerTen((int)-sdiff);
2670 return rb.compareMagnitude(val.intVal);
2671 }
2672 } else { // sdiff > 0
2673 // The cases sdiff > Integer.MAX_VALUE intentionally fall through.
2674 if ( sdiff <= Integer.MAX_VALUE &&
2675 (ys == INFLATED ||
2676 (ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&
2677 xs == INFLATED) {
2678 rb = val.bigMultiplyPowerTen((int)sdiff);
2679 return this.intVal.compareMagnitude(rb);
2680 }
2681 }
2682 }
2683 if (xs != INFLATED)
2684 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2685 else if (ys != INFLATED)
2686 return 1;
2687 else
2688 return this.intVal.compareMagnitude(val.intVal);
2689 }
2690
2691 /**
2692 * Compares this {@code BigDecimal} with the specified
2693 * {@code Object} for equality. Unlike {@link
2694 * #compareTo(BigDecimal) compareTo}, this method considers two
2695 * {@code BigDecimal} objects equal only if they are equal in
2696 * value and scale (thus 2.0 is not equal to 2.00 when compared by
2697 * this method).
2698 *
2863 * java.text.NumberFormat} class and its subclasses.
2864 *
2865 * <li>The {@link #toEngineeringString} method may be used for
2866 * presenting numbers with exponents in engineering notation, and the
2867 * {@link #setScale(int,RoundingMode) setScale} method may be used for
2868 * rounding a {@code BigDecimal} so it has a known number of digits after
2869 * the decimal point.
2870 *
2871 * <li>The digit-to-character mapping provided by
2872 * {@code Character.forDigit} is used.
2873 *
2874 * </ol>
2875 *
2876 * @return string representation of this {@code BigDecimal}.
2877 * @see Character#forDigit
2878 * @see #BigDecimal(java.lang.String)
2879 */
2880 @Override
2881 public String toString() {
2882 String sc = stringCache;
2883 if (sc == null)
2884 stringCache = sc = layoutChars(true);
2885 return sc;
2886 }
2887
2888 /**
2889 * Returns a string representation of this {@code BigDecimal},
2890 * using engineering notation if an exponent is needed.
2891 *
2892 * <p>Returns a string that represents the {@code BigDecimal} as
2893 * described in the {@link #toString()} method, except that if
2894 * exponential notation is used, the power of ten is adjusted to
2895 * be a multiple of three (engineering notation) such that the
2896 * integer part of nonzero values will be in the range 1 through
2897 * 999. If exponential notation is used for zero values, a
2898 * decimal point and one or two fractional zero digits are used so
2899 * that the scale of the zero value is preserved. Note that
2900 * unlike the output of {@link #toString()}, the output of this
2901 * method is <em>not</em> guaranteed to recover the same [integer,
2902 * scale] pair of this {@code BigDecimal} if the output string is
2903 * converting back to a {@code BigDecimal} using the {@linkplain
2904 * #BigDecimal(String) string constructor}. The result of this method meets
2941 * method in 1.4 and earlier releases.)
2942 *
2943 * @return a string representation of this {@code BigDecimal}
2944 * without an exponent field.
2945 * @since 1.5
2946 * @see #toString()
2947 * @see #toEngineeringString()
2948 */
2949 public String toPlainString() {
2950 if(scale==0) {
2951 if(intCompact!=INFLATED) {
2952 return Long.toString(intCompact);
2953 } else {
2954 return intVal.toString();
2955 }
2956 }
2957 if(this.scale<0) { // No decimal point
2958 if(signum()==0) {
2959 return "0";
2960 }
2961 int tailingZeros = checkScaleNonZero((-(long)scale));
2962 StringBuilder buf;
2963 if(intCompact!=INFLATED) {
2964 buf = new StringBuilder(20+tailingZeros);
2965 buf.append(intCompact);
2966 } else {
2967 String str = intVal.toString();
2968 buf = new StringBuilder(str.length()+tailingZeros);
2969 buf.append(str);
2970 }
2971 for (int i = 0; i < tailingZeros; i++)
2972 buf.append('0');
2973 return buf.toString();
2974 }
2975 String str ;
2976 if(intCompact!=INFLATED) {
2977 str = Long.toString(Math.abs(intCompact));
2978 } else {
2979 str = intVal.abs().toString();
2980 }
2981 return getValueString(signum(), str, scale);
2982 }
2983
2984 /* Returns a digit.digit string */
2985 private String getValueString(int signum, String intString, int scale) {
2986 /* Insert decimal point */
2987 StringBuilder buf;
2988 int insertionPoint = intString.length() - scale;
2989 if (insertionPoint == 0) { /* Point goes right before intVal */
2990 return (signum<0 ? "-0." : "0.") + intString;
2991 } else if (insertionPoint > 0) { /* Point goes inside intVal */
2992 buf = new StringBuilder(intString);
2993 buf.insert(insertionPoint, '.');
2994 if (signum < 0)
2995 buf.insert(0, '-');
2996 } else { /* We must insert zeros between point and intVal */
2997 buf = new StringBuilder(3-insertionPoint + intString.length());
2998 buf.append(signum<0 ? "-0." : "0.");
2999 for (int i=0; i<-insertionPoint; i++)
3000 buf.append('0');
3001 buf.append(intString);
3002 }
3003 return buf.toString();
3004 }
3005
3006 /**
3007 * Converts this {@code BigDecimal} to a {@code BigInteger}.
3008 * This conversion is analogous to the
3009 * <i>narrowing primitive conversion</i> from {@code double} to
3010 * {@code long} as defined in section 5.1.3 of
3011 * <cite>The Java™ Language Specification</cite>:
3012 * any fractional part of this
3013 * {@code BigDecimal} will be discarded. Note that this
3014 * conversion can lose information about the precision of the
3015 * {@code BigDecimal} value.
3016 * <p>
3017 * To have an exception thrown if the conversion is inexact (in
3018 * other words if a nonzero fractional part is discarded), use the
3019 * {@link #toBigIntegerExact()} method.
3020 *
3039 // round to an integer, with Exception if decimal part non-0
3040 return this.setScale(0, ROUND_UNNECESSARY).inflated();
3041 }
3042
3043 /**
3044 * Converts this {@code BigDecimal} to a {@code long}.
3045 * This conversion is analogous to the
3046 * <i>narrowing primitive conversion</i> from {@code double} to
3047 * {@code short} as defined in section 5.1.3 of
3048 * <cite>The Java™ Language Specification</cite>:
3049 * any fractional part of this
3050 * {@code BigDecimal} will be discarded, and if the resulting
3051 * "{@code BigInteger}" is too big to fit in a
3052 * {@code long}, only the low-order 64 bits are returned.
3053 * Note that this conversion can lose information about the
3054 * overall magnitude and precision of this {@code BigDecimal} value as well
3055 * as return a result with the opposite sign.
3056 *
3057 * @return this {@code BigDecimal} converted to a {@code long}.
3058 */
3059 public long longValue(){
3060 return (intCompact != INFLATED && scale == 0) ?
3061 intCompact:
3062 toBigInteger().longValue();
3063 }
3064
3065 /**
3066 * Converts this {@code BigDecimal} to a {@code long}, checking
3067 * for lost information. If this {@code BigDecimal} has a
3068 * nonzero fractional part or is out of the possible range for a
3069 * {@code long} result then an {@code ArithmeticException} is
3070 * thrown.
3071 *
3072 * @return this {@code BigDecimal} converted to a {@code long}.
3073 * @throws ArithmeticException if {@code this} has a nonzero
3074 * fractional part, or will not fit in a {@code long}.
3075 * @since 1.5
3076 */
3077 public long longValueExact() {
3078 if (intCompact != INFLATED && scale == 0)
3107 throw new java.lang.ArithmeticException("Overflow");
3108 }
3109 }
3110
3111 /**
3112 * Converts this {@code BigDecimal} to an {@code int}.
3113 * This conversion is analogous to the
3114 * <i>narrowing primitive conversion</i> from {@code double} to
3115 * {@code short} as defined in section 5.1.3 of
3116 * <cite>The Java™ Language Specification</cite>:
3117 * any fractional part of this
3118 * {@code BigDecimal} will be discarded, and if the resulting
3119 * "{@code BigInteger}" is too big to fit in an
3120 * {@code int}, only the low-order 32 bits are returned.
3121 * Note that this conversion can lose information about the
3122 * overall magnitude and precision of this {@code BigDecimal}
3123 * value as well as return a result with the opposite sign.
3124 *
3125 * @return this {@code BigDecimal} converted to an {@code int}.
3126 */
3127 public int intValue() {
3128 return (intCompact != INFLATED && scale == 0) ?
3129 (int)intCompact :
3130 toBigInteger().intValue();
3131 }
3132
3133 /**
3134 * Converts this {@code BigDecimal} to an {@code int}, checking
3135 * for lost information. If this {@code BigDecimal} has a
3136 * nonzero fractional part or is out of the possible range for an
3137 * {@code int} result then an {@code ArithmeticException} is
3138 * thrown.
3139 *
3140 * @return this {@code BigDecimal} converted to an {@code int}.
3141 * @throws ArithmeticException if {@code this} has a nonzero
3142 * fractional part, or will not fit in an {@code int}.
3143 * @since 1.5
3144 */
3145 public int intValueExact() {
3146 long num;
3189 throw new java.lang.ArithmeticException("Overflow");
3190 return (byte)num;
3191 }
3192
3193 /**
3194 * Converts this {@code BigDecimal} to a {@code float}.
3195 * This conversion is similar to the
3196 * <i>narrowing primitive conversion</i> from {@code double} to
3197 * {@code float} as defined in section 5.1.3 of
3198 * <cite>The Java™ Language Specification</cite>:
3199 * if this {@code BigDecimal} has too great a
3200 * magnitude to represent as a {@code float}, it will be
3201 * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3202 * Float#POSITIVE_INFINITY} as appropriate. Note that even when
3203 * the return value is finite, this conversion can lose
3204 * information about the precision of the {@code BigDecimal}
3205 * value.
3206 *
3207 * @return this {@code BigDecimal} converted to a {@code float}.
3208 */
3209 public float floatValue(){
3210 if(intCompact != INFLATED) {
3211 if (scale == 0) {
3212 return (float)intCompact;
3213 } else {
3214 /*
3215 * If both intCompact and the scale can be exactly
3216 * represented as float values, perform a single float
3217 * multiply or divide to compute the (properly
3218 * rounded) result.
3219 */
3220 if (Math.abs(intCompact) < 1L<<22 ) {
3221 // Don't have too guard against
3222 // Math.abs(MIN_VALUE) because of outer check
3223 // against INFLATED.
3224 if (scale > 0 && scale < float10pow.length) {
3225 return (float)intCompact / float10pow[scale];
3226 } else if (scale < 0 && scale > -float10pow.length) {
3227 return (float)intCompact * float10pow[-scale];
3228 }
3229 }
3230 }
3231 }
3232 // Somewhat inefficient, but guaranteed to work.
3233 return Float.parseFloat(this.toString());
3234 }
3235
3236 /**
3237 * Converts this {@code BigDecimal} to a {@code double}.
3238 * This conversion is similar to the
3239 * <i>narrowing primitive conversion</i> from {@code double} to
3240 * {@code float} as defined in section 5.1.3 of
3241 * <cite>The Java™ Language Specification</cite>:
3242 * if this {@code BigDecimal} has too great a
3243 * magnitude represent as a {@code double}, it will be
3244 * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3245 * Double#POSITIVE_INFINITY} as appropriate. Note that even when
3246 * the return value is finite, this conversion can lose
3247 * information about the precision of the {@code BigDecimal}
3248 * value.
3249 *
3250 * @return this {@code BigDecimal} converted to a {@code double}.
3251 */
3252 public double doubleValue(){
3253 if(intCompact != INFLATED) {
3254 if (scale == 0) {
3255 return (double)intCompact;
3256 } else {
3257 /*
3258 * If both intCompact and the scale can be exactly
3259 * represented as double values, perform a single
3260 * double multiply or divide to compute the (properly
3261 * rounded) result.
3262 */
3263 if (Math.abs(intCompact) < 1L<<52 ) {
3264 // Don't have too guard against
3265 // Math.abs(MIN_VALUE) because of outer check
3266 // against INFLATED.
3267 if (scale > 0 && scale < double10pow.length) {
3268 return (double)intCompact / double10pow[scale];
3269 } else if (scale < 0 && scale > -double10pow.length) {
3270 return (double)intCompact * double10pow[-scale];
3271 }
3272 }
3273 }
3274 }
3275 // Somewhat inefficient, but guaranteed to work.
3276 return Double.parseDouble(this.toString());
3277 }
3278
3279 /**
3280 * Powers of 10 which can be represented exactly in {@code
3281 * double}.
3282 */
3283 private static final double double10pow[] = {
3284 1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
3285 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11,
3286 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3287 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3288 };
3289
3290 /**
3291 * Powers of 10 which can be represented exactly in {@code
3292 * float}.
3293 */
3294 private static final float float10pow[] = {
3295 1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3296 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3297 };
3298
3299 /**
3300 * Returns the size of an ulp, a unit in the last place, of this
3301 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
3302 * value is the positive distance between this value and the
3303 * {@code BigDecimal} value next larger in magnitude with the
3304 * same number of digits. An ulp of a zero value is numerically
3305 * equal to 1 with the scale of {@code this}. The result is
3306 * stored with the same scale as {@code this} so the result
3307 * for zero and nonzero values is equal to {@code [1,
3308 * this.scale()]}.
3309 *
3310 * @return the size of an ulp of {@code this}
3311 * @since 1.5
3312 */
3313 public BigDecimal ulp() {
3314 return BigDecimal.valueOf(1, this.scale(), 1);
3487 sig++;
3488 if (signum() == 0) {
3489 switch (sig) {
3490 case 1:
3491 buf.append('0'); // exponent is a multiple of three
3492 break;
3493 case 2:
3494 buf.append("0.00");
3495 adjusted += 3;
3496 break;
3497 case 3:
3498 buf.append("0.0");
3499 adjusted += 3;
3500 break;
3501 default:
3502 throw new AssertionError("Unexpected sig value " + sig);
3503 }
3504 } else if (sig >= coeffLen) { // significand all in integer
3505 buf.append(coeff, offset, coeffLen);
3506 // may need some zeros, too
3507 for (int i = sig - coeffLen; i > 0; i--)
3508 buf.append('0');
3509 } else { // xx.xxE form
3510 buf.append(coeff, offset, sig);
3511 buf.append('.');
3512 buf.append(coeff, offset + sig, coeffLen - sig);
3513 }
3514 }
3515 if (adjusted != 0) { // [!sci could have made 0]
3516 buf.append('E');
3517 if (adjusted > 0) // force sign for positive
3518 buf.append('+');
3519 buf.append(adjusted);
3520 }
3521 }
3522 return buf.toString();
3523 }
3524
3525 /**
3526 * Return 10 to the power n, as a {@code BigInteger}.
3527 *
3528 * @param n the power of ten to be returned (>=0)
3542
3543 return BigInteger.TEN.pow(n);
3544 }
3545
3546 /**
3547 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3548 *
3549 * @param n the power of ten to be returned (>=0)
3550 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3551 * in the meantime, the BIG_TEN_POWERS_TABLE array gets
3552 * expanded to the size greater than n.
3553 */
3554 private static BigInteger expandBigIntegerTenPowers(int n) {
3555 synchronized(BigDecimal.class) {
3556 BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3557 int curLen = pows.length;
3558 // The following comparison and the above synchronized statement is
3559 // to prevent multiple threads from expanding the same array.
3560 if (curLen <= n) {
3561 int newLen = curLen << 1;
3562 while (newLen <= n)
3563 newLen <<= 1;
3564 pows = Arrays.copyOf(pows, newLen);
3565 for (int i = curLen; i < newLen; i++)
3566 pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3567 // Based on the following facts:
3568 // 1. pows is a private local varible;
3569 // 2. the following store is a volatile store.
3570 // the newly created array elements can be safely published.
3571 BIG_TEN_POWERS_TABLE = pows;
3572 }
3573 return pows[n];
3574 }
3575 }
3576
3577 private static final long[] LONG_TEN_POWERS_TABLE = {
3578 1, // 0 / 10^0
3579 10, // 1 / 10^1
3580 100, // 2 / 10^2
3581 1000, // 3 / 10^3
3582 10000, // 4 / 10^4
3583 100000, // 5 / 10^5
3584 1000000, // 6 / 10^6
3585 10000000, // 7 / 10^7
3586 100000000, // 8 / 10^8
3686 if (intVal == null) {
3687 return BigInteger.valueOf(intCompact);
3688 }
3689 return intVal;
3690 }
3691
3692 /**
3693 * Match the scales of two {@code BigDecimal}s to align their
3694 * least significant digits.
3695 *
3696 * <p>If the scales of val[0] and val[1] differ, rescale
3697 * (non-destructively) the lower-scaled {@code BigDecimal} so
3698 * they match. That is, the lower-scaled reference will be
3699 * replaced by a reference to a new object with the same scale as
3700 * the other {@code BigDecimal}.
3701 *
3702 * @param val array of two elements referring to the two
3703 * {@code BigDecimal}s to be aligned.
3704 */
3705 private static void matchScale(BigDecimal[] val) {
3706 if (val[0].scale == val[1].scale) {
3707 return;
3708 } else if (val[0].scale < val[1].scale) {
3709 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3710 } else if (val[1].scale < val[0].scale) {
3711 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3712 }
3713 }
3714
3715 private static class UnsafeHolder {
3716 private static final sun.misc.Unsafe unsafe;
3717 private static final long intCompactOffset;
3718 private static final long intValOffset;
3719 static {
3720 try {
3721 unsafe = sun.misc.Unsafe.getUnsafe();
3722 intCompactOffset = unsafe.objectFieldOffset
3723 (BigDecimal.class.getDeclaredField("intCompact"));
3724 intValOffset = unsafe.objectFieldOffset
3725 (BigDecimal.class.getDeclaredField("intVal"));
3726 } catch (Exception ex) {
3727 throw new ExceptionInInitializerError(ex);
3728 }
4192 */
4193 private static boolean needIncrement(long ldivisor, int roundingMode,
4194 int qsign, long q, long r) {
4195 assert r != 0L;
4196
4197 int cmpFracHalf;
4198 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4199 cmpFracHalf = 1; // 2 * r can't fit into long
4200 } else {
4201 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4202 }
4203
4204 return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4205 }
4206
4207 /**
4208 * Divides {@code BigInteger} value by {@code long} value and
4209 * do rounding based on the passed in roundingMode.
4210 */
4211 private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4212 boolean isRemainderZero; // record remainder is zero or not
4213 int qsign; // quotient sign
4214 long r = 0; // store quotient & remainder in long
4215 MutableBigInteger mq = null; // store quotient
4216 // Descend into mutables for faster remainder checks
4217 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4218 mq = new MutableBigInteger();
4219 r = mdividend.divide(ldivisor, mq);
4220 isRemainderZero = (r == 0);
4221 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4222 if (!isRemainderZero) {
4223 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4224 mq.add(MutableBigInteger.ONE);
4225 }
4226 }
4227 return mq.toBigInteger(qsign);
4228 }
4229
4230 /**
4231 * Internally used for division operation for division {@code BigInteger}
4232 * by {@code long}.
4233 * The returned {@code BigDecimal} object is the quotient whose scale is set
4234 * to the passed in scale. If the remainder is not zero, it will be rounded
4235 * based on the passed in roundingMode. Also, if the remainder is zero and
4236 * the last parameter, i.e. preferredScale is NOT equal to scale, the
4237 * trailing zeros of the result is stripped to match the preferredScale.
4238 */
4239 private static BigDecimal divideAndRound(BigInteger bdividend,
4240 long ldivisor, int scale, int roundingMode, int preferredScale) {
4241 boolean isRemainderZero; // record remainder is zero or not
4242 int qsign; // quotient sign
4243 long r = 0; // store quotient & remainder in long
4244 MutableBigInteger mq = null; // store quotient
4245 // Descend into mutables for faster remainder checks
4246 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4247 mq = new MutableBigInteger();
4248 r = mdividend.divide(ldivisor, mq);
4249 isRemainderZero = (r == 0);
4250 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4251 if (!isRemainderZero) {
4252 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4253 mq.add(MutableBigInteger.ONE);
4254 }
4255 return mq.toBigDecimal(qsign, scale);
4256 } else {
4257 if (preferredScale != scale) {
4258 long compactVal = mq.toCompactValue(qsign);
4259 if(compactVal!=INFLATED) {
4260 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4261 }
4262 BigInteger intVal = mq.toBigInteger(qsign);
4263 return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4264 } else {
4265 return mq.toBigDecimal(qsign, scale);
4266 }
4267 }
4268 }
4269
4270 /**
|
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 /*
27 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
28 */
29
30 package java.math;
31
32 import static java.math.BigInteger.LONG_MASK;
33 import java.util.Arrays;
34
35 /**
36 * Immutable, arbitrary-precision signed decimal numbers. A
37 * {@code BigDecimal} consists of an arbitrary precision integer
38 * <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
39 * or positive, the scale is the number of digits to the right of the
40 * decimal point. If negative, the unscaled value of the number is
41 * multiplied by ten to the power of the negation of the scale. The
42 * value of the number represented by the {@code BigDecimal} is
43 * therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
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
266 * compactly stored in this field and used in computations.
267 */
268 private final transient long intCompact;
269
270 // All 18-digit base ten strings fit into a long; not all 19-digit
271 // strings will
272 private static final int MAX_COMPACT_DIGITS = 18;
273
274 /* Appease the serialization gods */
275 private static final long serialVersionUID = 6108874887143696463L;
276
277 private static final ThreadLocal<StringBuilderHelper>
278 threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
279 @Override
280 protected StringBuilderHelper initialValue() {
281 return new StringBuilderHelper();
282 }
283 };
284
285 // Cache of common small BigDecimal values.
286 private static final BigDecimal ZERO_THROUGH_TEN[] = {
287 new BigDecimal(BigInteger.ZERO, 0, 0, 1),
288 new BigDecimal(BigInteger.ONE, 1, 0, 1),
289 new BigDecimal(BigInteger.valueOf(2), 2, 0, 1),
290 new BigDecimal(BigInteger.valueOf(3), 3, 0, 1),
291 new BigDecimal(BigInteger.valueOf(4), 4, 0, 1),
292 new BigDecimal(BigInteger.valueOf(5), 5, 0, 1),
293 new BigDecimal(BigInteger.valueOf(6), 6, 0, 1),
294 new BigDecimal(BigInteger.valueOf(7), 7, 0, 1),
295 new BigDecimal(BigInteger.valueOf(8), 8, 0, 1),
296 new BigDecimal(BigInteger.valueOf(9), 9, 0, 1),
297 new BigDecimal(BigInteger.TEN, 10, 0, 2),
298 };
299
300 // Cache of zero scaled by 0 - 15
301 private static final BigDecimal[] ZERO_SCALED_BY = {
302 ZERO_THROUGH_TEN[0],
303 new BigDecimal(BigInteger.ZERO, 0, 1, 1),
304 new BigDecimal(BigInteger.ZERO, 0, 2, 1),
305 new BigDecimal(BigInteger.ZERO, 0, 3, 1),
306 new BigDecimal(BigInteger.ZERO, 0, 4, 1),
307 new BigDecimal(BigInteger.ZERO, 0, 5, 1),
308 new BigDecimal(BigInteger.ZERO, 0, 6, 1),
309 new BigDecimal(BigInteger.ZERO, 0, 7, 1),
310 new BigDecimal(BigInteger.ZERO, 0, 8, 1),
311 new BigDecimal(BigInteger.ZERO, 0, 9, 1),
312 new BigDecimal(BigInteger.ZERO, 0, 10, 1),
313 new BigDecimal(BigInteger.ZERO, 0, 11, 1),
314 new BigDecimal(BigInteger.ZERO, 0, 12, 1),
315 new BigDecimal(BigInteger.ZERO, 0, 13, 1),
316 new BigDecimal(BigInteger.ZERO, 0, 14, 1),
317 new BigDecimal(BigInteger.ZERO, 0, 15, 1),
318 };
319
320 // Half of Long.MIN_VALUE & Long.MAX_VALUE.
321 private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2;
322 private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2;
323
324 // Constants
325 /**
326 * The value 0, with a scale of 0.
327 *
328 * @since 1.5
329 */
330 public static final BigDecimal ZERO =
331 ZERO_THROUGH_TEN[0];
332
333 /**
334 * The value 1, with a scale of 0.
335 *
336 * @since 1.5
337 */
338 public static final BigDecimal ONE =
339 ZERO_THROUGH_TEN[1];
340
341 /**
342 * The value 10, with a scale of 0.
343 *
344 * @since 1.5
345 */
346 public static final BigDecimal TEN =
347 ZERO_THROUGH_TEN[10];
348
349 // Constructors
350
351 /**
352 * Trusted package private constructor.
353 * Trusted simply means if val is INFLATED, intVal could not be null and
354 * if intVal is null, val could not be INFLATED.
355 */
356 BigDecimal(BigInteger intVal, long val, int scale, int prec) {
357 this.scale = scale;
358 this.precision = prec;
359 this.intCompact = val;
360 this.intVal = intVal;
361 }
362
363 /**
364 * Translates a character array representation of a
365 * {@code BigDecimal} into a {@code BigDecimal}, accepting the
366 * same sequence of characters as the {@link #BigDecimal(String)}
367 * constructor, while allowing a sub-array to be specified.
903 : (valBits & ((1L << 52) - 1)) | (1L << 52));
904 exponent -= 1075;
905 // At this point, val == sign * significand * 2**exponent.
906
907 /*
908 * Special case zero to supress nonterminating normalization and bogus
909 * scale calculation.
910 */
911 if (significand == 0) {
912 this.intVal = BigInteger.ZERO;
913 this.scale = 0;
914 this.intCompact = 0;
915 this.precision = 1;
916 return;
917 }
918 // Normalize
919 while ((significand & 1) == 0) { // i.e., significand is even
920 significand >>= 1;
921 exponent++;
922 }
923 int scl = 0;
924 // Calculate intVal and scale
925 BigInteger rb;
926 long compactVal = sign * significand;
927 if (exponent == 0) {
928 rb = (compactVal == INFLATED) ? INFLATED_BIGINT : null;
929 } else {
930 if (exponent < 0) {
931 rb = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal);
932 scl = -exponent;
933 } else { // (exponent > 0)
934 rb = BigInteger.valueOf(2).pow(exponent).multiply(compactVal);
935 }
936 compactVal = compactValFor(rb);
937 }
938 int prec = 0;
939 int mcp = mc.precision;
940 if (mcp > 0) { // do rounding
941 int mode = mc.roundingMode.oldMode;
942 int drop;
943 if (compactVal == INFLATED) {
944 prec = bigDigitLength(rb);
945 drop = prec - mcp;
946 while (drop > 0) {
947 scl = checkScaleNonZero((long) scl - drop);
948 rb = divideAndRoundByTenPow(rb, drop, mode);
949 compactVal = compactValFor(rb);
950 if (compactVal != INFLATED) {
951 break;
952 }
953 prec = bigDigitLength(rb);
954 drop = prec - mcp;
955 }
956 }
957 if (compactVal != INFLATED) {
958 prec = longDigitLength(compactVal);
959 drop = prec - mcp;
960 while (drop > 0) {
961 scl = checkScaleNonZero((long) scl - drop);
962 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
963 prec = longDigitLength(compactVal);
964 drop = prec - mcp;
965 }
966 rb = null;
967 }
968 }
969 this.intVal = rb;
970 this.intCompact = compactVal;
971 this.scale = scl;
972 this.precision = prec;
973 }
974
975 /**
976 * Translates a {@code BigInteger} into a {@code BigDecimal}.
977 * The scale of the {@code BigDecimal} is zero.
978 *
979 * @param val {@code BigInteger} value to be converted to
980 * {@code BigDecimal}.
981 */
982 public BigDecimal(BigInteger val) {
983 scale = 0;
984 intVal = val;
985 intCompact = compactValFor(val);
986 }
987
988 /**
989 * Translates a {@code BigInteger} into a {@code BigDecimal}
990 * rounding according to the context settings. The scale of the
991 * {@code BigDecimal} is zero.
1081 public BigDecimal(int val) {
1082 this.intCompact = val;
1083 this.scale = 0;
1084 this.intVal = null;
1085 }
1086
1087 /**
1088 * Translates an {@code int} into a {@code BigDecimal}, with
1089 * rounding according to the context settings. The scale of the
1090 * {@code BigDecimal}, before any rounding, is zero.
1091 *
1092 * @param val {@code int} value to be converted to {@code BigDecimal}.
1093 * @param mc the context to use.
1094 * @throws ArithmeticException if the result is inexact but the
1095 * rounding mode is {@code UNNECESSARY}.
1096 * @since 1.5
1097 */
1098 public BigDecimal(int val, MathContext mc) {
1099 int mcp = mc.precision;
1100 long compactVal = val;
1101 int scl = 0;
1102 int prec = 0;
1103 if (mcp > 0) { // do rounding
1104 prec = longDigitLength(compactVal);
1105 int drop = prec - mcp; // drop can't be more than 18
1106 while (drop > 0) {
1107 scl = checkScaleNonZero((long) scl - drop);
1108 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1109 prec = longDigitLength(compactVal);
1110 drop = prec - mcp;
1111 }
1112 }
1113 this.intVal = null;
1114 this.intCompact = compactVal;
1115 this.scale = scl;
1116 this.precision = prec;
1117 }
1118
1119 /**
1120 * Translates a {@code long} into a {@code BigDecimal}. The
1121 * scale of the {@code BigDecimal} is zero.
1122 *
1123 * @param val {@code long} value to be converted to {@code BigDecimal}.
1124 * @since 1.5
1125 */
1126 public BigDecimal(long val) {
1127 this.intCompact = val;
1128 this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null;
1129 this.scale = 0;
1130 }
1131
1132 /**
1133 * Translates a {@code long} into a {@code BigDecimal}, with
1134 * rounding according to the context settings. The scale of the
1135 * {@code BigDecimal}, before any rounding, is zero.
1136 *
1137 * @param val {@code long} value to be converted to {@code BigDecimal}.
1138 * @param mc the context to use.
1139 * @throws ArithmeticException if the result is inexact but the
1140 * rounding mode is {@code UNNECESSARY}.
1141 * @since 1.5
1142 */
1143 public BigDecimal(long val, MathContext mc) {
1144 int mcp = mc.precision;
1145 int mode = mc.roundingMode.oldMode;
1146 int prec = 0;
1147 int scl = 0;
1148 BigInteger rb = (val == INFLATED) ? INFLATED_BIGINT : null;
1149 if (mcp > 0) { // do rounding
1150 if (val == INFLATED) {
1151 prec = 19;
1152 int drop = prec - mcp;
1153 while (drop > 0) {
1154 scl = checkScaleNonZero((long) scl - drop);
1155 rb = divideAndRoundByTenPow(rb, drop, mode);
1156 val = compactValFor(rb);
1157 if (val != INFLATED) {
1158 break;
1159 }
1160 prec = bigDigitLength(rb);
1161 drop = prec - mcp;
1162 }
1163 }
1164 if (val != INFLATED) {
1165 prec = longDigitLength(val);
1166 int drop = prec - mcp;
1167 while (drop > 0) {
1168 scl = checkScaleNonZero((long) scl - drop);
1169 val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode);
1170 prec = longDigitLength(val);
1171 drop = prec - mcp;
1172 }
1173 rb = null;
1174 }
1175 }
1176 this.intVal = rb;
1177 this.intCompact = val;
1178 this.scale = scl;
1179 this.precision = prec;
1180 }
1181
1182 // Static Factory Methods
1183
1184 /**
1185 * Translates a {@code long} unscaled value and an
1186 * {@code int} scale into a {@code BigDecimal}. This
1187 * {@literal "static factory method"} is provided in preference to
1188 * a ({@code long}, {@code int}) constructor because it
1189 * allows for reuse of frequently used {@code BigDecimal} values..
1190 *
1191 * @param unscaledVal unscaled value of the {@code BigDecimal}.
1192 * @param scale scale of the {@code BigDecimal}.
1193 * @return a {@code BigDecimal} whose value is
1194 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>.
1195 */
1196 public static BigDecimal valueOf(long unscaledVal, int scale) {
1197 if (scale == 0)
1198 return valueOf(unscaledVal);
1199 else if (unscaledVal == 0) {
1200 return zeroValueOf(scale);
1201 }
1202 return new BigDecimal(unscaledVal == INFLATED ?
1203 INFLATED_BIGINT : null,
1204 unscaledVal, scale, 0);
1205 }
1206
1207 /**
1208 * Translates a {@code long} value into a {@code BigDecimal}
1209 * with a scale of zero. This {@literal "static factory method"}
1210 * is provided in preference to a ({@code long}) constructor
1211 * because it allows for reuse of frequently used
1212 * {@code BigDecimal} values.
1213 *
1214 * @param val value of the {@code BigDecimal}.
1215 * @return a {@code BigDecimal} whose value is {@code val}.
1216 */
1217 public static BigDecimal valueOf(long val) {
1218 if (val >= 0 && val < ZERO_THROUGH_TEN.length)
1219 return ZERO_THROUGH_TEN[(int)val];
1220 else if (val != INFLATED)
1221 return new BigDecimal(null, val, 0, 0);
1222 return new BigDecimal(INFLATED_BIGINT, val, 0, 0);
1223 }
1224
1225 static BigDecimal valueOf(long unscaledVal, int scale, int prec) {
1226 if (scale == 0 && unscaledVal >= 0 && unscaledVal < ZERO_THROUGH_TEN.length) {
1227 return ZERO_THROUGH_TEN[(int) unscaledVal];
1228 } else if (unscaledVal == 0) {
1229 return zeroValueOf(scale);
1230 }
1231 return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null,
1232 unscaledVal, scale, prec);
1233 }
1234
1235 static BigDecimal valueOf(BigInteger intVal, int scale, int prec) {
1236 long val = compactValFor(intVal);
1237 if (val == 0) {
1238 return zeroValueOf(scale);
1239 } else if (scale == 0 && val >= 0 && val < ZERO_THROUGH_TEN.length) {
1240 return ZERO_THROUGH_TEN[(int) val];
1241 }
1242 return new BigDecimal(intVal, val, scale, prec);
1243 }
1244
1245 static BigDecimal zeroValueOf(int scale) {
1246 if (scale >= 0 && scale < ZERO_SCALED_BY.length)
1247 return ZERO_SCALED_BY[scale];
1248 else
1249 return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
1250 }
1251
1252 /**
1253 * Translates a {@code double} into a {@code BigDecimal}, using
1254 * the {@code double}'s canonical string representation provided
1255 * by the {@link Double#toString(double)} method.
1256 *
1257 * <p><b>Note:</b> This is generally the preferred way to convert
1258 * a {@code double} (or {@code float}) into a
1259 * {@code BigDecimal}, as the value returned is equal to that
1260 * resulting from constructing a {@code BigDecimal} from the
2603
2604 // Comparison Operations
2605
2606 /**
2607 * Compares this {@code BigDecimal} with the specified
2608 * {@code BigDecimal}. Two {@code BigDecimal} objects that are
2609 * equal in value but have a different scale (like 2.0 and 2.00)
2610 * are considered equal by this method. This method is provided
2611 * in preference to individual methods for each of the six boolean
2612 * comparison operators ({@literal <}, ==,
2613 * {@literal >}, {@literal >=}, !=, {@literal <=}). The
2614 * suggested idiom for performing these comparisons is:
2615 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
2616 * <<i>op</i>> is one of the six comparison operators.
2617 *
2618 * @param val {@code BigDecimal} to which this {@code BigDecimal} is
2619 * to be compared.
2620 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically
2621 * less than, equal to, or greater than {@code val}.
2622 */
2623 @Override
2624 public int compareTo(BigDecimal val) {
2625 // Quick path for equal scale and non-inflated case.
2626 if (scale == val.scale) {
2627 long xs = intCompact;
2628 long ys = val.intCompact;
2629 if (xs != INFLATED && ys != INFLATED)
2630 return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
2631 }
2632 int xsign = this.signum();
2633 int ysign = val.signum();
2634 if (xsign != ysign)
2635 return (xsign > ysign) ? 1 : -1;
2636 if (xsign == 0)
2637 return 0;
2638 int cmp = compareMagnitude(val);
2639 return (xsign > 0) ? cmp : -cmp;
2640 }
2641
2642 /**
2643 * Version of compareTo that ignores sign.
2644 */
2645 private int compareMagnitude(BigDecimal val) {
2646 // Match scales, avoid unnecessary inflation
2647 long ys = val.intCompact;
2648 long xs = this.intCompact;
2649 if (xs == 0)
2650 return (ys == 0) ? 0 : -1;
2651 if (ys == 0)
2652 return 1;
2653
2654 long sdiff = (long)this.scale - val.scale;
2655 if (sdiff != 0) {
2656 // Avoid matching scales if the (adjusted) exponents differ
2657 long xae = (long)this.precision() - this.scale; // [-1]
2658 long yae = (long)val.precision() - val.scale; // [-1]
2659 if (xae < yae)
2660 return -1;
2661 if (xae > yae)
2662 return 1;
2663 if (sdiff < 0) {
2664 // The cases sdiff <= Integer.MIN_VALUE intentionally fall through.
2665 if ( sdiff > Integer.MIN_VALUE &&
2666 (xs == INFLATED ||
2667 (xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&
2668 ys == INFLATED) {
2669 BigInteger rb = bigMultiplyPowerTen((int)-sdiff);
2670 return rb.compareMagnitude(val.intVal);
2671 }
2672 } else { // sdiff > 0
2673 // The cases sdiff > Integer.MAX_VALUE intentionally fall through.
2674 if ( sdiff <= Integer.MAX_VALUE &&
2675 (ys == INFLATED ||
2676 (ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&
2677 xs == INFLATED) {
2678 BigInteger rb = val.bigMultiplyPowerTen((int)sdiff);
2679 return this.intVal.compareMagnitude(rb);
2680 }
2681 }
2682 }
2683 if (xs != INFLATED)
2684 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
2685 else if (ys != INFLATED)
2686 return 1;
2687 else
2688 return this.intVal.compareMagnitude(val.intVal);
2689 }
2690
2691 /**
2692 * Compares this {@code BigDecimal} with the specified
2693 * {@code Object} for equality. Unlike {@link
2694 * #compareTo(BigDecimal) compareTo}, this method considers two
2695 * {@code BigDecimal} objects equal only if they are equal in
2696 * value and scale (thus 2.0 is not equal to 2.00 when compared by
2697 * this method).
2698 *
2863 * java.text.NumberFormat} class and its subclasses.
2864 *
2865 * <li>The {@link #toEngineeringString} method may be used for
2866 * presenting numbers with exponents in engineering notation, and the
2867 * {@link #setScale(int,RoundingMode) setScale} method may be used for
2868 * rounding a {@code BigDecimal} so it has a known number of digits after
2869 * the decimal point.
2870 *
2871 * <li>The digit-to-character mapping provided by
2872 * {@code Character.forDigit} is used.
2873 *
2874 * </ol>
2875 *
2876 * @return string representation of this {@code BigDecimal}.
2877 * @see Character#forDigit
2878 * @see #BigDecimal(java.lang.String)
2879 */
2880 @Override
2881 public String toString() {
2882 String sc = stringCache;
2883 if (sc == null) {
2884 stringCache = sc = layoutChars(true);
2885 }
2886 return sc;
2887 }
2888
2889 /**
2890 * Returns a string representation of this {@code BigDecimal},
2891 * using engineering notation if an exponent is needed.
2892 *
2893 * <p>Returns a string that represents the {@code BigDecimal} as
2894 * described in the {@link #toString()} method, except that if
2895 * exponential notation is used, the power of ten is adjusted to
2896 * be a multiple of three (engineering notation) such that the
2897 * integer part of nonzero values will be in the range 1 through
2898 * 999. If exponential notation is used for zero values, a
2899 * decimal point and one or two fractional zero digits are used so
2900 * that the scale of the zero value is preserved. Note that
2901 * unlike the output of {@link #toString()}, the output of this
2902 * method is <em>not</em> guaranteed to recover the same [integer,
2903 * scale] pair of this {@code BigDecimal} if the output string is
2904 * converting back to a {@code BigDecimal} using the {@linkplain
2905 * #BigDecimal(String) string constructor}. The result of this method meets
2942 * method in 1.4 and earlier releases.)
2943 *
2944 * @return a string representation of this {@code BigDecimal}
2945 * without an exponent field.
2946 * @since 1.5
2947 * @see #toString()
2948 * @see #toEngineeringString()
2949 */
2950 public String toPlainString() {
2951 if(scale==0) {
2952 if(intCompact!=INFLATED) {
2953 return Long.toString(intCompact);
2954 } else {
2955 return intVal.toString();
2956 }
2957 }
2958 if(this.scale<0) { // No decimal point
2959 if(signum()==0) {
2960 return "0";
2961 }
2962 int trailingZeros = checkScaleNonZero((-(long)scale));
2963 StringBuilder buf;
2964 if(intCompact!=INFLATED) {
2965 buf = new StringBuilder(20+trailingZeros);
2966 buf.append(intCompact);
2967 } else {
2968 String str = intVal.toString();
2969 buf = new StringBuilder(str.length()+trailingZeros);
2970 buf.append(str);
2971 }
2972 for (int i = 0; i < trailingZeros; i++) {
2973 buf.append('0');
2974 }
2975 return buf.toString();
2976 }
2977 String str ;
2978 if(intCompact!=INFLATED) {
2979 str = Long.toString(Math.abs(intCompact));
2980 } else {
2981 str = intVal.abs().toString();
2982 }
2983 return getValueString(signum(), str, scale);
2984 }
2985
2986 /* Returns a digit.digit string */
2987 private String getValueString(int signum, String intString, int scale) {
2988 /* Insert decimal point */
2989 StringBuilder buf;
2990 int insertionPoint = intString.length() - scale;
2991 if (insertionPoint == 0) { /* Point goes right before intVal */
2992 return (signum<0 ? "-0." : "0.") + intString;
2993 } else if (insertionPoint > 0) { /* Point goes inside intVal */
2994 buf = new StringBuilder(intString);
2995 buf.insert(insertionPoint, '.');
2996 if (signum < 0)
2997 buf.insert(0, '-');
2998 } else { /* We must insert zeros between point and intVal */
2999 buf = new StringBuilder(3-insertionPoint + intString.length());
3000 buf.append(signum<0 ? "-0." : "0.");
3001 for (int i=0; i<-insertionPoint; i++) {
3002 buf.append('0');
3003 }
3004 buf.append(intString);
3005 }
3006 return buf.toString();
3007 }
3008
3009 /**
3010 * Converts this {@code BigDecimal} to a {@code BigInteger}.
3011 * This conversion is analogous to the
3012 * <i>narrowing primitive conversion</i> from {@code double} to
3013 * {@code long} as defined in section 5.1.3 of
3014 * <cite>The Java™ Language Specification</cite>:
3015 * any fractional part of this
3016 * {@code BigDecimal} will be discarded. Note that this
3017 * conversion can lose information about the precision of the
3018 * {@code BigDecimal} value.
3019 * <p>
3020 * To have an exception thrown if the conversion is inexact (in
3021 * other words if a nonzero fractional part is discarded), use the
3022 * {@link #toBigIntegerExact()} method.
3023 *
3042 // round to an integer, with Exception if decimal part non-0
3043 return this.setScale(0, ROUND_UNNECESSARY).inflated();
3044 }
3045
3046 /**
3047 * Converts this {@code BigDecimal} to a {@code long}.
3048 * This conversion is analogous to the
3049 * <i>narrowing primitive conversion</i> from {@code double} to
3050 * {@code short} as defined in section 5.1.3 of
3051 * <cite>The Java™ Language Specification</cite>:
3052 * any fractional part of this
3053 * {@code BigDecimal} will be discarded, and if the resulting
3054 * "{@code BigInteger}" is too big to fit in a
3055 * {@code long}, only the low-order 64 bits are returned.
3056 * Note that this conversion can lose information about the
3057 * overall magnitude and precision of this {@code BigDecimal} value as well
3058 * as return a result with the opposite sign.
3059 *
3060 * @return this {@code BigDecimal} converted to a {@code long}.
3061 */
3062 @Override
3063 public long longValue(){
3064 return (intCompact != INFLATED && scale == 0) ?
3065 intCompact:
3066 toBigInteger().longValue();
3067 }
3068
3069 /**
3070 * Converts this {@code BigDecimal} to a {@code long}, checking
3071 * for lost information. If this {@code BigDecimal} has a
3072 * nonzero fractional part or is out of the possible range for a
3073 * {@code long} result then an {@code ArithmeticException} is
3074 * thrown.
3075 *
3076 * @return this {@code BigDecimal} converted to a {@code long}.
3077 * @throws ArithmeticException if {@code this} has a nonzero
3078 * fractional part, or will not fit in a {@code long}.
3079 * @since 1.5
3080 */
3081 public long longValueExact() {
3082 if (intCompact != INFLATED && scale == 0)
3111 throw new java.lang.ArithmeticException("Overflow");
3112 }
3113 }
3114
3115 /**
3116 * Converts this {@code BigDecimal} to an {@code int}.
3117 * This conversion is analogous to the
3118 * <i>narrowing primitive conversion</i> from {@code double} to
3119 * {@code short} as defined in section 5.1.3 of
3120 * <cite>The Java™ Language Specification</cite>:
3121 * any fractional part of this
3122 * {@code BigDecimal} will be discarded, and if the resulting
3123 * "{@code BigInteger}" is too big to fit in an
3124 * {@code int}, only the low-order 32 bits are returned.
3125 * Note that this conversion can lose information about the
3126 * overall magnitude and precision of this {@code BigDecimal}
3127 * value as well as return a result with the opposite sign.
3128 *
3129 * @return this {@code BigDecimal} converted to an {@code int}.
3130 */
3131 @Override
3132 public int intValue() {
3133 return (intCompact != INFLATED && scale == 0) ?
3134 (int)intCompact :
3135 toBigInteger().intValue();
3136 }
3137
3138 /**
3139 * Converts this {@code BigDecimal} to an {@code int}, checking
3140 * for lost information. If this {@code BigDecimal} has a
3141 * nonzero fractional part or is out of the possible range for an
3142 * {@code int} result then an {@code ArithmeticException} is
3143 * thrown.
3144 *
3145 * @return this {@code BigDecimal} converted to an {@code int}.
3146 * @throws ArithmeticException if {@code this} has a nonzero
3147 * fractional part, or will not fit in an {@code int}.
3148 * @since 1.5
3149 */
3150 public int intValueExact() {
3151 long num;
3194 throw new java.lang.ArithmeticException("Overflow");
3195 return (byte)num;
3196 }
3197
3198 /**
3199 * Converts this {@code BigDecimal} to a {@code float}.
3200 * This conversion is similar to the
3201 * <i>narrowing primitive conversion</i> from {@code double} to
3202 * {@code float} as defined in section 5.1.3 of
3203 * <cite>The Java™ Language Specification</cite>:
3204 * if this {@code BigDecimal} has too great a
3205 * magnitude to represent as a {@code float}, it will be
3206 * converted to {@link Float#NEGATIVE_INFINITY} or {@link
3207 * Float#POSITIVE_INFINITY} as appropriate. Note that even when
3208 * the return value is finite, this conversion can lose
3209 * information about the precision of the {@code BigDecimal}
3210 * value.
3211 *
3212 * @return this {@code BigDecimal} converted to a {@code float}.
3213 */
3214 @Override
3215 public float floatValue(){
3216 if(intCompact != INFLATED) {
3217 if (scale == 0) {
3218 return (float)intCompact;
3219 } else {
3220 /*
3221 * If both intCompact and the scale can be exactly
3222 * represented as float values, perform a single float
3223 * multiply or divide to compute the (properly
3224 * rounded) result.
3225 */
3226 if (Math.abs(intCompact) < 1L<<22 ) {
3227 // Don't have too guard against
3228 // Math.abs(MIN_VALUE) because of outer check
3229 // against INFLATED.
3230 if (scale > 0 && scale < FLOAT_10_POW.length) {
3231 return (float)intCompact / FLOAT_10_POW[scale];
3232 } else if (scale < 0 && scale > -FLOAT_10_POW.length) {
3233 return (float)intCompact * FLOAT_10_POW[-scale];
3234 }
3235 }
3236 }
3237 }
3238 // Somewhat inefficient, but guaranteed to work.
3239 return Float.parseFloat(this.toString());
3240 }
3241
3242 /**
3243 * Converts this {@code BigDecimal} to a {@code double}.
3244 * This conversion is similar to the
3245 * <i>narrowing primitive conversion</i> from {@code double} to
3246 * {@code float} as defined in section 5.1.3 of
3247 * <cite>The Java™ Language Specification</cite>:
3248 * if this {@code BigDecimal} has too great a
3249 * magnitude represent as a {@code double}, it will be
3250 * converted to {@link Double#NEGATIVE_INFINITY} or {@link
3251 * Double#POSITIVE_INFINITY} as appropriate. Note that even when
3252 * the return value is finite, this conversion can lose
3253 * information about the precision of the {@code BigDecimal}
3254 * value.
3255 *
3256 * @return this {@code BigDecimal} converted to a {@code double}.
3257 */
3258 @Override
3259 public double doubleValue(){
3260 if(intCompact != INFLATED) {
3261 if (scale == 0) {
3262 return (double)intCompact;
3263 } else {
3264 /*
3265 * If both intCompact and the scale can be exactly
3266 * represented as double values, perform a single
3267 * double multiply or divide to compute the (properly
3268 * rounded) result.
3269 */
3270 if (Math.abs(intCompact) < 1L<<52 ) {
3271 // Don't have too guard against
3272 // Math.abs(MIN_VALUE) because of outer check
3273 // against INFLATED.
3274 if (scale > 0 && scale < DOUBLE_10_POW.length) {
3275 return (double)intCompact / DOUBLE_10_POW[scale];
3276 } else if (scale < 0 && scale > -DOUBLE_10_POW.length) {
3277 return (double)intCompact * DOUBLE_10_POW[-scale];
3278 }
3279 }
3280 }
3281 }
3282 // Somewhat inefficient, but guaranteed to work.
3283 return Double.parseDouble(this.toString());
3284 }
3285
3286 /**
3287 * Powers of 10 which can be represented exactly in {@code
3288 * double}.
3289 */
3290 private static final double DOUBLE_10_POW[] = {
3291 1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
3292 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11,
3293 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17,
3294 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22
3295 };
3296
3297 /**
3298 * Powers of 10 which can be represented exactly in {@code
3299 * float}.
3300 */
3301 private static final float FLOAT_10_POW[] = {
3302 1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
3303 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
3304 };
3305
3306 /**
3307 * Returns the size of an ulp, a unit in the last place, of this
3308 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
3309 * value is the positive distance between this value and the
3310 * {@code BigDecimal} value next larger in magnitude with the
3311 * same number of digits. An ulp of a zero value is numerically
3312 * equal to 1 with the scale of {@code this}. The result is
3313 * stored with the same scale as {@code this} so the result
3314 * for zero and nonzero values is equal to {@code [1,
3315 * this.scale()]}.
3316 *
3317 * @return the size of an ulp of {@code this}
3318 * @since 1.5
3319 */
3320 public BigDecimal ulp() {
3321 return BigDecimal.valueOf(1, this.scale(), 1);
3494 sig++;
3495 if (signum() == 0) {
3496 switch (sig) {
3497 case 1:
3498 buf.append('0'); // exponent is a multiple of three
3499 break;
3500 case 2:
3501 buf.append("0.00");
3502 adjusted += 3;
3503 break;
3504 case 3:
3505 buf.append("0.0");
3506 adjusted += 3;
3507 break;
3508 default:
3509 throw new AssertionError("Unexpected sig value " + sig);
3510 }
3511 } else if (sig >= coeffLen) { // significand all in integer
3512 buf.append(coeff, offset, coeffLen);
3513 // may need some zeros, too
3514 for (int i = sig - coeffLen; i > 0; i--) {
3515 buf.append('0');
3516 }
3517 } else { // xx.xxE form
3518 buf.append(coeff, offset, sig);
3519 buf.append('.');
3520 buf.append(coeff, offset + sig, coeffLen - sig);
3521 }
3522 }
3523 if (adjusted != 0) { // [!sci could have made 0]
3524 buf.append('E');
3525 if (adjusted > 0) // force sign for positive
3526 buf.append('+');
3527 buf.append(adjusted);
3528 }
3529 }
3530 return buf.toString();
3531 }
3532
3533 /**
3534 * Return 10 to the power n, as a {@code BigInteger}.
3535 *
3536 * @param n the power of ten to be returned (>=0)
3550
3551 return BigInteger.TEN.pow(n);
3552 }
3553
3554 /**
3555 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n.
3556 *
3557 * @param n the power of ten to be returned (>=0)
3558 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and
3559 * in the meantime, the BIG_TEN_POWERS_TABLE array gets
3560 * expanded to the size greater than n.
3561 */
3562 private static BigInteger expandBigIntegerTenPowers(int n) {
3563 synchronized(BigDecimal.class) {
3564 BigInteger[] pows = BIG_TEN_POWERS_TABLE;
3565 int curLen = pows.length;
3566 // The following comparison and the above synchronized statement is
3567 // to prevent multiple threads from expanding the same array.
3568 if (curLen <= n) {
3569 int newLen = curLen << 1;
3570 while (newLen <= n) {
3571 newLen <<= 1;
3572 }
3573 pows = Arrays.copyOf(pows, newLen);
3574 for (int i = curLen; i < newLen; i++) {
3575 pows[i] = pows[i - 1].multiply(BigInteger.TEN);
3576 }
3577 // Based on the following facts:
3578 // 1. pows is a private local varible;
3579 // 2. the following store is a volatile store.
3580 // the newly created array elements can be safely published.
3581 BIG_TEN_POWERS_TABLE = pows;
3582 }
3583 return pows[n];
3584 }
3585 }
3586
3587 private static final long[] LONG_TEN_POWERS_TABLE = {
3588 1, // 0 / 10^0
3589 10, // 1 / 10^1
3590 100, // 2 / 10^2
3591 1000, // 3 / 10^3
3592 10000, // 4 / 10^4
3593 100000, // 5 / 10^5
3594 1000000, // 6 / 10^6
3595 10000000, // 7 / 10^7
3596 100000000, // 8 / 10^8
3696 if (intVal == null) {
3697 return BigInteger.valueOf(intCompact);
3698 }
3699 return intVal;
3700 }
3701
3702 /**
3703 * Match the scales of two {@code BigDecimal}s to align their
3704 * least significant digits.
3705 *
3706 * <p>If the scales of val[0] and val[1] differ, rescale
3707 * (non-destructively) the lower-scaled {@code BigDecimal} so
3708 * they match. That is, the lower-scaled reference will be
3709 * replaced by a reference to a new object with the same scale as
3710 * the other {@code BigDecimal}.
3711 *
3712 * @param val array of two elements referring to the two
3713 * {@code BigDecimal}s to be aligned.
3714 */
3715 private static void matchScale(BigDecimal[] val) {
3716 if (val[0].scale < val[1].scale) {
3717 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY);
3718 } else if (val[1].scale < val[0].scale) {
3719 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY);
3720 }
3721 }
3722
3723 private static class UnsafeHolder {
3724 private static final sun.misc.Unsafe unsafe;
3725 private static final long intCompactOffset;
3726 private static final long intValOffset;
3727 static {
3728 try {
3729 unsafe = sun.misc.Unsafe.getUnsafe();
3730 intCompactOffset = unsafe.objectFieldOffset
3731 (BigDecimal.class.getDeclaredField("intCompact"));
3732 intValOffset = unsafe.objectFieldOffset
3733 (BigDecimal.class.getDeclaredField("intVal"));
3734 } catch (Exception ex) {
3735 throw new ExceptionInInitializerError(ex);
3736 }
4200 */
4201 private static boolean needIncrement(long ldivisor, int roundingMode,
4202 int qsign, long q, long r) {
4203 assert r != 0L;
4204
4205 int cmpFracHalf;
4206 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) {
4207 cmpFracHalf = 1; // 2 * r can't fit into long
4208 } else {
4209 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor);
4210 }
4211
4212 return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L);
4213 }
4214
4215 /**
4216 * Divides {@code BigInteger} value by {@code long} value and
4217 * do rounding based on the passed in roundingMode.
4218 */
4219 private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) {
4220 // Descend into mutables for faster remainder checks
4221 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4222 // store quotient
4223 MutableBigInteger mq = new MutableBigInteger();
4224 // store quotient & remainder in long
4225 long r = mdividend.divide(ldivisor, mq);
4226 // record remainder is zero or not
4227 boolean isRemainderZero = (r == 0);
4228 // quotient sign
4229 int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4230 if (!isRemainderZero) {
4231 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4232 mq.add(MutableBigInteger.ONE);
4233 }
4234 }
4235 return mq.toBigInteger(qsign);
4236 }
4237
4238 /**
4239 * Internally used for division operation for division {@code BigInteger}
4240 * by {@code long}.
4241 * The returned {@code BigDecimal} object is the quotient whose scale is set
4242 * to the passed in scale. If the remainder is not zero, it will be rounded
4243 * based on the passed in roundingMode. Also, if the remainder is zero and
4244 * the last parameter, i.e. preferredScale is NOT equal to scale, the
4245 * trailing zeros of the result is stripped to match the preferredScale.
4246 */
4247 private static BigDecimal divideAndRound(BigInteger bdividend,
4248 long ldivisor, int scale, int roundingMode, int preferredScale) {
4249 // Descend into mutables for faster remainder checks
4250 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag);
4251 // store quotient
4252 MutableBigInteger mq = new MutableBigInteger();
4253 // store quotient & remainder in long
4254 long r = mdividend.divide(ldivisor, mq);
4255 // record remainder is zero or not
4256 boolean isRemainderZero = (r == 0);
4257 // quotient sign
4258 int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum;
4259 if (!isRemainderZero) {
4260 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) {
4261 mq.add(MutableBigInteger.ONE);
4262 }
4263 return mq.toBigDecimal(qsign, scale);
4264 } else {
4265 if (preferredScale != scale) {
4266 long compactVal = mq.toCompactValue(qsign);
4267 if(compactVal!=INFLATED) {
4268 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale);
4269 }
4270 BigInteger intVal = mq.toBigInteger(qsign);
4271 return createAndStripZerosToMatchScale(intVal,scale, preferredScale);
4272 } else {
4273 return mq.toBigDecimal(qsign, scale);
4274 }
4275 }
4276 }
4277
4278 /**
|