1 /* 2 * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 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 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 117 * the leading digit position of the returned result. 118 * 119 * <p>Besides a logical exact result, each arithmetic operation has a 120 * preferred scale for representing a result. The preferred 121 * scale for each operation is listed in the table below. 122 * 123 * <table border> 124 * <caption top><b>Preferred Scales for Results of Arithmetic Operations 125 * </b></caption> 126 * <tr><th>Operation</th><th>Preferred Scale of Result</th></tr> 127 * <tr><td>Add</td><td>max(addend.scale(), augend.scale())</td> 128 * <tr><td>Subtract</td><td>max(minuend.scale(), subtrahend.scale())</td> 129 * <tr><td>Multiply</td><td>multiplier.scale() + multiplicand.scale()</td> 130 * <tr><td>Divide</td><td>dividend.scale() - divisor.scale()</td> 131 * </table> 132 * 133 * These scales are the ones used by the methods which return exact 134 * arithmetic results; except that an exact divide may have to use a 135 * larger scale since the exact result may have more digits. For 136 * example, {@code 1/32} is {@code 0.03125}. 137 * 138 * <p>Before rounding, the scale of the logical exact intermediate 139 * result is the preferred scale for that operation. If the exact 140 * numerical result cannot be represented in {@code precision} 141 * digits, rounding selects the set of digits to return and the scale 142 * of the result is reduced from the scale of the intermediate result 143 * to the least scale which can represent the {@code precision} 144 * digits actually returned. If the exact result can be represented 145 * with at most {@code precision} digits, the representation 146 * of the result with the scale closest to the preferred scale is 147 * returned. In particular, an exactly representable quotient may be 148 * represented in fewer than {@code precision} digits by removing 149 * trailing zeros and decreasing the scale. For example, rounding to 150 * three digits using the {@linkplain RoundingMode#FLOOR floor} 151 * rounding mode, <br> 152 * 153 * {@code 19/100 = 0.19 // integer=19, scale=2} <br> 154 * 155 * but<br> 156 * 157 * {@code 21/110 = 0.190 // integer=190, scale=3} <br> 158 * 159 * <p>Note that for add, subtract, and multiply, the reduction in 160 * scale will equal the number of digit positions of the exact result 161 * which are discarded. If the rounding causes a carry propagation to 162 * create a new high-order digit position, an additional digit of the 163 * result is discarded than when no new digit position is created. 164 * 165 * <p>Other methods may have slightly different rounding semantics. 166 * For example, the result of the {@code pow} method using the 167 * {@linkplain #pow(int, MathContext) specified algorithm} can 168 * occasionally differ from the rounded mathematical result by more 169 * than one unit in the last place, one <i>{@linkplain #ulp() ulp}</i>. 170 * 171 * <p>Two types of operations are provided for manipulating the scale 172 * of a {@code BigDecimal}: scaling/rounding operations and decimal 173 * point motion operations. Scaling/rounding operations ({@link 174 * #setScale setScale} and {@link #round round}) return a 175 * {@code BigDecimal} whose value is approximately (or exactly) equal 176 * to that of the operand, but whose scale or precision is the 177 * specified value; that is, they increase or decrease the precision 178 * of the stored number with minimal effect on its value. Decimal 179 * point motion operations ({@link #movePointLeft movePointLeft} and 180 * {@link #movePointRight movePointRight}) return a 181 * {@code BigDecimal} created from the operand by moving the decimal 182 * point a specified distance in the specified direction. 183 * 184 * <p>For the sake of brevity and clarity, pseudo-code is used 185 * throughout the descriptions of {@code BigDecimal} methods. The 186 * pseudo-code expression {@code (i + j)} is shorthand for "a 187 * {@code BigDecimal} whose value is that of the {@code BigDecimal} 188 * {@code i} added to that of the {@code BigDecimal} 189 * {@code j}." The pseudo-code expression {@code (i == j)} is 190 * shorthand for "{@code true} if and only if the 191 * {@code BigDecimal} {@code i} represents the same value as the 192 * {@code BigDecimal} {@code j}." Other pseudo-code expressions 193 * are interpreted similarly. Square brackets are used to represent 194 * the particular {@code BigInteger} and scale pair defining a 195 * {@code BigDecimal} value; for example [19, 2] is the 196 * {@code BigDecimal} numerically equal to 0.19 having a scale of 2. 197 * 198 * <p>Note: care should be exercised if {@code BigDecimal} objects 199 * are used as keys in a {@link java.util.SortedMap SortedMap} or 200 * elements in a {@link java.util.SortedSet SortedSet} since 201 * {@code BigDecimal}'s <i>natural ordering</i> is <i>inconsistent 202 * with equals</i>. See {@link Comparable}, {@link 203 * java.util.SortedMap} or {@link java.util.SortedSet} for more 204 * information. 205 * 206 * <p>All methods and constructors for this class throw 207 * {@code NullPointerException} when passed a {@code null} object 208 * reference for any input parameter. 209 * 210 * @see BigInteger 211 * @see MathContext 212 * @see RoundingMode 213 * @see java.util.SortedMap 214 * @see java.util.SortedSet 215 * @author Josh Bloch 216 * @author Mike Cowlishaw 217 * @author Joseph D. Darcy 218 */ 219 public class BigDecimal extends Number implements Comparable<BigDecimal> { 220 /** 221 * The unscaled value of this BigDecimal, as returned by {@link 222 * #unscaledValue}. 223 * 224 * @serial 225 * @see #unscaledValue 226 */ 227 private volatile BigInteger intVal; 228 229 /** 230 * The scale of this BigDecimal, as returned by {@link #scale}. 231 * 232 * @serial 233 * @see #scale 234 */ 235 private int scale; // Note: this may have any value, so 236 // calculations must be done in longs 237 /** 238 * The number of decimal digits in this BigDecimal, or 0 if the 239 * number of digits are not known (lookaside information). If 240 * nonzero, the value is guaranteed correct. Use the precision() 241 * method to obtain and set the value if it might be 0. This 242 * field is mutable until set nonzero. 243 * 244 * @since 1.5 245 */ 246 private transient int precision; 247 248 /** 249 * Used to store the canonical string representation, if computed. 250 */ 251 private transient String stringCache; 252 253 /** 254 * Sentinel value for {@link #intCompact} indicating the 255 * significand information is only available from {@code intVal}. 256 */ 257 static final long INFLATED = Long.MIN_VALUE; 258 259 /** 260 * If the absolute value of the significand of this BigDecimal is 261 * less than or equal to {@code Long.MAX_VALUE}, the value can be 262 * compactly stored in this field and used in computations. 263 */ 264 private transient long intCompact; 265 266 // All 18-digit base ten strings fit into a long; not all 19-digit 267 // strings will 268 private static final int MAX_COMPACT_DIGITS = 18; 269 270 private static final int MAX_BIGINT_BITS = 62; 271 272 /* Appease the serialization gods */ 273 private static final long serialVersionUID = 6108874887143696463L; 274 275 private static final ThreadLocal<StringBuilderHelper> 276 threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() { 277 @Override 278 protected StringBuilderHelper initialValue() { 279 return new StringBuilderHelper(); 280 } 281 }; 282 283 // Cache of common small BigDecimal values. 284 private static final BigDecimal zeroThroughTen[] = { 285 new BigDecimal(BigInteger.ZERO, 0, 0, 1), 286 new BigDecimal(BigInteger.ONE, 1, 0, 1), 287 new BigDecimal(BigInteger.valueOf(2), 2, 0, 1), 288 new BigDecimal(BigInteger.valueOf(3), 3, 0, 1), 289 new BigDecimal(BigInteger.valueOf(4), 4, 0, 1), 290 new BigDecimal(BigInteger.valueOf(5), 5, 0, 1), 291 new BigDecimal(BigInteger.valueOf(6), 6, 0, 1), 292 new BigDecimal(BigInteger.valueOf(7), 7, 0, 1), 293 new BigDecimal(BigInteger.valueOf(8), 8, 0, 1), 294 new BigDecimal(BigInteger.valueOf(9), 9, 0, 1), 295 new BigDecimal(BigInteger.TEN, 10, 0, 2), 296 }; 297 298 // Cache of zero scaled by 0 - 15 299 private static final BigDecimal[] ZERO_SCALED_BY = { 300 zeroThroughTen[0], 301 new BigDecimal(BigInteger.ZERO, 0, 1, 1), 302 new BigDecimal(BigInteger.ZERO, 0, 2, 1), 303 new BigDecimal(BigInteger.ZERO, 0, 3, 1), 304 new BigDecimal(BigInteger.ZERO, 0, 4, 1), 305 new BigDecimal(BigInteger.ZERO, 0, 5, 1), 306 new BigDecimal(BigInteger.ZERO, 0, 6, 1), 307 new BigDecimal(BigInteger.ZERO, 0, 7, 1), 308 new BigDecimal(BigInteger.ZERO, 0, 8, 1), 309 new BigDecimal(BigInteger.ZERO, 0, 9, 1), 310 new BigDecimal(BigInteger.ZERO, 0, 10, 1), 311 new BigDecimal(BigInteger.ZERO, 0, 11, 1), 312 new BigDecimal(BigInteger.ZERO, 0, 12, 1), 313 new BigDecimal(BigInteger.ZERO, 0, 13, 1), 314 new BigDecimal(BigInteger.ZERO, 0, 14, 1), 315 new BigDecimal(BigInteger.ZERO, 0, 15, 1), 316 }; 317 318 // Half of Long.MIN_VALUE & Long.MAX_VALUE. 319 private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2; 320 private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2; 321 322 // Constants 323 /** 324 * The value 0, with a scale of 0. 325 * 326 * @since 1.5 327 */ 328 public static final BigDecimal ZERO = 329 zeroThroughTen[0]; 330 331 /** 332 * The value 1, with a scale of 0. 333 * 334 * @since 1.5 335 */ 336 public static final BigDecimal ONE = 337 zeroThroughTen[1]; 338 339 /** 340 * The value 10, with a scale of 0. 341 * 342 * @since 1.5 343 */ 344 public static final BigDecimal TEN = 345 zeroThroughTen[10]; 346 347 // Constructors 348 349 /** 350 * Trusted package private constructor. 351 * Trusted simply means if val is INFLATED, intVal could not be null and 352 * if intVal is null, val could not be INFLATED. 353 */ 354 BigDecimal(BigInteger intVal, long val, int scale, int prec) { 355 this.scale = scale; 356 this.precision = prec; 357 this.intCompact = val; 358 this.intVal = intVal; 359 } 360 361 /** 362 * Translates a character array representation of a 363 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 364 * same sequence of characters as the {@link #BigDecimal(String)} 365 * constructor, while allowing a sub-array to be specified. 366 * 367 * <p>Note that if the sequence of characters is already available 368 * within a character array, using this constructor is faster than 369 * converting the {@code char} array to string and using the 370 * {@code BigDecimal(String)} constructor . 371 * 372 * @param in {@code char} array that is the source of characters. 373 * @param offset first character in the array to inspect. 374 * @param len number of characters to consider. 375 * @throws NumberFormatException if {@code in} is not a valid 376 * representation of a {@code BigDecimal} or the defined subarray 377 * is not wholly within {@code in}. 378 * @since 1.5 379 */ 380 public BigDecimal(char[] in, int offset, int len) { 381 // protect against huge length. 382 if (offset+len > in.length || offset < 0) 383 throw new NumberFormatException(); 384 // This is the primary string to BigDecimal constructor; all 385 // incoming strings end up here; it uses explicit (inline) 386 // parsing for speed and generates at most one intermediate 387 // (temporary) object (a char[] array) for non-compact case. 388 389 // Use locals for all fields values until completion 390 int prec = 0; // record precision value 391 int scl = 0; // record scale value 392 long rs = 0; // the compact value in long 393 BigInteger rb = null; // the inflated value in BigInteger 394 395 // use array bounds checking to handle too-long, len == 0, 396 // bad offset, etc. 397 try { 398 // handle the sign 399 boolean isneg = false; // assume positive 400 if (in[offset] == '-') { 401 isneg = true; // leading minus means negative 402 offset++; 403 len--; 404 } else if (in[offset] == '+') { // leading + allowed 405 offset++; 406 len--; 407 } 408 409 // should now be at numeric part of the significand 410 boolean dot = false; // true when there is a '.' 411 int cfirst = offset; // record start of integer 412 long exp = 0; // exponent 413 char c; // current character 414 415 boolean isCompact = (len <= MAX_COMPACT_DIGITS); 416 // integer significand array & idx is the index to it. The array 417 // is ONLY used when we can't use a compact representation. 418 char coeff[] = isCompact ? null : new char[len]; 419 int idx = 0; 420 421 for (; len > 0; offset++, len--) { 422 c = in[offset]; 423 // have digit 424 if ((c >= '0' && c <= '9') || Character.isDigit(c)) { 425 // First compact case, we need not to preserve the character 426 // and we can just compute the value in place. 427 if (isCompact) { 428 int digit = Character.digit(c, 10); 429 if (digit == 0) { 430 if (prec == 0) 431 prec = 1; 432 else if (rs != 0) { 433 rs *= 10; 434 ++prec; 435 } // else digit is a redundant leading zero 436 } else { 437 if (prec != 1 || rs != 0) 438 ++prec; // prec unchanged if preceded by 0s 439 rs = rs * 10 + digit; 440 } 441 } else { // the unscaled value is likely a BigInteger object. 442 if (c == '0' || Character.digit(c, 10) == 0) { 443 if (prec == 0) { 444 coeff[idx] = c; 445 prec = 1; 446 } else if (idx != 0) { 447 coeff[idx++] = c; 448 ++prec; 449 } // else c must be a redundant leading zero 450 } else { 451 if (prec != 1 || idx != 0) 452 ++prec; // prec unchanged if preceded by 0s 453 coeff[idx++] = c; 454 } 455 } 456 if (dot) 457 ++scl; 458 continue; 459 } 460 // have dot 461 if (c == '.') { 462 // have dot 463 if (dot) // two dots 464 throw new NumberFormatException(); 465 dot = true; 466 continue; 467 } 468 // exponent expected 469 if ((c != 'e') && (c != 'E')) 470 throw new NumberFormatException(); 471 offset++; 472 c = in[offset]; 473 len--; 474 boolean negexp = (c == '-'); 475 // optional sign 476 if (negexp || c == '+') { 477 offset++; 478 c = in[offset]; 479 len--; 480 } 481 if (len <= 0) // no exponent digits 482 throw new NumberFormatException(); 483 // skip leading zeros in the exponent 484 while (len > 10 && Character.digit(c, 10) == 0) { 485 offset++; 486 c = in[offset]; 487 len--; 488 } 489 if (len > 10) // too many nonzero exponent digits 490 throw new NumberFormatException(); 491 // c now holds first digit of exponent 492 for (;; len--) { 493 int v; 494 if (c >= '0' && c <= '9') { 495 v = c - '0'; 496 } else { 497 v = Character.digit(c, 10); 498 if (v < 0) // not a digit 499 throw new NumberFormatException(); 500 } 501 exp = exp * 10 + v; 502 if (len == 1) 503 break; // that was final character 504 offset++; 505 c = in[offset]; 506 } 507 if (negexp) // apply sign 508 exp = -exp; 509 // Next test is required for backwards compatibility 510 if ((int)exp != exp) // overflow 511 throw new NumberFormatException(); 512 break; // [saves a test] 513 } 514 // here when no characters left 515 if (prec == 0) // no digits found 516 throw new NumberFormatException(); 517 518 // Adjust scale if exp is not zero. 519 if (exp != 0) { // had significant exponent 520 // Can't call checkScale which relies on proper fields value 521 long adjustedScale = scl - exp; 522 if (adjustedScale > Integer.MAX_VALUE || 523 adjustedScale < Integer.MIN_VALUE) 524 throw new NumberFormatException("Scale out of range."); 525 scl = (int)adjustedScale; 526 } 527 528 // Remove leading zeros from precision (digits count) 529 if (isCompact) { 530 rs = isneg ? -rs : rs; 531 } else { 532 char quick[]; 533 if (!isneg) { 534 quick = (coeff.length != prec) ? 535 Arrays.copyOf(coeff, prec) : coeff; 536 } else { 537 quick = new char[prec + 1]; 538 quick[0] = '-'; 539 System.arraycopy(coeff, 0, quick, 1, prec); 540 } 541 rb = new BigInteger(quick); 542 rs = compactValFor(rb); 543 } 544 } catch (ArrayIndexOutOfBoundsException e) { 545 throw new NumberFormatException(); 546 } catch (NegativeArraySizeException e) { 547 throw new NumberFormatException(); 548 } 549 this.scale = scl; 550 this.precision = prec; 551 this.intCompact = rs; 552 this.intVal = (rs != INFLATED) ? null : rb; 553 } 554 555 /** 556 * Translates a character array representation of a 557 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 558 * same sequence of characters as the {@link #BigDecimal(String)} 559 * constructor, while allowing a sub-array to be specified and 560 * with rounding according to the context settings. 561 * 562 * <p>Note that if the sequence of characters is already available 563 * within a character array, using this constructor is faster than 564 * converting the {@code char} array to string and using the 565 * {@code BigDecimal(String)} constructor . 566 * 567 * @param in {@code char} array that is the source of characters. 568 * @param offset first character in the array to inspect. 569 * @param len number of characters to consider.. 570 * @param mc the context to use. 571 * @throws ArithmeticException if the result is inexact but the 572 * rounding mode is {@code UNNECESSARY}. 573 * @throws NumberFormatException if {@code in} is not a valid 574 * representation of a {@code BigDecimal} or the defined subarray 575 * is not wholly within {@code in}. 576 * @since 1.5 577 */ 578 public BigDecimal(char[] in, int offset, int len, MathContext mc) { 579 this(in, offset, len); 580 if (mc.precision > 0) 581 roundThis(mc); 582 } 583 584 /** 585 * Translates a character array representation of a 586 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 587 * same sequence of characters as the {@link #BigDecimal(String)} 588 * constructor. 589 * 590 * <p>Note that if the sequence of characters is already available 591 * as a character array, using this constructor is faster than 592 * converting the {@code char} array to string and using the 593 * {@code BigDecimal(String)} constructor . 594 * 595 * @param in {@code char} array that is the source of characters. 596 * @throws NumberFormatException if {@code in} is not a valid 597 * representation of a {@code BigDecimal}. 598 * @since 1.5 599 */ 600 public BigDecimal(char[] in) { 601 this(in, 0, in.length); 602 } 603 604 /** 605 * Translates a character array representation of a 606 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 607 * same sequence of characters as the {@link #BigDecimal(String)} 608 * constructor and with rounding according to the context 609 * settings. 610 * 611 * <p>Note that if the sequence of characters is already available 612 * as a character array, using this constructor is faster than 613 * converting the {@code char} array to string and using the 614 * {@code BigDecimal(String)} constructor . 615 * 616 * @param in {@code char} array that is the source of characters. 617 * @param mc the context to use. 618 * @throws ArithmeticException if the result is inexact but the 619 * rounding mode is {@code UNNECESSARY}. 620 * @throws NumberFormatException if {@code in} is not a valid 621 * representation of a {@code BigDecimal}. 622 * @since 1.5 623 */ 624 public BigDecimal(char[] in, MathContext mc) { 625 this(in, 0, in.length, mc); 626 } 627 628 /** 629 * Translates the string representation of a {@code BigDecimal} 630 * into a {@code BigDecimal}. The string representation consists 631 * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or 632 * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of 633 * zero or more decimal digits ("the integer"), optionally 634 * followed by a fraction, optionally followed by an exponent. 635 * 636 * <p>The fraction consists of a decimal point followed by zero 637 * or more decimal digits. The string must contain at least one 638 * digit in either the integer or the fraction. The number formed 639 * by the sign, the integer and the fraction is referred to as the 640 * <i>significand</i>. 641 * 642 * <p>The exponent consists of the character {@code 'e'} 643 * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>) 644 * followed by one or more decimal digits. The value of the 645 * exponent must lie between -{@link Integer#MAX_VALUE} ({@link 646 * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive. 647 * 648 * <p>More formally, the strings this constructor accepts are 649 * described by the following grammar: 650 * <blockquote> 651 * <dl> 652 * <dt><i>BigDecimalString:</i> 653 * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i> 654 * <p> 655 * <dt><i>Sign:</i> 656 * <dd>{@code +} 657 * <dd>{@code -} 658 * <p> 659 * <dt><i>Significand:</i> 660 * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i> 661 * <dd>{@code .} <i>FractionPart</i> 662 * <dd><i>IntegerPart</i> 663 * <p> 664 * <dt><i>IntegerPart:</i> 665 * <dd><i>Digits</i> 666 * <p> 667 * <dt><i>FractionPart:</i> 668 * <dd><i>Digits</i> 669 * <p> 670 * <dt><i>Exponent:</i> 671 * <dd><i>ExponentIndicator SignedInteger</i> 672 * <p> 673 * <dt><i>ExponentIndicator:</i> 674 * <dd>{@code e} 675 * <dd>{@code E} 676 * <p> 677 * <dt><i>SignedInteger:</i> 678 * <dd><i>Sign<sub>opt</sub> Digits</i> 679 * <p> 680 * <dt><i>Digits:</i> 681 * <dd><i>Digit</i> 682 * <dd><i>Digits Digit</i> 683 * <p> 684 * <dt><i>Digit:</i> 685 * <dd>any character for which {@link Character#isDigit} 686 * returns {@code true}, including 0, 1, 2 ... 687 * </dl> 688 * </blockquote> 689 * 690 * <p>The scale of the returned {@code BigDecimal} will be the 691 * number of digits in the fraction, or zero if the string 692 * contains no decimal point, subject to adjustment for any 693 * exponent; if the string contains an exponent, the exponent is 694 * subtracted from the scale. The value of the resulting scale 695 * must lie between {@code Integer.MIN_VALUE} and 696 * {@code Integer.MAX_VALUE}, inclusive. 697 * 698 * <p>The character-to-digit mapping is provided by {@link 699 * java.lang.Character#digit} set to convert to radix 10. The 700 * String may not contain any extraneous characters (whitespace, 701 * for example). 702 * 703 * <p><b>Examples:</b><br> 704 * The value of the returned {@code BigDecimal} is equal to 705 * <i>significand</i> × 10<sup> <i>exponent</i></sup>. 706 * For each string on the left, the resulting representation 707 * [{@code BigInteger}, {@code scale}] is shown on the right. 708 * <pre> 709 * "0" [0,0] 710 * "0.00" [0,2] 711 * "123" [123,0] 712 * "-123" [-123,0] 713 * "1.23E3" [123,-1] 714 * "1.23E+3" [123,-1] 715 * "12.3E+7" [123,-6] 716 * "12.0" [120,1] 717 * "12.3" [123,1] 718 * "0.00123" [123,5] 719 * "-1.23E-12" [-123,14] 720 * "1234.5E-4" [12345,5] 721 * "0E+7" [0,-7] 722 * "-0" [0,0] 723 * </pre> 724 * 725 * <p>Note: For values other than {@code float} and 726 * {@code double} NaN and ±Infinity, this constructor is 727 * compatible with the values returned by {@link Float#toString} 728 * and {@link Double#toString}. This is generally the preferred 729 * way to convert a {@code float} or {@code double} into a 730 * BigDecimal, as it doesn't suffer from the unpredictability of 731 * the {@link #BigDecimal(double)} constructor. 732 * 733 * @param val String representation of {@code BigDecimal}. 734 * 735 * @throws NumberFormatException if {@code val} is not a valid 736 * representation of a {@code BigDecimal}. 737 */ 738 public BigDecimal(String val) { 739 this(val.toCharArray(), 0, val.length()); 740 } 741 742 /** 743 * Translates the string representation of a {@code BigDecimal} 744 * into a {@code BigDecimal}, accepting the same strings as the 745 * {@link #BigDecimal(String)} constructor, with rounding 746 * according to the context settings. 747 * 748 * @param val string representation of a {@code BigDecimal}. 749 * @param mc the context to use. 750 * @throws ArithmeticException if the result is inexact but the 751 * rounding mode is {@code UNNECESSARY}. 752 * @throws NumberFormatException if {@code val} is not a valid 753 * representation of a BigDecimal. 754 * @since 1.5 755 */ 756 public BigDecimal(String val, MathContext mc) { 757 this(val.toCharArray(), 0, val.length()); 758 if (mc.precision > 0) 759 roundThis(mc); 760 } 761 762 /** 763 * Translates a {@code double} into a {@code BigDecimal} which 764 * is the exact decimal representation of the {@code double}'s 765 * binary floating-point value. The scale of the returned 766 * {@code BigDecimal} is the smallest value such that 767 * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 768 * <p> 769 * <b>Notes:</b> 770 * <ol> 771 * <li> 772 * The results of this constructor can be somewhat unpredictable. 773 * One might assume that writing {@code new BigDecimal(0.1)} in 774 * Java creates a {@code BigDecimal} which is exactly equal to 775 * 0.1 (an unscaled value of 1, with a scale of 1), but it is 776 * actually equal to 777 * 0.1000000000000000055511151231257827021181583404541015625. 778 * This is because 0.1 cannot be represented exactly as a 779 * {@code double} (or, for that matter, as a binary fraction of 780 * any finite length). Thus, the value that is being passed 781 * <i>in</i> to the constructor is not exactly equal to 0.1, 782 * appearances notwithstanding. 783 * 784 * <li> 785 * The {@code String} constructor, on the other hand, is 786 * perfectly predictable: writing {@code new BigDecimal("0.1")} 787 * creates a {@code BigDecimal} which is <i>exactly</i> equal to 788 * 0.1, as one would expect. Therefore, it is generally 789 * recommended that the {@linkplain #BigDecimal(String) 790 * <tt>String</tt> constructor} be used in preference to this one. 791 * 792 * <li> 793 * When a {@code double} must be used as a source for a 794 * {@code BigDecimal}, note that this constructor provides an 795 * exact conversion; it does not give the same result as 796 * converting the {@code double} to a {@code String} using the 797 * {@link Double#toString(double)} method and then using the 798 * {@link #BigDecimal(String)} constructor. To get that result, 799 * use the {@code static} {@link #valueOf(double)} method. 800 * </ol> 801 * 802 * @param val {@code double} value to be converted to 803 * {@code BigDecimal}. 804 * @throws NumberFormatException if {@code val} is infinite or NaN. 805 */ 806 public BigDecimal(double val) { 807 if (Double.isInfinite(val) || Double.isNaN(val)) 808 throw new NumberFormatException("Infinite or NaN"); 809 810 // Translate the double into sign, exponent and significand, according 811 // to the formulae in JLS, Section 20.10.22. 812 long valBits = Double.doubleToLongBits(val); 813 int sign = ((valBits >> 63)==0 ? 1 : -1); 814 int exponent = (int) ((valBits >> 52) & 0x7ffL); 815 long significand = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1 816 : (valBits & ((1L<<52) - 1)) | (1L<<52)); 817 exponent -= 1075; 818 // At this point, val == sign * significand * 2**exponent. 819 820 /* 821 * Special case zero to supress nonterminating normalization 822 * and bogus scale calculation. 823 */ 824 if (significand == 0) { 825 intVal = BigInteger.ZERO; 826 intCompact = 0; 827 precision = 1; 828 return; 829 } 830 831 // Normalize 832 while((significand & 1) == 0) { // i.e., significand is even 833 significand >>= 1; 834 exponent++; 835 } 836 837 // Calculate intVal and scale 838 long s = sign * significand; 839 BigInteger b; 840 if (exponent < 0) { 841 b = BigInteger.valueOf(5).pow(-exponent).multiply(s); 842 scale = -exponent; 843 } else if (exponent > 0) { 844 b = BigInteger.valueOf(2).pow(exponent).multiply(s); 845 } else { 846 b = BigInteger.valueOf(s); 847 } 848 intCompact = compactValFor(b); 849 intVal = (intCompact != INFLATED) ? null : b; 850 } 851 852 /** 853 * Translates a {@code double} into a {@code BigDecimal}, with 854 * rounding according to the context settings. The scale of the 855 * {@code BigDecimal} is the smallest value such that 856 * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 857 * 858 * <p>The results of this constructor can be somewhat unpredictable 859 * and its use is generally not recommended; see the notes under 860 * the {@link #BigDecimal(double)} constructor. 861 * 862 * @param val {@code double} value to be converted to 863 * {@code BigDecimal}. 864 * @param mc the context to use. 865 * @throws ArithmeticException if the result is inexact but the 866 * RoundingMode is UNNECESSARY. 867 * @throws NumberFormatException if {@code val} is infinite or NaN. 868 * @since 1.5 869 */ 870 public BigDecimal(double val, MathContext mc) { 871 this(val); 872 if (mc.precision > 0) 873 roundThis(mc); 874 } 875 876 /** 877 * Translates a {@code BigInteger} into a {@code BigDecimal}. 878 * The scale of the {@code BigDecimal} is zero. 879 * 880 * @param val {@code BigInteger} value to be converted to 881 * {@code BigDecimal}. 882 */ 883 public BigDecimal(BigInteger val) { 884 intCompact = compactValFor(val); 885 intVal = (intCompact != INFLATED) ? null : val; 886 } 887 888 /** 889 * Translates a {@code BigInteger} into a {@code BigDecimal} 890 * rounding according to the context settings. The scale of the 891 * {@code BigDecimal} is zero. 892 * 893 * @param val {@code BigInteger} value to be converted to 894 * {@code BigDecimal}. 895 * @param mc the context to use. 896 * @throws ArithmeticException if the result is inexact but the 897 * rounding mode is {@code UNNECESSARY}. 898 * @since 1.5 899 */ 900 public BigDecimal(BigInteger val, MathContext mc) { 901 this(val); 902 if (mc.precision > 0) 903 roundThis(mc); 904 } 905 906 /** 907 * Translates a {@code BigInteger} unscaled value and an 908 * {@code int} scale into a {@code BigDecimal}. The value of 909 * the {@code BigDecimal} is 910 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 911 * 912 * @param unscaledVal unscaled value of the {@code BigDecimal}. 913 * @param scale scale of the {@code BigDecimal}. 914 */ 915 public BigDecimal(BigInteger unscaledVal, int scale) { 916 // Negative scales are now allowed 917 this(unscaledVal); 918 this.scale = scale; 919 } 920 921 /** 922 * Translates a {@code BigInteger} unscaled value and an 923 * {@code int} scale into a {@code BigDecimal}, with rounding 924 * according to the context settings. The value of the 925 * {@code BigDecimal} is <tt>(unscaledVal × 926 * 10<sup>-scale</sup>)</tt>, rounded according to the 927 * {@code precision} and rounding mode settings. 928 * 929 * @param unscaledVal unscaled value of the {@code BigDecimal}. 930 * @param scale scale of the {@code BigDecimal}. 931 * @param mc the context to use. 932 * @throws ArithmeticException if the result is inexact but the 933 * rounding mode is {@code UNNECESSARY}. 934 * @since 1.5 935 */ 936 public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) { 937 this(unscaledVal); 938 this.scale = scale; 939 if (mc.precision > 0) 940 roundThis(mc); 941 } 942 943 /** 944 * Translates an {@code int} into a {@code BigDecimal}. The 945 * scale of the {@code BigDecimal} is zero. 946 * 947 * @param val {@code int} value to be converted to 948 * {@code BigDecimal}. 949 * @since 1.5 950 */ 951 public BigDecimal(int val) { 952 intCompact = val; 953 } 954 955 /** 956 * Translates an {@code int} into a {@code BigDecimal}, with 957 * rounding according to the context settings. The scale of the 958 * {@code BigDecimal}, before any rounding, is zero. 959 * 960 * @param val {@code int} value to be converted to {@code BigDecimal}. 961 * @param mc the context to use. 962 * @throws ArithmeticException if the result is inexact but the 963 * rounding mode is {@code UNNECESSARY}. 964 * @since 1.5 965 */ 966 public BigDecimal(int val, MathContext mc) { 967 intCompact = val; 968 if (mc.precision > 0) 969 roundThis(mc); 970 } 971 972 /** 973 * Translates a {@code long} into a {@code BigDecimal}. The 974 * scale of the {@code BigDecimal} is zero. 975 * 976 * @param val {@code long} value to be converted to {@code BigDecimal}. 977 * @since 1.5 978 */ 979 public BigDecimal(long val) { 980 this.intCompact = val; 981 this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null; 982 } 983 984 /** 985 * Translates a {@code long} into a {@code BigDecimal}, with 986 * rounding according to the context settings. The scale of the 987 * {@code BigDecimal}, before any rounding, is zero. 988 * 989 * @param val {@code long} value to be converted to {@code BigDecimal}. 990 * @param mc the context to use. 991 * @throws ArithmeticException if the result is inexact but the 992 * rounding mode is {@code UNNECESSARY}. 993 * @since 1.5 994 */ 995 public BigDecimal(long val, MathContext mc) { 996 this(val); 997 if (mc.precision > 0) 998 roundThis(mc); 999 } 1000 1001 // Static Factory Methods 1002 1003 /** 1004 * Translates a {@code long} unscaled value and an 1005 * {@code int} scale into a {@code BigDecimal}. This 1006 * {@literal "static factory method"} is provided in preference to 1007 * a ({@code long}, {@code int}) constructor because it 1008 * allows for reuse of frequently used {@code BigDecimal} values.. 1009 * 1010 * @param unscaledVal unscaled value of the {@code BigDecimal}. 1011 * @param scale scale of the {@code BigDecimal}. 1012 * @return a {@code BigDecimal} whose value is 1013 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 1014 */ 1015 public static BigDecimal valueOf(long unscaledVal, int scale) { 1016 if (scale == 0) 1017 return valueOf(unscaledVal); 1018 else if (unscaledVal == 0) { 1019 if (scale > 0 && scale < ZERO_SCALED_BY.length) 1020 return ZERO_SCALED_BY[scale]; 1021 else 1022 return new BigDecimal(BigInteger.ZERO, 0, scale, 1); 1023 } 1024 return new BigDecimal(unscaledVal == INFLATED ? 1025 BigInteger.valueOf(unscaledVal) : null, 1026 unscaledVal, scale, 0); 1027 } 1028 1029 /** 1030 * Translates a {@code long} value into a {@code BigDecimal} 1031 * with a scale of zero. This {@literal "static factory method"} 1032 * is provided in preference to a ({@code long}) constructor 1033 * because it allows for reuse of frequently used 1034 * {@code BigDecimal} values. 1035 * 1036 * @param val value of the {@code BigDecimal}. 1037 * @return a {@code BigDecimal} whose value is {@code val}. 1038 */ 1039 public static BigDecimal valueOf(long val) { 1040 if (val >= 0 && val < zeroThroughTen.length) 1041 return zeroThroughTen[(int)val]; 1042 else if (val != INFLATED) 1043 return new BigDecimal(null, val, 0, 0); 1044 return new BigDecimal(BigInteger.valueOf(val), val, 0, 0); 1045 } 1046 1047 /** 1048 * Translates a {@code double} into a {@code BigDecimal}, using 1049 * the {@code double}'s canonical string representation provided 1050 * by the {@link Double#toString(double)} method. 1051 * 1052 * <p><b>Note:</b> This is generally the preferred way to convert 1053 * a {@code double} (or {@code float}) into a 1054 * {@code BigDecimal}, as the value returned is equal to that 1055 * resulting from constructing a {@code BigDecimal} from the 1056 * result of using {@link Double#toString(double)}. 1057 * 1058 * @param val {@code double} to convert to a {@code BigDecimal}. 1059 * @return a {@code BigDecimal} whose value is equal to or approximately 1060 * equal to the value of {@code val}. 1061 * @throws NumberFormatException if {@code val} is infinite or NaN. 1062 * @since 1.5 1063 */ 1064 public static BigDecimal valueOf(double val) { 1065 // Reminder: a zero double returns '0.0', so we cannot fastpath 1066 // to use the constant ZERO. This might be important enough to 1067 // justify a factory approach, a cache, or a few private 1068 // constants, later. 1069 return new BigDecimal(Double.toString(val)); 1070 } 1071 1072 // Arithmetic Operations 1073 /** 1074 * Returns a {@code BigDecimal} whose value is {@code (this + 1075 * augend)}, and whose scale is {@code max(this.scale(), 1076 * augend.scale())}. 1077 * 1078 * @param augend value to be added to this {@code BigDecimal}. 1079 * @return {@code this + augend} 1080 */ 1081 public BigDecimal add(BigDecimal augend) { 1082 long xs = this.intCompact; 1083 long ys = augend.intCompact; 1084 BigInteger fst = (xs != INFLATED) ? null : this.intVal; 1085 BigInteger snd = (ys != INFLATED) ? null : augend.intVal; 1086 int rscale = this.scale; 1087 1088 long sdiff = (long)rscale - augend.scale; 1089 if (sdiff != 0) { 1090 if (sdiff < 0) { 1091 int raise = checkScale(-sdiff); 1092 rscale = augend.scale; 1093 if (xs == INFLATED || 1094 (xs = longMultiplyPowerTen(xs, raise)) == INFLATED) 1095 fst = bigMultiplyPowerTen(raise); 1096 } else { 1097 int raise = augend.checkScale(sdiff); 1098 if (ys == INFLATED || 1099 (ys = longMultiplyPowerTen(ys, raise)) == INFLATED) 1100 snd = augend.bigMultiplyPowerTen(raise); 1101 } 1102 } 1103 if (xs != INFLATED && ys != INFLATED) { 1104 long sum = xs + ys; 1105 // See "Hacker's Delight" section 2-12 for explanation of 1106 // the overflow test. 1107 if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed 1108 return BigDecimal.valueOf(sum, rscale); 1109 } 1110 if (fst == null) 1111 fst = BigInteger.valueOf(xs); 1112 if (snd == null) 1113 snd = BigInteger.valueOf(ys); 1114 BigInteger sum = fst.add(snd); 1115 return (fst.signum == snd.signum) ? 1116 new BigDecimal(sum, INFLATED, rscale, 0) : 1117 new BigDecimal(sum, rscale); 1118 } 1119 1120 /** 1121 * Returns a {@code BigDecimal} whose value is {@code (this + augend)}, 1122 * with rounding according to the context settings. 1123 * 1124 * If either number is zero and the precision setting is nonzero then 1125 * the other number, rounded if necessary, is used as the result. 1126 * 1127 * @param augend value to be added to this {@code BigDecimal}. 1128 * @param mc the context to use. 1129 * @return {@code this + augend}, rounded as necessary. 1130 * @throws ArithmeticException if the result is inexact but the 1131 * rounding mode is {@code UNNECESSARY}. 1132 * @since 1.5 1133 */ 1134 public BigDecimal add(BigDecimal augend, MathContext mc) { 1135 if (mc.precision == 0) 1136 return add(augend); 1137 BigDecimal lhs = this; 1138 1139 // Could optimize if values are compact 1140 this.inflate(); 1141 augend.inflate(); 1142 1143 // If either number is zero then the other number, rounded and 1144 // scaled if necessary, is used as the result. 1145 { 1146 boolean lhsIsZero = lhs.signum() == 0; 1147 boolean augendIsZero = augend.signum() == 0; 1148 1149 if (lhsIsZero || augendIsZero) { 1150 int preferredScale = Math.max(lhs.scale(), augend.scale()); 1151 BigDecimal result; 1152 1153 // Could use a factory for zero instead of a new object 1154 if (lhsIsZero && augendIsZero) 1155 return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0); 1156 1157 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc); 1158 1159 if (result.scale() == preferredScale) 1160 return result; 1161 else if (result.scale() > preferredScale) { 1162 BigDecimal scaledResult = 1163 new BigDecimal(result.intVal, result.intCompact, 1164 result.scale, 0); 1165 scaledResult.stripZerosToMatchScale(preferredScale); 1166 return scaledResult; 1167 } else { // result.scale < preferredScale 1168 int precisionDiff = mc.precision - result.precision(); 1169 int scaleDiff = preferredScale - result.scale(); 1170 1171 if (precisionDiff >= scaleDiff) 1172 return result.setScale(preferredScale); // can achieve target scale 1173 else 1174 return result.setScale(result.scale() + precisionDiff); 1175 } 1176 } 1177 } 1178 1179 long padding = (long)lhs.scale - augend.scale; 1180 if (padding != 0) { // scales differ; alignment needed 1181 BigDecimal arg[] = preAlign(lhs, augend, padding, mc); 1182 matchScale(arg); 1183 lhs = arg[0]; 1184 augend = arg[1]; 1185 } 1186 1187 BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()), 1188 lhs.scale); 1189 return doRound(d, mc); 1190 } 1191 1192 /** 1193 * Returns an array of length two, the sum of whose entries is 1194 * equal to the rounded sum of the {@code BigDecimal} arguments. 1195 * 1196 * <p>If the digit positions of the arguments have a sufficient 1197 * gap between them, the value smaller in magnitude can be 1198 * condensed into a {@literal "sticky bit"} and the end result will 1199 * round the same way <em>if</em> the precision of the final 1200 * result does not include the high order digit of the small 1201 * magnitude operand. 1202 * 1203 * <p>Note that while strictly speaking this is an optimization, 1204 * it makes a much wider range of additions practical. 1205 * 1206 * <p>This corresponds to a pre-shift operation in a fixed 1207 * precision floating-point adder; this method is complicated by 1208 * variable precision of the result as determined by the 1209 * MathContext. A more nuanced operation could implement a 1210 * {@literal "right shift"} on the smaller magnitude operand so 1211 * that the number of digits of the smaller operand could be 1212 * reduced even though the significands partially overlapped. 1213 */ 1214 private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, 1215 long padding, MathContext mc) { 1216 assert padding != 0; 1217 BigDecimal big; 1218 BigDecimal small; 1219 1220 if (padding < 0) { // lhs is big; augend is small 1221 big = lhs; 1222 small = augend; 1223 } else { // lhs is small; augend is big 1224 big = augend; 1225 small = lhs; 1226 } 1227 1228 /* 1229 * This is the estimated scale of an ulp of the result; it 1230 * assumes that the result doesn't have a carry-out on a true 1231 * add (e.g. 999 + 1 => 1000) or any subtractive cancellation 1232 * on borrowing (e.g. 100 - 1.2 => 98.8) 1233 */ 1234 long estResultUlpScale = (long)big.scale - big.precision() + mc.precision; 1235 1236 /* 1237 * The low-order digit position of big is big.scale(). This 1238 * is true regardless of whether big has a positive or 1239 * negative scale. The high-order digit position of small is 1240 * small.scale - (small.precision() - 1). To do the full 1241 * condensation, the digit positions of big and small must be 1242 * disjoint *and* the digit positions of small should not be 1243 * directly visible in the result. 1244 */ 1245 long smallHighDigitPos = (long)small.scale - small.precision() + 1; 1246 if (smallHighDigitPos > big.scale + 2 && // big and small disjoint 1247 smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible 1248 small = BigDecimal.valueOf(small.signum(), 1249 this.checkScale(Math.max(big.scale, estResultUlpScale) + 3)); 1250 } 1251 1252 // Since addition is symmetric, preserving input order in 1253 // returned operands doesn't matter 1254 BigDecimal[] result = {big, small}; 1255 return result; 1256 } 1257 1258 /** 1259 * Returns a {@code BigDecimal} whose value is {@code (this - 1260 * subtrahend)}, and whose scale is {@code max(this.scale(), 1261 * subtrahend.scale())}. 1262 * 1263 * @param subtrahend value to be subtracted from this {@code BigDecimal}. 1264 * @return {@code this - subtrahend} 1265 */ 1266 public BigDecimal subtract(BigDecimal subtrahend) { 1267 return add(subtrahend.negate()); 1268 } 1269 1270 /** 1271 * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)}, 1272 * with rounding according to the context settings. 1273 * 1274 * If {@code subtrahend} is zero then this, rounded if necessary, is used as the 1275 * result. If this is zero then the result is {@code subtrahend.negate(mc)}. 1276 * 1277 * @param subtrahend value to be subtracted from this {@code BigDecimal}. 1278 * @param mc the context to use. 1279 * @return {@code this - subtrahend}, rounded as necessary. 1280 * @throws ArithmeticException if the result is inexact but the 1281 * rounding mode is {@code UNNECESSARY}. 1282 * @since 1.5 1283 */ 1284 public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) { 1285 BigDecimal nsubtrahend = subtrahend.negate(); 1286 if (mc.precision == 0) 1287 return add(nsubtrahend); 1288 // share the special rounding code in add() 1289 return add(nsubtrahend, mc); 1290 } 1291 1292 /** 1293 * Returns a {@code BigDecimal} whose value is <tt>(this × 1294 * multiplicand)</tt>, and whose scale is {@code (this.scale() + 1295 * multiplicand.scale())}. 1296 * 1297 * @param multiplicand value to be multiplied by this {@code BigDecimal}. 1298 * @return {@code this * multiplicand} 1299 */ 1300 public BigDecimal multiply(BigDecimal multiplicand) { 1301 long x = this.intCompact; 1302 long y = multiplicand.intCompact; 1303 int productScale = checkScale((long)scale + multiplicand.scale); 1304 1305 // Might be able to do a more clever check incorporating the 1306 // inflated check into the overflow computation. 1307 if (x != INFLATED && y != INFLATED) { 1308 /* 1309 * If the product is not an overflowed value, continue 1310 * to use the compact representation. if either of x or y 1311 * is INFLATED, the product should also be regarded as 1312 * an overflow. Before using the overflow test suggested in 1313 * "Hacker's Delight" section 2-12, we perform quick checks 1314 * using the precision information to see whether the overflow 1315 * would occur since division is expensive on most CPUs. 1316 */ 1317 long product = x * y; 1318 long prec = this.precision() + multiplicand.precision(); 1319 if (prec < 19 || (prec < 21 && (y == 0 || product / y == x))) 1320 return BigDecimal.valueOf(product, productScale); 1321 return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED, 1322 productScale, 0); 1323 } 1324 BigInteger rb; 1325 if (x == INFLATED && y == INFLATED) 1326 rb = this.intVal.multiply(multiplicand.intVal); 1327 else if (x != INFLATED) 1328 rb = multiplicand.intVal.multiply(x); 1329 else 1330 rb = this.intVal.multiply(y); 1331 return new BigDecimal(rb, INFLATED, productScale, 0); 1332 } 1333 1334 /** 1335 * Returns a {@code BigDecimal} whose value is <tt>(this × 1336 * multiplicand)</tt>, with rounding according to the context settings. 1337 * 1338 * @param multiplicand value to be multiplied by this {@code BigDecimal}. 1339 * @param mc the context to use. 1340 * @return {@code this * multiplicand}, rounded as necessary. 1341 * @throws ArithmeticException if the result is inexact but the 1342 * rounding mode is {@code UNNECESSARY}. 1343 * @since 1.5 1344 */ 1345 public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { 1346 if (mc.precision == 0) 1347 return multiply(multiplicand); 1348 return doRound(this.multiply(multiplicand), mc); 1349 } 1350 1351 /** 1352 * Returns a {@code BigDecimal} whose value is {@code (this / 1353 * divisor)}, and whose scale is as specified. If rounding must 1354 * be performed to generate a result with the specified scale, the 1355 * specified rounding mode is applied. 1356 * 1357 * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method 1358 * should be used in preference to this legacy method. 1359 * 1360 * @param divisor value by which this {@code BigDecimal} is to be divided. 1361 * @param scale scale of the {@code BigDecimal} quotient to be returned. 1362 * @param roundingMode rounding mode to apply. 1363 * @return {@code this / divisor} 1364 * @throws ArithmeticException if {@code divisor} is zero, 1365 * {@code roundingMode==ROUND_UNNECESSARY} and 1366 * the specified scale is insufficient to represent the result 1367 * of the division exactly. 1368 * @throws IllegalArgumentException if {@code roundingMode} does not 1369 * represent a valid rounding mode. 1370 * @see #ROUND_UP 1371 * @see #ROUND_DOWN 1372 * @see #ROUND_CEILING 1373 * @see #ROUND_FLOOR 1374 * @see #ROUND_HALF_UP 1375 * @see #ROUND_HALF_DOWN 1376 * @see #ROUND_HALF_EVEN 1377 * @see #ROUND_UNNECESSARY 1378 */ 1379 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { 1380 /* 1381 * IMPLEMENTATION NOTE: This method *must* return a new object 1382 * since divideAndRound uses divide to generate a value whose 1383 * scale is then modified. 1384 */ 1385 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 1386 throw new IllegalArgumentException("Invalid rounding mode"); 1387 /* 1388 * Rescale dividend or divisor (whichever can be "upscaled" to 1389 * produce correctly scaled quotient). 1390 * Take care to detect out-of-range scales 1391 */ 1392 BigDecimal dividend = this; 1393 if (checkScale((long)scale + divisor.scale) > this.scale) 1394 dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY); 1395 else 1396 divisor = divisor.setScale(checkScale((long)this.scale - scale), 1397 ROUND_UNNECESSARY); 1398 return divideAndRound(dividend.intCompact, dividend.intVal, 1399 divisor.intCompact, divisor.intVal, 1400 scale, roundingMode, scale); 1401 } 1402 1403 /** 1404 * Internally used for division operation. The dividend and divisor are 1405 * passed both in {@code long} format and {@code BigInteger} format. The 1406 * returned {@code BigDecimal} object is the quotient whose scale is set to 1407 * the passed in scale. If the remainder is not zero, it will be rounded 1408 * based on the passed in roundingMode. Also, if the remainder is zero and 1409 * the last parameter, i.e. preferredScale is NOT equal to scale, the 1410 * trailing zeros of the result is stripped to match the preferredScale. 1411 */ 1412 private static BigDecimal divideAndRound(long ldividend, BigInteger bdividend, 1413 long ldivisor, BigInteger bdivisor, 1414 int scale, int roundingMode, 1415 int preferredScale) { 1416 boolean isRemainderZero; // record remainder is zero or not 1417 int qsign; // quotient sign 1418 long q = 0, r = 0; // store quotient & remainder in long 1419 MutableBigInteger mq = null; // store quotient 1420 MutableBigInteger mr = null; // store remainder 1421 MutableBigInteger mdivisor = null; 1422 boolean isLongDivision = (ldividend != INFLATED && ldivisor != INFLATED); 1423 if (isLongDivision) { 1424 q = ldividend / ldivisor; 1425 if (roundingMode == ROUND_DOWN && scale == preferredScale) 1426 return new BigDecimal(null, q, scale, 0); 1427 r = ldividend % ldivisor; 1428 isRemainderZero = (r == 0); 1429 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; 1430 } else { 1431 if (bdividend == null) 1432 bdividend = BigInteger.valueOf(ldividend); 1433 // Descend into mutables for faster remainder checks 1434 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 1435 mq = new MutableBigInteger(); 1436 if (ldivisor != INFLATED) { 1437 r = mdividend.divide(ldivisor, mq); 1438 isRemainderZero = (r == 0); 1439 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; 1440 } else { 1441 mdivisor = new MutableBigInteger(bdivisor.mag); 1442 mr = mdividend.divide(mdivisor, mq); 1443 isRemainderZero = mr.isZero(); 1444 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; 1445 } 1446 } 1447 boolean increment = false; 1448 if (!isRemainderZero) { 1449 int cmpFracHalf; 1450 /* Round as appropriate */ 1451 if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited 1452 throw new ArithmeticException("Rounding necessary"); 1453 } else if (roundingMode == ROUND_UP) { // Away from zero 1454 increment = true; 1455 } else if (roundingMode == ROUND_DOWN) { // Towards zero 1456 increment = false; 1457 } else if (roundingMode == ROUND_CEILING) { // Towards +infinity 1458 increment = (qsign > 0); 1459 } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity 1460 increment = (qsign < 0); 1461 } else { 1462 if (isLongDivision || ldivisor != INFLATED) { 1463 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { 1464 cmpFracHalf = 1; // 2 * r can't fit into long 1465 } else { 1466 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); 1467 } 1468 } else { 1469 cmpFracHalf = mr.compareHalf(mdivisor); 1470 } 1471 if (cmpFracHalf < 0) 1472 increment = false; // We're closer to higher digit 1473 else if (cmpFracHalf > 0) // We're closer to lower digit 1474 increment = true; 1475 else if (roundingMode == ROUND_HALF_UP) 1476 increment = true; 1477 else if (roundingMode == ROUND_HALF_DOWN) 1478 increment = false; 1479 else // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd 1480 increment = isLongDivision ? (q & 1L) != 0L : mq.isOdd(); 1481 } 1482 } 1483 BigDecimal res; 1484 if (isLongDivision) 1485 res = new BigDecimal(null, (increment ? q + qsign : q), scale, 0); 1486 else { 1487 if (increment) 1488 mq.add(MutableBigInteger.ONE); 1489 res = mq.toBigDecimal(qsign, scale); 1490 } 1491 if (isRemainderZero && preferredScale != scale) 1492 res.stripZerosToMatchScale(preferredScale); 1493 return res; 1494 } 1495 1496 /** 1497 * Returns a {@code BigDecimal} whose value is {@code (this / 1498 * divisor)}, and whose scale is as specified. If rounding must 1499 * be performed to generate a result with the specified scale, the 1500 * specified rounding mode is applied. 1501 * 1502 * @param divisor value by which this {@code BigDecimal} is to be divided. 1503 * @param scale scale of the {@code BigDecimal} quotient to be returned. 1504 * @param roundingMode rounding mode to apply. 1505 * @return {@code this / divisor} 1506 * @throws ArithmeticException if {@code divisor} is zero, 1507 * {@code roundingMode==RoundingMode.UNNECESSARY} and 1508 * the specified scale is insufficient to represent the result 1509 * of the division exactly. 1510 * @since 1.5 1511 */ 1512 public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { 1513 return divide(divisor, scale, roundingMode.oldMode); 1514 } 1515 1516 /** 1517 * Returns a {@code BigDecimal} whose value is {@code (this / 1518 * divisor)}, and whose scale is {@code this.scale()}. If 1519 * rounding must be performed to generate a result with the given 1520 * scale, the specified rounding mode is applied. 1521 * 1522 * <p>The new {@link #divide(BigDecimal, RoundingMode)} method 1523 * should be used in preference to this legacy method. 1524 * 1525 * @param divisor value by which this {@code BigDecimal} is to be divided. 1526 * @param roundingMode rounding mode to apply. 1527 * @return {@code this / divisor} 1528 * @throws ArithmeticException if {@code divisor==0}, or 1529 * {@code roundingMode==ROUND_UNNECESSARY} and 1530 * {@code this.scale()} is insufficient to represent the result 1531 * of the division exactly. 1532 * @throws IllegalArgumentException if {@code roundingMode} does not 1533 * represent a valid rounding mode. 1534 * @see #ROUND_UP 1535 * @see #ROUND_DOWN 1536 * @see #ROUND_CEILING 1537 * @see #ROUND_FLOOR 1538 * @see #ROUND_HALF_UP 1539 * @see #ROUND_HALF_DOWN 1540 * @see #ROUND_HALF_EVEN 1541 * @see #ROUND_UNNECESSARY 1542 */ 1543 public BigDecimal divide(BigDecimal divisor, int roundingMode) { 1544 return this.divide(divisor, scale, roundingMode); 1545 } 1546 1547 /** 1548 * Returns a {@code BigDecimal} whose value is {@code (this / 1549 * divisor)}, and whose scale is {@code this.scale()}. If 1550 * rounding must be performed to generate a result with the given 1551 * scale, the specified rounding mode is applied. 1552 * 1553 * @param divisor value by which this {@code BigDecimal} is to be divided. 1554 * @param roundingMode rounding mode to apply. 1555 * @return {@code this / divisor} 1556 * @throws ArithmeticException if {@code divisor==0}, or 1557 * {@code roundingMode==RoundingMode.UNNECESSARY} and 1558 * {@code this.scale()} is insufficient to represent the result 1559 * of the division exactly. 1560 * @since 1.5 1561 */ 1562 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { 1563 return this.divide(divisor, scale, roundingMode.oldMode); 1564 } 1565 1566 /** 1567 * Returns a {@code BigDecimal} whose value is {@code (this / 1568 * divisor)}, and whose preferred scale is {@code (this.scale() - 1569 * divisor.scale())}; if the exact quotient cannot be 1570 * represented (because it has a non-terminating decimal 1571 * expansion) an {@code ArithmeticException} is thrown. 1572 * 1573 * @param divisor value by which this {@code BigDecimal} is to be divided. 1574 * @throws ArithmeticException if the exact quotient does not have a 1575 * terminating decimal expansion 1576 * @return {@code this / divisor} 1577 * @since 1.5 1578 * @author Joseph D. Darcy 1579 */ 1580 public BigDecimal divide(BigDecimal divisor) { 1581 /* 1582 * Handle zero cases first. 1583 */ 1584 if (divisor.signum() == 0) { // x/0 1585 if (this.signum() == 0) // 0/0 1586 throw new ArithmeticException("Division undefined"); // NaN 1587 throw new ArithmeticException("Division by zero"); 1588 } 1589 1590 // Calculate preferred scale 1591 int preferredScale = saturateLong((long)this.scale - divisor.scale); 1592 if (this.signum() == 0) // 0/y 1593 return (preferredScale >= 0 && 1594 preferredScale < ZERO_SCALED_BY.length) ? 1595 ZERO_SCALED_BY[preferredScale] : 1596 BigDecimal.valueOf(0, preferredScale); 1597 else { 1598 this.inflate(); 1599 divisor.inflate(); 1600 /* 1601 * If the quotient this/divisor has a terminating decimal 1602 * expansion, the expansion can have no more than 1603 * (a.precision() + ceil(10*b.precision)/3) digits. 1604 * Therefore, create a MathContext object with this 1605 * precision and do a divide with the UNNECESSARY rounding 1606 * mode. 1607 */ 1608 MathContext mc = new MathContext( (int)Math.min(this.precision() + 1609 (long)Math.ceil(10.0*divisor.precision()/3.0), 1610 Integer.MAX_VALUE), 1611 RoundingMode.UNNECESSARY); 1612 BigDecimal quotient; 1613 try { 1614 quotient = this.divide(divisor, mc); 1615 } catch (ArithmeticException e) { 1616 throw new ArithmeticException("Non-terminating decimal expansion; " + 1617 "no exact representable decimal result."); 1618 } 1619 1620 int quotientScale = quotient.scale(); 1621 1622 // divide(BigDecimal, mc) tries to adjust the quotient to 1623 // the desired one by removing trailing zeros; since the 1624 // exact divide method does not have an explicit digit 1625 // limit, we can add zeros too. 1626 1627 if (preferredScale > quotientScale) 1628 return quotient.setScale(preferredScale, ROUND_UNNECESSARY); 1629 1630 return quotient; 1631 } 1632 } 1633 1634 /** 1635 * Returns a {@code BigDecimal} whose value is {@code (this / 1636 * divisor)}, with rounding according to the context settings. 1637 * 1638 * @param divisor value by which this {@code BigDecimal} is to be divided. 1639 * @param mc the context to use. 1640 * @return {@code this / divisor}, rounded as necessary. 1641 * @throws ArithmeticException if the result is inexact but the 1642 * rounding mode is {@code UNNECESSARY} or 1643 * {@code mc.precision == 0} and the quotient has a 1644 * non-terminating decimal expansion. 1645 * @since 1.5 1646 */ 1647 public BigDecimal divide(BigDecimal divisor, MathContext mc) { 1648 int mcp = mc.precision; 1649 if (mcp == 0) 1650 return divide(divisor); 1651 1652 BigDecimal dividend = this; 1653 long preferredScale = (long)dividend.scale - divisor.scale; 1654 // Now calculate the answer. We use the existing 1655 // divide-and-round method, but as this rounds to scale we have 1656 // to normalize the values here to achieve the desired result. 1657 // For x/y we first handle y=0 and x=0, and then normalize x and 1658 // y to give x' and y' with the following constraints: 1659 // (a) 0.1 <= x' < 1 1660 // (b) x' <= y' < 10*x' 1661 // Dividing x'/y' with the required scale set to mc.precision then 1662 // will give a result in the range 0.1 to 1 rounded to exactly 1663 // the right number of digits (except in the case of a result of 1664 // 1.000... which can arise when x=y, or when rounding overflows 1665 // The 1.000... case will reduce properly to 1. 1666 if (divisor.signum() == 0) { // x/0 1667 if (dividend.signum() == 0) // 0/0 1668 throw new ArithmeticException("Division undefined"); // NaN 1669 throw new ArithmeticException("Division by zero"); 1670 } 1671 if (dividend.signum() == 0) // 0/y 1672 return new BigDecimal(BigInteger.ZERO, 0, 1673 saturateLong(preferredScale), 1); 1674 1675 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 1676 int xscale = dividend.precision(); 1677 int yscale = divisor.precision(); 1678 dividend = new BigDecimal(dividend.intVal, dividend.intCompact, 1679 xscale, xscale); 1680 divisor = new BigDecimal(divisor.intVal, divisor.intCompact, 1681 yscale, yscale); 1682 if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b) 1683 yscale = divisor.scale -= 1; // [that is, divisor *= 10] 1684 1685 // In order to find out whether the divide generates the exact result, 1686 // we avoid calling the above divide method. 'quotient' holds the 1687 // return BigDecimal object whose scale will be set to 'scl'. 1688 BigDecimal quotient; 1689 int scl = checkScale(preferredScale + yscale - xscale + mcp); 1690 if (checkScale((long)mcp + yscale) > xscale) 1691 dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY); 1692 else 1693 divisor = divisor.setScale(checkScale((long)xscale - mcp), 1694 ROUND_UNNECESSARY); 1695 quotient = divideAndRound(dividend.intCompact, dividend.intVal, 1696 divisor.intCompact, divisor.intVal, 1697 scl, mc.roundingMode.oldMode, 1698 checkScale(preferredScale)); 1699 // doRound, here, only affects 1000000000 case. 1700 quotient = doRound(quotient, mc); 1701 1702 return quotient; 1703 } 1704 1705 /** 1706 * Returns a {@code BigDecimal} whose value is the integer part 1707 * of the quotient {@code (this / divisor)} rounded down. The 1708 * preferred scale of the result is {@code (this.scale() - 1709 * divisor.scale())}. 1710 * 1711 * @param divisor value by which this {@code BigDecimal} is to be divided. 1712 * @return The integer part of {@code this / divisor}. 1713 * @throws ArithmeticException if {@code divisor==0} 1714 * @since 1.5 1715 */ 1716 public BigDecimal divideToIntegralValue(BigDecimal divisor) { 1717 // Calculate preferred scale 1718 int preferredScale = saturateLong((long)this.scale - divisor.scale); 1719 if (this.compareMagnitude(divisor) < 0) { 1720 // much faster when this << divisor 1721 return BigDecimal.valueOf(0, preferredScale); 1722 } 1723 1724 if(this.signum() == 0 && divisor.signum() != 0) 1725 return this.setScale(preferredScale, ROUND_UNNECESSARY); 1726 1727 // Perform a divide with enough digits to round to a correct 1728 // integer value; then remove any fractional digits 1729 1730 int maxDigits = (int)Math.min(this.precision() + 1731 (long)Math.ceil(10.0*divisor.precision()/3.0) + 1732 Math.abs((long)this.scale() - divisor.scale()) + 2, 1733 Integer.MAX_VALUE); 1734 BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits, 1735 RoundingMode.DOWN)); 1736 if (quotient.scale > 0) { 1737 quotient = quotient.setScale(0, RoundingMode.DOWN); 1738 quotient.stripZerosToMatchScale(preferredScale); 1739 } 1740 1741 if (quotient.scale < preferredScale) { 1742 // pad with zeros if necessary 1743 quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY); 1744 } 1745 return quotient; 1746 } 1747 1748 /** 1749 * Returns a {@code BigDecimal} whose value is the integer part 1750 * of {@code (this / divisor)}. Since the integer part of the 1751 * exact quotient does not depend on the rounding mode, the 1752 * rounding mode does not affect the values returned by this 1753 * method. The preferred scale of the result is 1754 * {@code (this.scale() - divisor.scale())}. An 1755 * {@code ArithmeticException} is thrown if the integer part of 1756 * the exact quotient needs more than {@code mc.precision} 1757 * digits. 1758 * 1759 * @param divisor value by which this {@code BigDecimal} is to be divided. 1760 * @param mc the context to use. 1761 * @return The integer part of {@code this / divisor}. 1762 * @throws ArithmeticException if {@code divisor==0} 1763 * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result 1764 * requires a precision of more than {@code mc.precision} digits. 1765 * @since 1.5 1766 * @author Joseph D. Darcy 1767 */ 1768 public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { 1769 if (mc.precision == 0 || // exact result 1770 (this.compareMagnitude(divisor) < 0) ) // zero result 1771 return divideToIntegralValue(divisor); 1772 1773 // Calculate preferred scale 1774 int preferredScale = saturateLong((long)this.scale - divisor.scale); 1775 1776 /* 1777 * Perform a normal divide to mc.precision digits. If the 1778 * remainder has absolute value less than the divisor, the 1779 * integer portion of the quotient fits into mc.precision 1780 * digits. Next, remove any fractional digits from the 1781 * quotient and adjust the scale to the preferred value. 1782 */ 1783 BigDecimal result = this. 1784 divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN)); 1785 1786 if (result.scale() < 0) { 1787 /* 1788 * Result is an integer. See if quotient represents the 1789 * full integer portion of the exact quotient; if it does, 1790 * the computed remainder will be less than the divisor. 1791 */ 1792 BigDecimal product = result.multiply(divisor); 1793 // If the quotient is the full integer value, 1794 // |dividend-product| < |divisor|. 1795 if (this.subtract(product).compareMagnitude(divisor) >= 0) { 1796 throw new ArithmeticException("Division impossible"); 1797 } 1798 } else if (result.scale() > 0) { 1799 /* 1800 * Integer portion of quotient will fit into precision 1801 * digits; recompute quotient to scale 0 to avoid double 1802 * rounding and then try to adjust, if necessary. 1803 */ 1804 result = result.setScale(0, RoundingMode.DOWN); 1805 } 1806 // else result.scale() == 0; 1807 1808 int precisionDiff; 1809 if ((preferredScale > result.scale()) && 1810 (precisionDiff = mc.precision - result.precision()) > 0) { 1811 return result.setScale(result.scale() + 1812 Math.min(precisionDiff, preferredScale - result.scale) ); 1813 } else { 1814 result.stripZerosToMatchScale(preferredScale); 1815 return result; 1816 } 1817 } 1818 1819 /** 1820 * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}. 1821 * 1822 * <p>The remainder is given by 1823 * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. 1824 * Note that this is not the modulo operation (the result can be 1825 * negative). 1826 * 1827 * @param divisor value by which this {@code BigDecimal} is to be divided. 1828 * @return {@code this % divisor}. 1829 * @throws ArithmeticException if {@code divisor==0} 1830 * @since 1.5 1831 */ 1832 public BigDecimal remainder(BigDecimal divisor) { 1833 BigDecimal divrem[] = this.divideAndRemainder(divisor); 1834 return divrem[1]; 1835 } 1836 1837 1838 /** 1839 * Returns a {@code BigDecimal} whose value is {@code (this % 1840 * divisor)}, with rounding according to the context settings. 1841 * The {@code MathContext} settings affect the implicit divide 1842 * used to compute the remainder. The remainder computation 1843 * itself is by definition exact. Therefore, the remainder may 1844 * contain more than {@code mc.getPrecision()} digits. 1845 * 1846 * <p>The remainder is given by 1847 * {@code this.subtract(this.divideToIntegralValue(divisor, 1848 * mc).multiply(divisor))}. Note that this is not the modulo 1849 * operation (the result can be negative). 1850 * 1851 * @param divisor value by which this {@code BigDecimal} is to be divided. 1852 * @param mc the context to use. 1853 * @return {@code this % divisor}, rounded as necessary. 1854 * @throws ArithmeticException if {@code divisor==0} 1855 * @throws ArithmeticException if the result is inexact but the 1856 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 1857 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 1858 * require a precision of more than {@code mc.precision} digits. 1859 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1860 * @since 1.5 1861 */ 1862 public BigDecimal remainder(BigDecimal divisor, MathContext mc) { 1863 BigDecimal divrem[] = this.divideAndRemainder(divisor, mc); 1864 return divrem[1]; 1865 } 1866 1867 /** 1868 * Returns a two-element {@code BigDecimal} array containing the 1869 * result of {@code divideToIntegralValue} followed by the result of 1870 * {@code remainder} on the two operands. 1871 * 1872 * <p>Note that if both the integer quotient and remainder are 1873 * needed, this method is faster than using the 1874 * {@code divideToIntegralValue} and {@code remainder} methods 1875 * separately because the division need only be carried out once. 1876 * 1877 * @param divisor value by which this {@code BigDecimal} is to be divided, 1878 * and the remainder computed. 1879 * @return a two element {@code BigDecimal} array: the quotient 1880 * (the result of {@code divideToIntegralValue}) is the initial element 1881 * and the remainder is the final element. 1882 * @throws ArithmeticException if {@code divisor==0} 1883 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1884 * @see #remainder(java.math.BigDecimal, java.math.MathContext) 1885 * @since 1.5 1886 */ 1887 public BigDecimal[] divideAndRemainder(BigDecimal divisor) { 1888 // we use the identity x = i * y + r to determine r 1889 BigDecimal[] result = new BigDecimal[2]; 1890 1891 result[0] = this.divideToIntegralValue(divisor); 1892 result[1] = this.subtract(result[0].multiply(divisor)); 1893 return result; 1894 } 1895 1896 /** 1897 * Returns a two-element {@code BigDecimal} array containing the 1898 * result of {@code divideToIntegralValue} followed by the result of 1899 * {@code remainder} on the two operands calculated with rounding 1900 * according to the context settings. 1901 * 1902 * <p>Note that if both the integer quotient and remainder are 1903 * needed, this method is faster than using the 1904 * {@code divideToIntegralValue} and {@code remainder} methods 1905 * separately because the division need only be carried out once. 1906 * 1907 * @param divisor value by which this {@code BigDecimal} is to be divided, 1908 * and the remainder computed. 1909 * @param mc the context to use. 1910 * @return a two element {@code BigDecimal} array: the quotient 1911 * (the result of {@code divideToIntegralValue}) is the 1912 * initial element and the remainder is the final element. 1913 * @throws ArithmeticException if {@code divisor==0} 1914 * @throws ArithmeticException if the result is inexact but the 1915 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 1916 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 1917 * require a precision of more than {@code mc.precision} digits. 1918 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1919 * @see #remainder(java.math.BigDecimal, java.math.MathContext) 1920 * @since 1.5 1921 */ 1922 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { 1923 if (mc.precision == 0) 1924 return divideAndRemainder(divisor); 1925 1926 BigDecimal[] result = new BigDecimal[2]; 1927 BigDecimal lhs = this; 1928 1929 result[0] = lhs.divideToIntegralValue(divisor, mc); 1930 result[1] = lhs.subtract(result[0].multiply(divisor)); 1931 return result; 1932 } 1933 1934 /** 1935 * Returns a {@code BigDecimal} whose value is 1936 * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to 1937 * unlimited precision. 1938 * 1939 * <p>The parameter {@code n} must be in the range 0 through 1940 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link 1941 * #ONE}. 1942 * 1943 * Note that future releases may expand the allowable exponent 1944 * range of this method. 1945 * 1946 * @param n power to raise this {@code BigDecimal} to. 1947 * @return <tt>this<sup>n</sup></tt> 1948 * @throws ArithmeticException if {@code n} is out of range. 1949 * @since 1.5 1950 */ 1951 public BigDecimal pow(int n) { 1952 if (n < 0 || n > 999999999) 1953 throw new ArithmeticException("Invalid operation"); 1954 // No need to calculate pow(n) if result will over/underflow. 1955 // Don't attempt to support "supernormal" numbers. 1956 int newScale = checkScale((long)scale * n); 1957 this.inflate(); 1958 return new BigDecimal(intVal.pow(n), newScale); 1959 } 1960 1961 1962 /** 1963 * Returns a {@code BigDecimal} whose value is 1964 * <tt>(this<sup>n</sup>)</tt>. The current implementation uses 1965 * the core algorithm defined in ANSI standard X3.274-1996 with 1966 * rounding according to the context settings. In general, the 1967 * returned numerical value is within two ulps of the exact 1968 * numerical value for the chosen precision. Note that future 1969 * releases may use a different algorithm with a decreased 1970 * allowable error bound and increased allowable exponent range. 1971 * 1972 * <p>The X3.274-1996 algorithm is: 1973 * 1974 * <ul> 1975 * <li> An {@code ArithmeticException} exception is thrown if 1976 * <ul> 1977 * <li>{@code abs(n) > 999999999} 1978 * <li>{@code mc.precision == 0} and {@code n < 0} 1979 * <li>{@code mc.precision > 0} and {@code n} has more than 1980 * {@code mc.precision} decimal digits 1981 * </ul> 1982 * 1983 * <li> if {@code n} is zero, {@link #ONE} is returned even if 1984 * {@code this} is zero, otherwise 1985 * <ul> 1986 * <li> if {@code n} is positive, the result is calculated via 1987 * the repeated squaring technique into a single accumulator. 1988 * The individual multiplications with the accumulator use the 1989 * same math context settings as in {@code mc} except for a 1990 * precision increased to {@code mc.precision + elength + 1} 1991 * where {@code elength} is the number of decimal digits in 1992 * {@code n}. 1993 * 1994 * <li> if {@code n} is negative, the result is calculated as if 1995 * {@code n} were positive; this value is then divided into one 1996 * using the working precision specified above. 1997 * 1998 * <li> The final value from either the positive or negative case 1999 * is then rounded to the destination precision. 2000 * </ul> 2001 * </ul> 2002 * 2003 * @param n power to raise this {@code BigDecimal} to. 2004 * @param mc the context to use. 2005 * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996 2006 * algorithm 2007 * @throws ArithmeticException if the result is inexact but the 2008 * rounding mode is {@code UNNECESSARY}, or {@code n} is out 2009 * of range. 2010 * @since 1.5 2011 */ 2012 public BigDecimal pow(int n, MathContext mc) { 2013 if (mc.precision == 0) 2014 return pow(n); 2015 if (n < -999999999 || n > 999999999) 2016 throw new ArithmeticException("Invalid operation"); 2017 if (n == 0) 2018 return ONE; // x**0 == 1 in X3.274 2019 this.inflate(); 2020 BigDecimal lhs = this; 2021 MathContext workmc = mc; // working settings 2022 int mag = Math.abs(n); // magnitude of n 2023 if (mc.precision > 0) { 2024 2025 int elength = longDigitLength(mag); // length of n in digits 2026 if (elength > mc.precision) // X3.274 rule 2027 throw new ArithmeticException("Invalid operation"); 2028 workmc = new MathContext(mc.precision + elength + 1, 2029 mc.roundingMode); 2030 } 2031 // ready to carry out power calculation... 2032 BigDecimal acc = ONE; // accumulator 2033 boolean seenbit = false; // set once we've seen a 1-bit 2034 for (int i=1;;i++) { // for each bit [top bit ignored] 2035 mag += mag; // shift left 1 bit 2036 if (mag < 0) { // top bit is set 2037 seenbit = true; // OK, we're off 2038 acc = acc.multiply(lhs, workmc); // acc=acc*x 2039 } 2040 if (i == 31) 2041 break; // that was the last bit 2042 if (seenbit) 2043 acc=acc.multiply(acc, workmc); // acc=acc*acc [square] 2044 // else (!seenbit) no point in squaring ONE 2045 } 2046 // if negative n, calculate the reciprocal using working precision 2047 if (n<0) // [hence mc.precision>0] 2048 acc=ONE.divide(acc, workmc); 2049 // round to final precision and strip zeros 2050 return doRound(acc, mc); 2051 } 2052 2053 /** 2054 * Returns a {@code BigDecimal} whose value is the absolute value 2055 * of this {@code BigDecimal}, and whose scale is 2056 * {@code this.scale()}. 2057 * 2058 * @return {@code abs(this)} 2059 */ 2060 public BigDecimal abs() { 2061 return (signum() < 0 ? negate() : this); 2062 } 2063 2064 /** 2065 * Returns a {@code BigDecimal} whose value is the absolute value 2066 * of this {@code BigDecimal}, with rounding according to the 2067 * context settings. 2068 * 2069 * @param mc the context to use. 2070 * @return {@code abs(this)}, rounded as necessary. 2071 * @throws ArithmeticException if the result is inexact but the 2072 * rounding mode is {@code UNNECESSARY}. 2073 * @since 1.5 2074 */ 2075 public BigDecimal abs(MathContext mc) { 2076 return (signum() < 0 ? negate(mc) : plus(mc)); 2077 } 2078 2079 /** 2080 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2081 * and whose scale is {@code this.scale()}. 2082 * 2083 * @return {@code -this}. 2084 */ 2085 public BigDecimal negate() { 2086 BigDecimal result; 2087 if (intCompact != INFLATED) 2088 result = BigDecimal.valueOf(-intCompact, scale); 2089 else { 2090 result = new BigDecimal(intVal.negate(), scale); 2091 result.precision = precision; 2092 } 2093 return result; 2094 } 2095 2096 /** 2097 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2098 * with rounding according to the context settings. 2099 * 2100 * @param mc the context to use. 2101 * @return {@code -this}, rounded as necessary. 2102 * @throws ArithmeticException if the result is inexact but the 2103 * rounding mode is {@code UNNECESSARY}. 2104 * @since 1.5 2105 */ 2106 public BigDecimal negate(MathContext mc) { 2107 return negate().plus(mc); 2108 } 2109 2110 /** 2111 * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose 2112 * scale is {@code this.scale()}. 2113 * 2114 * <p>This method, which simply returns this {@code BigDecimal} 2115 * is included for symmetry with the unary minus method {@link 2116 * #negate()}. 2117 * 2118 * @return {@code this}. 2119 * @see #negate() 2120 * @since 1.5 2121 */ 2122 public BigDecimal plus() { 2123 return this; 2124 } 2125 2126 /** 2127 * Returns a {@code BigDecimal} whose value is {@code (+this)}, 2128 * with rounding according to the context settings. 2129 * 2130 * <p>The effect of this method is identical to that of the {@link 2131 * #round(MathContext)} method. 2132 * 2133 * @param mc the context to use. 2134 * @return {@code this}, rounded as necessary. A zero result will 2135 * have a scale of 0. 2136 * @throws ArithmeticException if the result is inexact but the 2137 * rounding mode is {@code UNNECESSARY}. 2138 * @see #round(MathContext) 2139 * @since 1.5 2140 */ 2141 public BigDecimal plus(MathContext mc) { 2142 if (mc.precision == 0) // no rounding please 2143 return this; 2144 return doRound(this, mc); 2145 } 2146 2147 /** 2148 * Returns the signum function of this {@code BigDecimal}. 2149 * 2150 * @return -1, 0, or 1 as the value of this {@code BigDecimal} 2151 * is negative, zero, or positive. 2152 */ 2153 public int signum() { 2154 return (intCompact != INFLATED)? 2155 Long.signum(intCompact): 2156 intVal.signum(); 2157 } 2158 2159 /** 2160 * Returns the <i>scale</i> of this {@code BigDecimal}. If zero 2161 * or positive, the scale is the number of digits to the right of 2162 * the decimal point. If negative, the unscaled value of the 2163 * number is multiplied by ten to the power of the negation of the 2164 * scale. For example, a scale of {@code -3} means the unscaled 2165 * value is multiplied by 1000. 2166 * 2167 * @return the scale of this {@code BigDecimal}. 2168 */ 2169 public int scale() { 2170 return scale; 2171 } 2172 2173 /** 2174 * Returns the <i>precision</i> of this {@code BigDecimal}. (The 2175 * precision is the number of digits in the unscaled value.) 2176 * 2177 * <p>The precision of a zero value is 1. 2178 * 2179 * @return the precision of this {@code BigDecimal}. 2180 * @since 1.5 2181 */ 2182 public int precision() { 2183 int result = precision; 2184 if (result == 0) { 2185 long s = intCompact; 2186 if (s != INFLATED) 2187 result = longDigitLength(s); 2188 else 2189 result = bigDigitLength(inflate()); 2190 precision = result; 2191 } 2192 return result; 2193 } 2194 2195 2196 /** 2197 * Returns a {@code BigInteger} whose value is the <i>unscaled 2198 * value</i> of this {@code BigDecimal}. (Computes <tt>(this * 2199 * 10<sup>this.scale()</sup>)</tt>.) 2200 * 2201 * @return the unscaled value of this {@code BigDecimal}. 2202 * @since 1.2 2203 */ 2204 public BigInteger unscaledValue() { 2205 return this.inflate(); 2206 } 2207 2208 // Rounding Modes 2209 2210 /** 2211 * Rounding mode to round away from zero. Always increments the 2212 * digit prior to a nonzero discarded fraction. Note that this rounding 2213 * mode never decreases the magnitude of the calculated value. 2214 */ 2215 public final static int ROUND_UP = 0; 2216 2217 /** 2218 * Rounding mode to round towards zero. Never increments the digit 2219 * prior to a discarded fraction (i.e., truncates). Note that this 2220 * rounding mode never increases the magnitude of the calculated value. 2221 */ 2222 public final static int ROUND_DOWN = 1; 2223 2224 /** 2225 * Rounding mode to round towards positive infinity. If the 2226 * {@code BigDecimal} is positive, behaves as for 2227 * {@code ROUND_UP}; if negative, behaves as for 2228 * {@code ROUND_DOWN}. Note that this rounding mode never 2229 * decreases the calculated value. 2230 */ 2231 public final static int ROUND_CEILING = 2; 2232 2233 /** 2234 * Rounding mode to round towards negative infinity. If the 2235 * {@code BigDecimal} is positive, behave as for 2236 * {@code ROUND_DOWN}; if negative, behave as for 2237 * {@code ROUND_UP}. Note that this rounding mode never 2238 * increases the calculated value. 2239 */ 2240 public final static int ROUND_FLOOR = 3; 2241 2242 /** 2243 * Rounding mode to round towards {@literal "nearest neighbor"} 2244 * unless both neighbors are equidistant, in which case round up. 2245 * Behaves as for {@code ROUND_UP} if the discarded fraction is 2246 * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note 2247 * that this is the rounding mode that most of us were taught in 2248 * grade school. 2249 */ 2250 public final static int ROUND_HALF_UP = 4; 2251 2252 /** 2253 * Rounding mode to round towards {@literal "nearest neighbor"} 2254 * unless both neighbors are equidistant, in which case round 2255 * down. Behaves as for {@code ROUND_UP} if the discarded 2256 * fraction is {@literal >} 0.5; otherwise, behaves as for 2257 * {@code ROUND_DOWN}. 2258 */ 2259 public final static int ROUND_HALF_DOWN = 5; 2260 2261 /** 2262 * Rounding mode to round towards the {@literal "nearest neighbor"} 2263 * unless both neighbors are equidistant, in which case, round 2264 * towards the even neighbor. Behaves as for 2265 * {@code ROUND_HALF_UP} if the digit to the left of the 2266 * discarded fraction is odd; behaves as for 2267 * {@code ROUND_HALF_DOWN} if it's even. Note that this is the 2268 * rounding mode that minimizes cumulative error when applied 2269 * repeatedly over a sequence of calculations. 2270 */ 2271 public final static int ROUND_HALF_EVEN = 6; 2272 2273 /** 2274 * Rounding mode to assert that the requested operation has an exact 2275 * result, hence no rounding is necessary. If this rounding mode is 2276 * specified on an operation that yields an inexact result, an 2277 * {@code ArithmeticException} is thrown. 2278 */ 2279 public final static int ROUND_UNNECESSARY = 7; 2280 2281 2282 // Scaling/Rounding Operations 2283 2284 /** 2285 * Returns a {@code BigDecimal} rounded according to the 2286 * {@code MathContext} settings. If the precision setting is 0 then 2287 * no rounding takes place. 2288 * 2289 * <p>The effect of this method is identical to that of the 2290 * {@link #plus(MathContext)} method. 2291 * 2292 * @param mc the context to use. 2293 * @return a {@code BigDecimal} rounded according to the 2294 * {@code MathContext} settings. 2295 * @throws ArithmeticException if the rounding mode is 2296 * {@code UNNECESSARY} and the 2297 * {@code BigDecimal} operation would require rounding. 2298 * @see #plus(MathContext) 2299 * @since 1.5 2300 */ 2301 public BigDecimal round(MathContext mc) { 2302 return plus(mc); 2303 } 2304 2305 /** 2306 * Returns a {@code BigDecimal} whose scale is the specified 2307 * value, and whose unscaled value is determined by multiplying or 2308 * dividing this {@code BigDecimal}'s unscaled value by the 2309 * appropriate power of ten to maintain its overall value. If the 2310 * scale is reduced by the operation, the unscaled value must be 2311 * divided (rather than multiplied), and the value may be changed; 2312 * in this case, the specified rounding mode is applied to the 2313 * division. 2314 * 2315 * <p>Note that since BigDecimal objects are immutable, calls of 2316 * this method do <i>not</i> result in the original object being 2317 * modified, contrary to the usual convention of having methods 2318 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 2319 * Instead, {@code setScale} returns an object with the proper 2320 * scale; the returned object may or may not be newly allocated. 2321 * 2322 * @param newScale scale of the {@code BigDecimal} value to be returned. 2323 * @param roundingMode The rounding mode to apply. 2324 * @return a {@code BigDecimal} whose scale is the specified value, 2325 * and whose unscaled value is determined by multiplying or 2326 * dividing this {@code BigDecimal}'s unscaled value by the 2327 * appropriate power of ten to maintain its overall value. 2328 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} 2329 * and the specified scaling operation would require 2330 * rounding. 2331 * @see RoundingMode 2332 * @since 1.5 2333 */ 2334 public BigDecimal setScale(int newScale, RoundingMode roundingMode) { 2335 return setScale(newScale, roundingMode.oldMode); 2336 } 2337 2338 /** 2339 * Returns a {@code BigDecimal} whose scale is the specified 2340 * value, and whose unscaled value is determined by multiplying or 2341 * dividing this {@code BigDecimal}'s unscaled value by the 2342 * appropriate power of ten to maintain its overall value. If the 2343 * scale is reduced by the operation, the unscaled value must be 2344 * divided (rather than multiplied), and the value may be changed; 2345 * in this case, the specified rounding mode is applied to the 2346 * division. 2347 * 2348 * <p>Note that since BigDecimal objects are immutable, calls of 2349 * this method do <i>not</i> result in the original object being 2350 * modified, contrary to the usual convention of having methods 2351 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 2352 * Instead, {@code setScale} returns an object with the proper 2353 * scale; the returned object may or may not be newly allocated. 2354 * 2355 * <p>The new {@link #setScale(int, RoundingMode)} method should 2356 * be used in preference to this legacy method. 2357 * 2358 * @param newScale scale of the {@code BigDecimal} value to be returned. 2359 * @param roundingMode The rounding mode to apply. 2360 * @return a {@code BigDecimal} whose scale is the specified value, 2361 * and whose unscaled value is determined by multiplying or 2362 * dividing this {@code BigDecimal}'s unscaled value by the 2363 * appropriate power of ten to maintain its overall value. 2364 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} 2365 * and the specified scaling operation would require 2366 * rounding. 2367 * @throws IllegalArgumentException if {@code roundingMode} does not 2368 * represent a valid rounding mode. 2369 * @see #ROUND_UP 2370 * @see #ROUND_DOWN 2371 * @see #ROUND_CEILING 2372 * @see #ROUND_FLOOR 2373 * @see #ROUND_HALF_UP 2374 * @see #ROUND_HALF_DOWN 2375 * @see #ROUND_HALF_EVEN 2376 * @see #ROUND_UNNECESSARY 2377 */ 2378 public BigDecimal setScale(int newScale, int roundingMode) { 2379 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 2380 throw new IllegalArgumentException("Invalid rounding mode"); 2381 2382 int oldScale = this.scale; 2383 if (newScale == oldScale) // easy case 2384 return this; 2385 if (this.signum() == 0) // zero can have any scale 2386 return BigDecimal.valueOf(0, newScale); 2387 2388 long rs = this.intCompact; 2389 if (newScale > oldScale) { 2390 int raise = checkScale((long)newScale - oldScale); 2391 BigInteger rb = null; 2392 if (rs == INFLATED || 2393 (rs = longMultiplyPowerTen(rs, raise)) == INFLATED) 2394 rb = bigMultiplyPowerTen(raise); 2395 return new BigDecimal(rb, rs, newScale, 2396 (precision > 0) ? precision + raise : 0); 2397 } else { 2398 // newScale < oldScale -- drop some digits 2399 // Can't predict the precision due to the effect of rounding. 2400 int drop = checkScale((long)oldScale - newScale); 2401 if (drop < LONG_TEN_POWERS_TABLE.length) 2402 return divideAndRound(rs, this.intVal, 2403 LONG_TEN_POWERS_TABLE[drop], null, 2404 newScale, roundingMode, newScale); 2405 else 2406 return divideAndRound(rs, this.intVal, 2407 INFLATED, bigTenToThe(drop), 2408 newScale, roundingMode, newScale); 2409 } 2410 } 2411 2412 /** 2413 * Returns a {@code BigDecimal} whose scale is the specified 2414 * value, and whose value is numerically equal to this 2415 * {@code BigDecimal}'s. Throws an {@code ArithmeticException} 2416 * if this is not possible. 2417 * 2418 * <p>This call is typically used to increase the scale, in which 2419 * case it is guaranteed that there exists a {@code BigDecimal} 2420 * of the specified scale and the correct value. The call can 2421 * also be used to reduce the scale if the caller knows that the 2422 * {@code BigDecimal} has sufficiently many zeros at the end of 2423 * its fractional part (i.e., factors of ten in its integer value) 2424 * to allow for the rescaling without changing its value. 2425 * 2426 * <p>This method returns the same result as the two-argument 2427 * versions of {@code setScale}, but saves the caller the trouble 2428 * of specifying a rounding mode in cases where it is irrelevant. 2429 * 2430 * <p>Note that since {@code BigDecimal} objects are immutable, 2431 * calls of this method do <i>not</i> result in the original 2432 * object being modified, contrary to the usual convention of 2433 * having methods named <tt>set<i>X</i></tt> mutate field 2434 * <i>{@code X}</i>. Instead, {@code setScale} returns an 2435 * object with the proper scale; the returned object may or may 2436 * not be newly allocated. 2437 * 2438 * @param newScale scale of the {@code BigDecimal} value to be returned. 2439 * @return a {@code BigDecimal} whose scale is the specified value, and 2440 * whose unscaled value is determined by multiplying or dividing 2441 * this {@code BigDecimal}'s unscaled value by the appropriate 2442 * power of ten to maintain its overall value. 2443 * @throws ArithmeticException if the specified scaling operation would 2444 * require rounding. 2445 * @see #setScale(int, int) 2446 * @see #setScale(int, RoundingMode) 2447 */ 2448 public BigDecimal setScale(int newScale) { 2449 return setScale(newScale, ROUND_UNNECESSARY); 2450 } 2451 2452 // Decimal Point Motion Operations 2453 2454 /** 2455 * Returns a {@code BigDecimal} which is equivalent to this one 2456 * with the decimal point moved {@code n} places to the left. If 2457 * {@code n} is non-negative, the call merely adds {@code n} to 2458 * the scale. If {@code n} is negative, the call is equivalent 2459 * to {@code movePointRight(-n)}. The {@code BigDecimal} 2460 * returned by this call has value <tt>(this × 2461 * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, 2462 * 0)}. 2463 * 2464 * @param n number of places to move the decimal point to the left. 2465 * @return a {@code BigDecimal} which is equivalent to this one with the 2466 * decimal point moved {@code n} places to the left. 2467 * @throws ArithmeticException if scale overflows. 2468 */ 2469 public BigDecimal movePointLeft(int n) { 2470 // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE 2471 int newScale = checkScale((long)scale + n); 2472 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2473 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2474 } 2475 2476 /** 2477 * Returns a {@code BigDecimal} which is equivalent to this one 2478 * with the decimal point moved {@code n} places to the right. 2479 * If {@code n} is non-negative, the call merely subtracts 2480 * {@code n} from the scale. If {@code n} is negative, the call 2481 * is equivalent to {@code movePointLeft(-n)}. The 2482 * {@code BigDecimal} returned by this call has value <tt>(this 2483 * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n, 2484 * 0)}. 2485 * 2486 * @param n number of places to move the decimal point to the right. 2487 * @return a {@code BigDecimal} which is equivalent to this one 2488 * with the decimal point moved {@code n} places to the right. 2489 * @throws ArithmeticException if scale overflows. 2490 */ 2491 public BigDecimal movePointRight(int n) { 2492 // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE 2493 int newScale = checkScale((long)scale - n); 2494 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2495 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2496 } 2497 2498 /** 2499 * Returns a BigDecimal whose numerical value is equal to 2500 * ({@code this} * 10<sup>n</sup>). The scale of 2501 * the result is {@code (this.scale() - n)}. 2502 * 2503 * @throws ArithmeticException if the scale would be 2504 * outside the range of a 32-bit integer. 2505 * 2506 * @since 1.5 2507 */ 2508 public BigDecimal scaleByPowerOfTen(int n) { 2509 return new BigDecimal(intVal, intCompact, 2510 checkScale((long)scale - n), precision); 2511 } 2512 2513 /** 2514 * Returns a {@code BigDecimal} which is numerically equal to 2515 * this one but with any trailing zeros removed from the 2516 * representation. For example, stripping the trailing zeros from 2517 * the {@code BigDecimal} value {@code 600.0}, which has 2518 * [{@code BigInteger}, {@code scale}] components equals to 2519 * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, 2520 * {@code scale}] components equals to [6, -2] 2521 * 2522 * @return a numerically equal {@code BigDecimal} with any 2523 * trailing zeros removed. 2524 * @since 1.5 2525 */ 2526 public BigDecimal stripTrailingZeros() { 2527 this.inflate(); 2528 BigDecimal result = new BigDecimal(intVal, scale); 2529 result.stripZerosToMatchScale(Long.MIN_VALUE); 2530 return result; 2531 } 2532 2533 // Comparison Operations 2534 2535 /** 2536 * Compares this {@code BigDecimal} with the specified 2537 * {@code BigDecimal}. Two {@code BigDecimal} objects that are 2538 * equal in value but have a different scale (like 2.0 and 2.00) 2539 * are considered equal by this method. This method is provided 2540 * in preference to individual methods for each of the six boolean 2541 * comparison operators ({@literal <}, ==, 2542 * {@literal >}, {@literal >=}, !=, {@literal <=}). The 2543 * suggested idiom for performing these comparisons is: 2544 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 2545 * <<i>op</i>> is one of the six comparison operators. 2546 * 2547 * @param val {@code BigDecimal} to which this {@code BigDecimal} is 2548 * to be compared. 2549 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically 2550 * less than, equal to, or greater than {@code val}. 2551 */ 2552 public int compareTo(BigDecimal val) { 2553 // Quick path for equal scale and non-inflated case. 2554 if (scale == val.scale) { 2555 long xs = intCompact; 2556 long ys = val.intCompact; 2557 if (xs != INFLATED && ys != INFLATED) 2558 return xs != ys ? ((xs > ys) ? 1 : -1) : 0; 2559 } 2560 int xsign = this.signum(); 2561 int ysign = val.signum(); 2562 if (xsign != ysign) 2563 return (xsign > ysign) ? 1 : -1; 2564 if (xsign == 0) 2565 return 0; 2566 int cmp = compareMagnitude(val); 2567 return (xsign > 0) ? cmp : -cmp; 2568 } 2569 2570 /** 2571 * Version of compareTo that ignores sign. 2572 */ 2573 private int compareMagnitude(BigDecimal val) { 2574 // Match scales, avoid unnecessary inflation 2575 long ys = val.intCompact; 2576 long xs = this.intCompact; 2577 if (xs == 0) 2578 return (ys == 0) ? 0 : -1; 2579 if (ys == 0) 2580 return 1; 2581 2582 int sdiff = this.scale - val.scale; 2583 if (sdiff != 0) { 2584 // Avoid matching scales if the (adjusted) exponents differ 2585 int xae = this.precision() - this.scale; // [-1] 2586 int yae = val.precision() - val.scale; // [-1] 2587 if (xae < yae) 2588 return -1; 2589 if (xae > yae) 2590 return 1; 2591 BigInteger rb = null; 2592 if (sdiff < 0) { 2593 if ( (xs == INFLATED || 2594 (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) && 2595 ys == INFLATED) { 2596 rb = bigMultiplyPowerTen(-sdiff); 2597 return rb.compareMagnitude(val.intVal); 2598 } 2599 } else { // sdiff > 0 2600 if ( (ys == INFLATED || 2601 (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) && 2602 xs == INFLATED) { 2603 rb = val.bigMultiplyPowerTen(sdiff); 2604 return this.intVal.compareMagnitude(rb); 2605 } 2606 } 2607 } 2608 if (xs != INFLATED) 2609 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; 2610 else if (ys != INFLATED) 2611 return 1; 2612 else 2613 return this.intVal.compareMagnitude(val.intVal); 2614 } 2615 2616 /** 2617 * Compares this {@code BigDecimal} with the specified 2618 * {@code Object} for equality. Unlike {@link 2619 * #compareTo(BigDecimal) compareTo}, this method considers two 2620 * {@code BigDecimal} objects equal only if they are equal in 2621 * value and scale (thus 2.0 is not equal to 2.00 when compared by 2622 * this method). 2623 * 2624 * @param x {@code Object} to which this {@code BigDecimal} is 2625 * to be compared. 2626 * @return {@code true} if and only if the specified {@code Object} is a 2627 * {@code BigDecimal} whose value and scale are equal to this 2628 * {@code BigDecimal}'s. 2629 * @see #compareTo(java.math.BigDecimal) 2630 * @see #hashCode 2631 */ 2632 @Override 2633 public boolean equals(Object x) { 2634 if (!(x instanceof BigDecimal)) 2635 return false; 2636 BigDecimal xDec = (BigDecimal) x; 2637 if (x == this) 2638 return true; 2639 if (scale != xDec.scale) 2640 return false; 2641 long s = this.intCompact; 2642 long xs = xDec.intCompact; 2643 if (s != INFLATED) { 2644 if (xs == INFLATED) 2645 xs = compactValFor(xDec.intVal); 2646 return xs == s; 2647 } else if (xs != INFLATED) 2648 return xs == compactValFor(this.intVal); 2649 2650 return this.inflate().equals(xDec.inflate()); 2651 } 2652 2653 /** 2654 * Returns the minimum of this {@code BigDecimal} and 2655 * {@code val}. 2656 * 2657 * @param val value with which the minimum is to be computed. 2658 * @return the {@code BigDecimal} whose value is the lesser of this 2659 * {@code BigDecimal} and {@code val}. If they are equal, 2660 * as defined by the {@link #compareTo(BigDecimal) compareTo} 2661 * method, {@code this} is returned. 2662 * @see #compareTo(java.math.BigDecimal) 2663 */ 2664 public BigDecimal min(BigDecimal val) { 2665 return (compareTo(val) <= 0 ? this : val); 2666 } 2667 2668 /** 2669 * Returns the maximum of this {@code BigDecimal} and {@code val}. 2670 * 2671 * @param val value with which the maximum is to be computed. 2672 * @return the {@code BigDecimal} whose value is the greater of this 2673 * {@code BigDecimal} and {@code val}. If they are equal, 2674 * as defined by the {@link #compareTo(BigDecimal) compareTo} 2675 * method, {@code this} is returned. 2676 * @see #compareTo(java.math.BigDecimal) 2677 */ 2678 public BigDecimal max(BigDecimal val) { 2679 return (compareTo(val) >= 0 ? this : val); 2680 } 2681 2682 // Hash Function 2683 2684 /** 2685 * Returns the hash code for this {@code BigDecimal}. Note that 2686 * two {@code BigDecimal} objects that are numerically equal but 2687 * differ in scale (like 2.0 and 2.00) will generally <i>not</i> 2688 * have the same hash code. 2689 * 2690 * @return hash code for this {@code BigDecimal}. 2691 * @see #equals(Object) 2692 */ 2693 @Override 2694 public int hashCode() { 2695 if (intCompact != INFLATED) { 2696 long val2 = (intCompact < 0)? -intCompact : intCompact; 2697 int temp = (int)( ((int)(val2 >>> 32)) * 31 + 2698 (val2 & LONG_MASK)); 2699 return 31*((intCompact < 0) ?-temp:temp) + scale; 2700 } else 2701 return 31*intVal.hashCode() + scale; 2702 } 2703 2704 // Format Converters 2705 2706 /** 2707 * Returns the string representation of this {@code BigDecimal}, 2708 * using scientific notation if an exponent is needed. 2709 * 2710 * <p>A standard canonical string form of the {@code BigDecimal} 2711 * is created as though by the following steps: first, the 2712 * absolute value of the unscaled value of the {@code BigDecimal} 2713 * is converted to a string in base ten using the characters 2714 * {@code '0'} through {@code '9'} with no leading zeros (except 2715 * if its value is zero, in which case a single {@code '0'} 2716 * character is used). 2717 * 2718 * <p>Next, an <i>adjusted exponent</i> is calculated; this is the 2719 * negated scale, plus the number of characters in the converted 2720 * unscaled value, less one. That is, 2721 * {@code -scale+(ulength-1)}, where {@code ulength} is the 2722 * length of the absolute value of the unscaled value in decimal 2723 * digits (its <i>precision</i>). 2724 * 2725 * <p>If the scale is greater than or equal to zero and the 2726 * adjusted exponent is greater than or equal to {@code -6}, the 2727 * number will be converted to a character form without using 2728 * exponential notation. In this case, if the scale is zero then 2729 * no decimal point is added and if the scale is positive a 2730 * decimal point will be inserted with the scale specifying the 2731 * number of characters to the right of the decimal point. 2732 * {@code '0'} characters are added to the left of the converted 2733 * unscaled value as necessary. If no character precedes the 2734 * decimal point after this insertion then a conventional 2735 * {@code '0'} character is prefixed. 2736 * 2737 * <p>Otherwise (that is, if the scale is negative, or the 2738 * adjusted exponent is less than {@code -6}), the number will be 2739 * converted to a character form using exponential notation. In 2740 * this case, if the converted {@code BigInteger} has more than 2741 * one digit a decimal point is inserted after the first digit. 2742 * An exponent in character form is then suffixed to the converted 2743 * unscaled value (perhaps with inserted decimal point); this 2744 * comprises the letter {@code 'E'} followed immediately by the 2745 * adjusted exponent converted to a character form. The latter is 2746 * in base ten, using the characters {@code '0'} through 2747 * {@code '9'} with no leading zeros, and is always prefixed by a 2748 * sign character {@code '-'} (<tt>'\u002D'</tt>) if the 2749 * adjusted exponent is negative, {@code '+'} 2750 * (<tt>'\u002B'</tt>) otherwise). 2751 * 2752 * <p>Finally, the entire string is prefixed by a minus sign 2753 * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled 2754 * value is less than zero. No sign character is prefixed if the 2755 * unscaled value is zero or positive. 2756 * 2757 * <p><b>Examples:</b> 2758 * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] 2759 * on the left, the resulting string is shown on the right. 2760 * <pre> 2761 * [123,0] "123" 2762 * [-123,0] "-123" 2763 * [123,-1] "1.23E+3" 2764 * [123,-3] "1.23E+5" 2765 * [123,1] "12.3" 2766 * [123,5] "0.00123" 2767 * [123,10] "1.23E-8" 2768 * [-123,12] "-1.23E-10" 2769 * </pre> 2770 * 2771 * <b>Notes:</b> 2772 * <ol> 2773 * 2774 * <li>There is a one-to-one mapping between the distinguishable 2775 * {@code BigDecimal} values and the result of this conversion. 2776 * That is, every distinguishable {@code BigDecimal} value 2777 * (unscaled value and scale) has a unique string representation 2778 * as a result of using {@code toString}. If that string 2779 * representation is converted back to a {@code BigDecimal} using 2780 * the {@link #BigDecimal(String)} constructor, then the original 2781 * value will be recovered. 2782 * 2783 * <li>The string produced for a given number is always the same; 2784 * it is not affected by locale. This means that it can be used 2785 * as a canonical string representation for exchanging decimal 2786 * data, or as a key for a Hashtable, etc. Locale-sensitive 2787 * number formatting and parsing is handled by the {@link 2788 * java.text.NumberFormat} class and its subclasses. 2789 * 2790 * <li>The {@link #toEngineeringString} method may be used for 2791 * presenting numbers with exponents in engineering notation, and the 2792 * {@link #setScale(int,RoundingMode) setScale} method may be used for 2793 * rounding a {@code BigDecimal} so it has a known number of digits after 2794 * the decimal point. 2795 * 2796 * <li>The digit-to-character mapping provided by 2797 * {@code Character.forDigit} is used. 2798 * 2799 * </ol> 2800 * 2801 * @return string representation of this {@code BigDecimal}. 2802 * @see Character#forDigit 2803 * @see #BigDecimal(java.lang.String) 2804 */ 2805 @Override 2806 public String toString() { 2807 String sc = stringCache; 2808 if (sc == null) 2809 stringCache = sc = layoutChars(true); 2810 return sc; 2811 } 2812 2813 /** 2814 * Returns a string representation of this {@code BigDecimal}, 2815 * using engineering notation if an exponent is needed. 2816 * 2817 * <p>Returns a string that represents the {@code BigDecimal} as 2818 * described in the {@link #toString()} method, except that if 2819 * exponential notation is used, the power of ten is adjusted to 2820 * be a multiple of three (engineering notation) such that the 2821 * integer part of nonzero values will be in the range 1 through 2822 * 999. If exponential notation is used for zero values, a 2823 * decimal point and one or two fractional zero digits are used so 2824 * that the scale of the zero value is preserved. Note that 2825 * unlike the output of {@link #toString()}, the output of this 2826 * method is <em>not</em> guaranteed to recover the same [integer, 2827 * scale] pair of this {@code BigDecimal} if the output string is 2828 * converting back to a {@code BigDecimal} using the {@linkplain 2829 * #BigDecimal(String) string constructor}. The result of this method meets 2830 * the weaker constraint of always producing a numerically equal 2831 * result from applying the string constructor to the method's output. 2832 * 2833 * @return string representation of this {@code BigDecimal}, using 2834 * engineering notation if an exponent is needed. 2835 * @since 1.5 2836 */ 2837 public String toEngineeringString() { 2838 return layoutChars(false); 2839 } 2840 2841 /** 2842 * Returns a string representation of this {@code BigDecimal} 2843 * without an exponent field. For values with a positive scale, 2844 * the number of digits to the right of the decimal point is used 2845 * to indicate scale. For values with a zero or negative scale, 2846 * the resulting string is generated as if the value were 2847 * converted to a numerically equal value with zero scale and as 2848 * if all the trailing zeros of the zero scale value were present 2849 * in the result. 2850 * 2851 * The entire string is prefixed by a minus sign character '-' 2852 * (<tt>'\u002D'</tt>) if the unscaled value is less than 2853 * zero. No sign character is prefixed if the unscaled value is 2854 * zero or positive. 2855 * 2856 * Note that if the result of this method is passed to the 2857 * {@linkplain #BigDecimal(String) string constructor}, only the 2858 * numerical value of this {@code BigDecimal} will necessarily be 2859 * recovered; the representation of the new {@code BigDecimal} 2860 * may have a different scale. In particular, if this 2861 * {@code BigDecimal} has a negative scale, the string resulting 2862 * from this method will have a scale of zero when processed by 2863 * the string constructor. 2864 * 2865 * (This method behaves analogously to the {@code toString} 2866 * method in 1.4 and earlier releases.) 2867 * 2868 * @return a string representation of this {@code BigDecimal} 2869 * without an exponent field. 2870 * @since 1.5 2871 * @see #toString() 2872 * @see #toEngineeringString() 2873 */ 2874 public String toPlainString() { 2875 BigDecimal bd = this; 2876 if (bd.scale < 0) 2877 bd = bd.setScale(0); 2878 bd.inflate(); 2879 if (bd.scale == 0) // No decimal point 2880 return bd.intVal.toString(); 2881 return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale); 2882 } 2883 2884 /* Returns a digit.digit string */ 2885 private String getValueString(int signum, String intString, int scale) { 2886 /* Insert decimal point */ 2887 StringBuilder buf; 2888 int insertionPoint = intString.length() - scale; 2889 if (insertionPoint == 0) { /* Point goes right before intVal */ 2890 return (signum<0 ? "-0." : "0.") + intString; 2891 } else if (insertionPoint > 0) { /* Point goes inside intVal */ 2892 buf = new StringBuilder(intString); 2893 buf.insert(insertionPoint, '.'); 2894 if (signum < 0) 2895 buf.insert(0, '-'); 2896 } else { /* We must insert zeros between point and intVal */ 2897 buf = new StringBuilder(3-insertionPoint + intString.length()); 2898 buf.append(signum<0 ? "-0." : "0."); 2899 for (int i=0; i<-insertionPoint; i++) 2900 buf.append('0'); 2901 buf.append(intString); 2902 } 2903 return buf.toString(); 2904 } 2905 2906 /** 2907 * Converts this {@code BigDecimal} to a {@code BigInteger}. 2908 * This conversion is analogous to a <a 2909 * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing 2910 * primitive conversion</i></a> from {@code double} to 2911 * {@code long} as defined in the <a 2912 * href="http://java.sun.com/docs/books/jls/html/">Java Language 2913 * Specification</a>: any fractional part of this 2914 * {@code BigDecimal} will be discarded. Note that this 2915 * conversion can lose information about the precision of the 2916 * {@code BigDecimal} value. 2917 * <p> 2918 * To have an exception thrown if the conversion is inexact (in 2919 * other words if a nonzero fractional part is discarded), use the 2920 * {@link #toBigIntegerExact()} method. 2921 * 2922 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 2923 */ 2924 public BigInteger toBigInteger() { 2925 // force to an integer, quietly 2926 return this.setScale(0, ROUND_DOWN).inflate(); 2927 } 2928 2929 /** 2930 * Converts this {@code BigDecimal} to a {@code BigInteger}, 2931 * checking for lost information. An exception is thrown if this 2932 * {@code BigDecimal} has a nonzero fractional part. 2933 * 2934 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 2935 * @throws ArithmeticException if {@code this} has a nonzero 2936 * fractional part. 2937 * @since 1.5 2938 */ 2939 public BigInteger toBigIntegerExact() { 2940 // round to an integer, with Exception if decimal part non-0 2941 return this.setScale(0, ROUND_UNNECESSARY).inflate(); 2942 } 2943 2944 /** 2945 * Converts this {@code BigDecimal} to a {@code long}. This 2946 * conversion is analogous to a <a 2947 * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing 2948 * primitive conversion</i></a> from {@code double} to 2949 * {@code short} as defined in the <a 2950 * href="http://java.sun.com/docs/books/jls/html/">Java Language 2951 * Specification</a>: any fractional part of this 2952 * {@code BigDecimal} will be discarded, and if the resulting 2953 * "{@code BigInteger}" is too big to fit in a 2954 * {@code long}, only the low-order 64 bits are returned. 2955 * Note that this conversion can lose information about the 2956 * overall magnitude and precision of this {@code BigDecimal} value as well 2957 * as return a result with the opposite sign. 2958 * 2959 * @return this {@code BigDecimal} converted to a {@code long}. 2960 */ 2961 public long longValue(){ 2962 return (intCompact != INFLATED && scale == 0) ? 2963 intCompact: 2964 toBigInteger().longValue(); 2965 } 2966 2967 /** 2968 * Converts this {@code BigDecimal} to a {@code long}, checking 2969 * for lost information. If this {@code BigDecimal} has a 2970 * nonzero fractional part or is out of the possible range for a 2971 * {@code long} result then an {@code ArithmeticException} is 2972 * thrown. 2973 * 2974 * @return this {@code BigDecimal} converted to a {@code long}. 2975 * @throws ArithmeticException if {@code this} has a nonzero 2976 * fractional part, or will not fit in a {@code long}. 2977 * @since 1.5 2978 */ 2979 public long longValueExact() { 2980 if (intCompact != INFLATED && scale == 0) 2981 return intCompact; 2982 // If more than 19 digits in integer part it cannot possibly fit 2983 if ((precision() - scale) > 19) // [OK for negative scale too] 2984 throw new java.lang.ArithmeticException("Overflow"); 2985 // Fastpath zero and < 1.0 numbers (the latter can be very slow 2986 // to round if very small) 2987 if (this.signum() == 0) 2988 return 0; 2989 if ((this.precision() - this.scale) <= 0) 2990 throw new ArithmeticException("Rounding necessary"); 2991 // round to an integer, with Exception if decimal part non-0 2992 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); 2993 if (num.precision() >= 19) // need to check carefully 2994 LongOverflow.check(num); 2995 return num.inflate().longValue(); 2996 } 2997 2998 private static class LongOverflow { 2999 /** BigInteger equal to Long.MIN_VALUE. */ 3000 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE); 3001 3002 /** BigInteger equal to Long.MAX_VALUE. */ 3003 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE); 3004 3005 public static void check(BigDecimal num) { 3006 num.inflate(); 3007 if ((num.intVal.compareTo(LONGMIN) < 0) || 3008 (num.intVal.compareTo(LONGMAX) > 0)) 3009 throw new java.lang.ArithmeticException("Overflow"); 3010 } 3011 } 3012 3013 /** 3014 * Converts this {@code BigDecimal} to an {@code int}. This 3015 * conversion is analogous to a <a 3016 * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing 3017 * primitive conversion</i></a> from {@code double} to 3018 * {@code short} as defined in the <a 3019 * href="http://java.sun.com/docs/books/jls/html/">Java Language 3020 * Specification</a>: any fractional part of this 3021 * {@code BigDecimal} will be discarded, and if the resulting 3022 * "{@code BigInteger}" is too big to fit in an 3023 * {@code int}, only the low-order 32 bits are returned. 3024 * Note that this conversion can lose information about the 3025 * overall magnitude and precision of this {@code BigDecimal} 3026 * value as well as return a result with the opposite sign. 3027 * 3028 * @return this {@code BigDecimal} converted to an {@code int}. 3029 */ 3030 public int intValue() { 3031 return (intCompact != INFLATED && scale == 0) ? 3032 (int)intCompact : 3033 toBigInteger().intValue(); 3034 } 3035 3036 /** 3037 * Converts this {@code BigDecimal} to an {@code int}, checking 3038 * for lost information. If this {@code BigDecimal} has a 3039 * nonzero fractional part or is out of the possible range for an 3040 * {@code int} result then an {@code ArithmeticException} is 3041 * thrown. 3042 * 3043 * @return this {@code BigDecimal} converted to an {@code int}. 3044 * @throws ArithmeticException if {@code this} has a nonzero 3045 * fractional part, or will not fit in an {@code int}. 3046 * @since 1.5 3047 */ 3048 public int intValueExact() { 3049 long num; 3050 num = this.longValueExact(); // will check decimal part 3051 if ((int)num != num) 3052 throw new java.lang.ArithmeticException("Overflow"); 3053 return (int)num; 3054 } 3055 3056 /** 3057 * Converts this {@code BigDecimal} to a {@code short}, checking 3058 * for lost information. If this {@code BigDecimal} has a 3059 * nonzero fractional part or is out of the possible range for a 3060 * {@code short} result then an {@code ArithmeticException} is 3061 * thrown. 3062 * 3063 * @return this {@code BigDecimal} converted to a {@code short}. 3064 * @throws ArithmeticException if {@code this} has a nonzero 3065 * fractional part, or will not fit in a {@code short}. 3066 * @since 1.5 3067 */ 3068 public short shortValueExact() { 3069 long num; 3070 num = this.longValueExact(); // will check decimal part 3071 if ((short)num != num) 3072 throw new java.lang.ArithmeticException("Overflow"); 3073 return (short)num; 3074 } 3075 3076 /** 3077 * Converts this {@code BigDecimal} to a {@code byte}, checking 3078 * for lost information. If this {@code BigDecimal} has a 3079 * nonzero fractional part or is out of the possible range for a 3080 * {@code byte} result then an {@code ArithmeticException} is 3081 * thrown. 3082 * 3083 * @return this {@code BigDecimal} converted to a {@code byte}. 3084 * @throws ArithmeticException if {@code this} has a nonzero 3085 * fractional part, or will not fit in a {@code byte}. 3086 * @since 1.5 3087 */ 3088 public byte byteValueExact() { 3089 long num; 3090 num = this.longValueExact(); // will check decimal part 3091 if ((byte)num != num) 3092 throw new java.lang.ArithmeticException("Overflow"); 3093 return (byte)num; 3094 } 3095 3096 /** 3097 * Converts this {@code BigDecimal} to a {@code float}. 3098 * This conversion is similar to the <a 3099 * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing 3100 * primitive conversion</i></a> from {@code double} to 3101 * {@code float} defined in the <a 3102 * href="http://java.sun.com/docs/books/jls/html/">Java Language 3103 * Specification</a>: if this {@code BigDecimal} has too great a 3104 * magnitude to represent as a {@code float}, it will be 3105 * converted to {@link Float#NEGATIVE_INFINITY} or {@link 3106 * Float#POSITIVE_INFINITY} as appropriate. Note that even when 3107 * the return value is finite, this conversion can lose 3108 * information about the precision of the {@code BigDecimal} 3109 * value. 3110 * 3111 * @return this {@code BigDecimal} converted to a {@code float}. 3112 */ 3113 public float floatValue(){ 3114 if (scale == 0 && intCompact != INFLATED) 3115 return (float)intCompact; 3116 // Somewhat inefficient, but guaranteed to work. 3117 return Float.parseFloat(this.toString()); 3118 } 3119 3120 /** 3121 * Converts this {@code BigDecimal} to a {@code double}. 3122 * This conversion is similar to the <a 3123 * href="http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363"><i>narrowing 3124 * primitive conversion</i></a> from {@code double} to 3125 * {@code float} as defined in the <a 3126 * href="http://java.sun.com/docs/books/jls/html/">Java Language 3127 * Specification</a>: if this {@code BigDecimal} has too great a 3128 * magnitude represent as a {@code double}, it will be 3129 * converted to {@link Double#NEGATIVE_INFINITY} or {@link 3130 * Double#POSITIVE_INFINITY} as appropriate. Note that even when 3131 * the return value is finite, this conversion can lose 3132 * information about the precision of the {@code BigDecimal} 3133 * value. 3134 * 3135 * @return this {@code BigDecimal} converted to a {@code double}. 3136 */ 3137 public double doubleValue(){ 3138 if (scale == 0 && intCompact != INFLATED) 3139 return (double)intCompact; 3140 // Somewhat inefficient, but guaranteed to work. 3141 return Double.parseDouble(this.toString()); 3142 } 3143 3144 /** 3145 * Returns the size of an ulp, a unit in the last place, of this 3146 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} 3147 * value is the positive distance between this value and the 3148 * {@code BigDecimal} value next larger in magnitude with the 3149 * same number of digits. An ulp of a zero value is numerically 3150 * equal to 1 with the scale of {@code this}. The result is 3151 * stored with the same scale as {@code this} so the result 3152 * for zero and nonzero values is equal to {@code [1, 3153 * this.scale()]}. 3154 * 3155 * @return the size of an ulp of {@code this} 3156 * @since 1.5 3157 */ 3158 public BigDecimal ulp() { 3159 return BigDecimal.valueOf(1, this.scale()); 3160 } 3161 3162 3163 // Private class to build a string representation for BigDecimal object. 3164 // "StringBuilderHelper" is constructed as a thread local variable so it is 3165 // thread safe. The StringBuilder field acts as a buffer to hold the temporary 3166 // representation of BigDecimal. The cmpCharArray holds all the characters for 3167 // the compact representation of BigDecimal (except for '-' sign' if it is 3168 // negative) if its intCompact field is not INFLATED. It is shared by all 3169 // calls to toString() and its variants in that particular thread. 3170 static class StringBuilderHelper { 3171 final StringBuilder sb; // Placeholder for BigDecimal string 3172 final char[] cmpCharArray; // character array to place the intCompact 3173 3174 StringBuilderHelper() { 3175 sb = new StringBuilder(); 3176 // All non negative longs can be made to fit into 19 character array. 3177 cmpCharArray = new char[19]; 3178 } 3179 3180 // Accessors. 3181 StringBuilder getStringBuilder() { 3182 sb.setLength(0); 3183 return sb; 3184 } 3185 3186 char[] getCompactCharArray() { 3187 return cmpCharArray; 3188 } 3189 3190 /** 3191 * Places characters representing the intCompact in {@code long} into 3192 * cmpCharArray and returns the offset to the array where the 3193 * representation starts. 3194 * 3195 * @param intCompact the number to put into the cmpCharArray. 3196 * @return offset to the array where the representation starts. 3197 * Note: intCompact must be greater or equal to zero. 3198 */ 3199 int putIntCompact(long intCompact) { 3200 assert intCompact >= 0; 3201 3202 long q; 3203 int r; 3204 // since we start from the least significant digit, charPos points to 3205 // the last character in cmpCharArray. 3206 int charPos = cmpCharArray.length; 3207 3208 // Get 2 digits/iteration using longs until quotient fits into an int 3209 while (intCompact > Integer.MAX_VALUE) { 3210 q = intCompact / 100; 3211 r = (int)(intCompact - q * 100); 3212 intCompact = q; 3213 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3214 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3215 } 3216 3217 // Get 2 digits/iteration using ints when i2 >= 100 3218 int q2; 3219 int i2 = (int)intCompact; 3220 while (i2 >= 100) { 3221 q2 = i2 / 100; 3222 r = i2 - q2 * 100; 3223 i2 = q2; 3224 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3225 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3226 } 3227 3228 cmpCharArray[--charPos] = DIGIT_ONES[i2]; 3229 if (i2 >= 10) 3230 cmpCharArray[--charPos] = DIGIT_TENS[i2]; 3231 3232 return charPos; 3233 } 3234 3235 final static char[] DIGIT_TENS = { 3236 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 3237 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 3238 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 3239 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 3240 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 3241 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 3242 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 3243 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 3244 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 3245 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 3246 }; 3247 3248 final static char[] DIGIT_ONES = { 3249 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3250 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3251 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3252 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3253 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3254 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3255 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3256 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3257 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3258 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3259 }; 3260 } 3261 3262 /** 3263 * Lay out this {@code BigDecimal} into a {@code char[]} array. 3264 * The Java 1.2 equivalent to this was called {@code getValueString}. 3265 * 3266 * @param sci {@code true} for Scientific exponential notation; 3267 * {@code false} for Engineering 3268 * @return string with canonical string representation of this 3269 * {@code BigDecimal} 3270 */ 3271 private String layoutChars(boolean sci) { 3272 if (scale == 0) // zero scale is trivial 3273 return (intCompact != INFLATED) ? 3274 Long.toString(intCompact): 3275 intVal.toString(); 3276 3277 StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get(); 3278 char[] coeff; 3279 int offset; // offset is the starting index for coeff array 3280 // Get the significand as an absolute value 3281 if (intCompact != INFLATED) { 3282 offset = sbHelper.putIntCompact(Math.abs(intCompact)); 3283 coeff = sbHelper.getCompactCharArray(); 3284 } else { 3285 offset = 0; 3286 coeff = intVal.abs().toString().toCharArray(); 3287 } 3288 3289 // Construct a buffer, with sufficient capacity for all cases. 3290 // If E-notation is needed, length will be: +1 if negative, +1 3291 // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. 3292 // Otherwise it could have +1 if negative, plus leading "0.00000" 3293 StringBuilder buf = sbHelper.getStringBuilder(); 3294 if (signum() < 0) // prefix '-' if negative 3295 buf.append('-'); 3296 int coeffLen = coeff.length - offset; 3297 long adjusted = -(long)scale + (coeffLen -1); 3298 if ((scale >= 0) && (adjusted >= -6)) { // plain number 3299 int pad = scale - coeffLen; // count of padding zeros 3300 if (pad >= 0) { // 0.xxx form 3301 buf.append('0'); 3302 buf.append('.'); 3303 for (; pad>0; pad--) { 3304 buf.append('0'); 3305 } 3306 buf.append(coeff, offset, coeffLen); 3307 } else { // xx.xx form 3308 buf.append(coeff, offset, -pad); 3309 buf.append('.'); 3310 buf.append(coeff, -pad + offset, scale); 3311 } 3312 } else { // E-notation is needed 3313 if (sci) { // Scientific notation 3314 buf.append(coeff[offset]); // first character 3315 if (coeffLen > 1) { // more to come 3316 buf.append('.'); 3317 buf.append(coeff, offset + 1, coeffLen - 1); 3318 } 3319 } else { // Engineering notation 3320 int sig = (int)(adjusted % 3); 3321 if (sig < 0) 3322 sig += 3; // [adjusted was negative] 3323 adjusted -= sig; // now a multiple of 3 3324 sig++; 3325 if (signum() == 0) { 3326 switch (sig) { 3327 case 1: 3328 buf.append('0'); // exponent is a multiple of three 3329 break; 3330 case 2: 3331 buf.append("0.00"); 3332 adjusted += 3; 3333 break; 3334 case 3: 3335 buf.append("0.0"); 3336 adjusted += 3; 3337 break; 3338 default: 3339 throw new AssertionError("Unexpected sig value " + sig); 3340 } 3341 } else if (sig >= coeffLen) { // significand all in integer 3342 buf.append(coeff, offset, coeffLen); 3343 // may need some zeros, too 3344 for (int i = sig - coeffLen; i > 0; i--) 3345 buf.append('0'); 3346 } else { // xx.xxE form 3347 buf.append(coeff, offset, sig); 3348 buf.append('.'); 3349 buf.append(coeff, offset + sig, coeffLen - sig); 3350 } 3351 } 3352 if (adjusted != 0) { // [!sci could have made 0] 3353 buf.append('E'); 3354 if (adjusted > 0) // force sign for positive 3355 buf.append('+'); 3356 buf.append(adjusted); 3357 } 3358 } 3359 return buf.toString(); 3360 } 3361 3362 /** 3363 * Return 10 to the power n, as a {@code BigInteger}. 3364 * 3365 * @param n the power of ten to be returned (>=0) 3366 * @return a {@code BigInteger} with the value (10<sup>n</sup>) 3367 */ 3368 private static BigInteger bigTenToThe(int n) { 3369 if (n < 0) 3370 return BigInteger.ZERO; 3371 3372 if (n < BIG_TEN_POWERS_TABLE_MAX) { 3373 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3374 if (n < pows.length) 3375 return pows[n]; 3376 else 3377 return expandBigIntegerTenPowers(n); 3378 } 3379 // BigInteger.pow is slow, so make 10**n by constructing a 3380 // BigInteger from a character string (still not very fast) 3381 char tenpow[] = new char[n + 1]; 3382 tenpow[0] = '1'; 3383 for (int i = 1; i <= n; i++) 3384 tenpow[i] = '0'; 3385 return new BigInteger(tenpow); 3386 } 3387 3388 /** 3389 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. 3390 * 3391 * @param n the power of ten to be returned (>=0) 3392 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and 3393 * in the meantime, the BIG_TEN_POWERS_TABLE array gets 3394 * expanded to the size greater than n. 3395 */ 3396 private static BigInteger expandBigIntegerTenPowers(int n) { 3397 synchronized(BigDecimal.class) { 3398 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3399 int curLen = pows.length; 3400 // The following comparison and the above synchronized statement is 3401 // to prevent multiple threads from expanding the same array. 3402 if (curLen <= n) { 3403 int newLen = curLen << 1; 3404 while (newLen <= n) 3405 newLen <<= 1; 3406 pows = Arrays.copyOf(pows, newLen); 3407 for (int i = curLen; i < newLen; i++) 3408 pows[i] = pows[i - 1].multiply(BigInteger.TEN); 3409 // Based on the following facts: 3410 // 1. pows is a private local varible; 3411 // 2. the following store is a volatile store. 3412 // the newly created array elements can be safely published. 3413 BIG_TEN_POWERS_TABLE = pows; 3414 } 3415 return pows[n]; 3416 } 3417 } 3418 3419 private static final long[] LONG_TEN_POWERS_TABLE = { 3420 1, // 0 / 10^0 3421 10, // 1 / 10^1 3422 100, // 2 / 10^2 3423 1000, // 3 / 10^3 3424 10000, // 4 / 10^4 3425 100000, // 5 / 10^5 3426 1000000, // 6 / 10^6 3427 10000000, // 7 / 10^7 3428 100000000, // 8 / 10^8 3429 1000000000, // 9 / 10^9 3430 10000000000L, // 10 / 10^10 3431 100000000000L, // 11 / 10^11 3432 1000000000000L, // 12 / 10^12 3433 10000000000000L, // 13 / 10^13 3434 100000000000000L, // 14 / 10^14 3435 1000000000000000L, // 15 / 10^15 3436 10000000000000000L, // 16 / 10^16 3437 100000000000000000L, // 17 / 10^17 3438 1000000000000000000L // 18 / 10^18 3439 }; 3440 3441 private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = {BigInteger.ONE, 3442 BigInteger.valueOf(10), BigInteger.valueOf(100), 3443 BigInteger.valueOf(1000), BigInteger.valueOf(10000), 3444 BigInteger.valueOf(100000), BigInteger.valueOf(1000000), 3445 BigInteger.valueOf(10000000), BigInteger.valueOf(100000000), 3446 BigInteger.valueOf(1000000000), 3447 BigInteger.valueOf(10000000000L), 3448 BigInteger.valueOf(100000000000L), 3449 BigInteger.valueOf(1000000000000L), 3450 BigInteger.valueOf(10000000000000L), 3451 BigInteger.valueOf(100000000000000L), 3452 BigInteger.valueOf(1000000000000000L), 3453 BigInteger.valueOf(10000000000000000L), 3454 BigInteger.valueOf(100000000000000000L), 3455 BigInteger.valueOf(1000000000000000000L) 3456 }; 3457 3458 private static final int BIG_TEN_POWERS_TABLE_INITLEN = 3459 BIG_TEN_POWERS_TABLE.length; 3460 private static final int BIG_TEN_POWERS_TABLE_MAX = 3461 16 * BIG_TEN_POWERS_TABLE_INITLEN; 3462 3463 private static final long THRESHOLDS_TABLE[] = { 3464 Long.MAX_VALUE, // 0 3465 Long.MAX_VALUE/10L, // 1 3466 Long.MAX_VALUE/100L, // 2 3467 Long.MAX_VALUE/1000L, // 3 3468 Long.MAX_VALUE/10000L, // 4 3469 Long.MAX_VALUE/100000L, // 5 3470 Long.MAX_VALUE/1000000L, // 6 3471 Long.MAX_VALUE/10000000L, // 7 3472 Long.MAX_VALUE/100000000L, // 8 3473 Long.MAX_VALUE/1000000000L, // 9 3474 Long.MAX_VALUE/10000000000L, // 10 3475 Long.MAX_VALUE/100000000000L, // 11 3476 Long.MAX_VALUE/1000000000000L, // 12 3477 Long.MAX_VALUE/10000000000000L, // 13 3478 Long.MAX_VALUE/100000000000000L, // 14 3479 Long.MAX_VALUE/1000000000000000L, // 15 3480 Long.MAX_VALUE/10000000000000000L, // 16 3481 Long.MAX_VALUE/100000000000000000L, // 17 3482 Long.MAX_VALUE/1000000000000000000L // 18 3483 }; 3484 3485 /** 3486 * Compute val * 10 ^ n; return this product if it is 3487 * representable as a long, INFLATED otherwise. 3488 */ 3489 private static long longMultiplyPowerTen(long val, int n) { 3490 if (val == 0 || n <= 0) 3491 return val; 3492 long[] tab = LONG_TEN_POWERS_TABLE; 3493 long[] bounds = THRESHOLDS_TABLE; 3494 if (n < tab.length && n < bounds.length) { 3495 long tenpower = tab[n]; 3496 if (val == 1) 3497 return tenpower; 3498 if (Math.abs(val) <= bounds[n]) 3499 return val * tenpower; 3500 } 3501 return INFLATED; 3502 } 3503 3504 /** 3505 * Compute this * 10 ^ n. 3506 * Needed mainly to allow special casing to trap zero value 3507 */ 3508 private BigInteger bigMultiplyPowerTen(int n) { 3509 if (n <= 0) 3510 return this.inflate(); 3511 3512 if (intCompact != INFLATED) 3513 return bigTenToThe(n).multiply(intCompact); 3514 else 3515 return intVal.multiply(bigTenToThe(n)); 3516 } 3517 3518 /** 3519 * Assign appropriate BigInteger to intVal field if intVal is 3520 * null, i.e. the compact representation is in use. 3521 */ 3522 private BigInteger inflate() { 3523 if (intVal == null) 3524 intVal = BigInteger.valueOf(intCompact); 3525 return intVal; 3526 } 3527 3528 /** 3529 * Match the scales of two {@code BigDecimal}s to align their 3530 * least significant digits. 3531 * 3532 * <p>If the scales of val[0] and val[1] differ, rescale 3533 * (non-destructively) the lower-scaled {@code BigDecimal} so 3534 * they match. That is, the lower-scaled reference will be 3535 * replaced by a reference to a new object with the same scale as 3536 * the other {@code BigDecimal}. 3537 * 3538 * @param val array of two elements referring to the two 3539 * {@code BigDecimal}s to be aligned. 3540 */ 3541 private static void matchScale(BigDecimal[] val) { 3542 if (val[0].scale == val[1].scale) { 3543 return; 3544 } else if (val[0].scale < val[1].scale) { 3545 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY); 3546 } else if (val[1].scale < val[0].scale) { 3547 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY); 3548 } 3549 } 3550 3551 /** 3552 * Reconstitute the {@code BigDecimal} instance from a stream (that is, 3553 * deserialize it). 3554 * 3555 * @param s the stream being read. 3556 */ 3557 private void readObject(java.io.ObjectInputStream s) 3558 throws java.io.IOException, ClassNotFoundException { 3559 // Read in all fields 3560 s.defaultReadObject(); 3561 // validate possibly bad fields 3562 if (intVal == null) { 3563 String message = "BigDecimal: null intVal in stream"; 3564 throw new java.io.StreamCorruptedException(message); 3565 // [all values of scale are now allowed] 3566 } 3567 intCompact = compactValFor(intVal); 3568 } 3569 3570 /** 3571 * Serialize this {@code BigDecimal} to the stream in question 3572 * 3573 * @param s the stream to serialize to. 3574 */ 3575 private void writeObject(java.io.ObjectOutputStream s) 3576 throws java.io.IOException { 3577 // Must inflate to maintain compatible serial form. 3578 this.inflate(); 3579 3580 // Write proper fields 3581 s.defaultWriteObject(); 3582 } 3583 3584 3585 /** 3586 * Returns the length of the absolute value of a {@code long}, in decimal 3587 * digits. 3588 * 3589 * @param x the {@code long} 3590 * @return the length of the unscaled value, in deciaml digits. 3591 */ 3592 private static int longDigitLength(long x) { 3593 /* 3594 * As described in "Bit Twiddling Hacks" by Sean Anderson, 3595 * (http://graphics.stanford.edu/~seander/bithacks.html) 3596 * integer log 10 of x is within 1 of 3597 * (1233/4096)* (1 + integer log 2 of x). 3598 * The fraction 1233/4096 approximates log10(2). So we first 3599 * do a version of log2 (a variant of Long class with 3600 * pre-checks and opposite directionality) and then scale and 3601 * check against powers table. This is a little simpler in 3602 * present context than the version in Hacker's Delight sec 3603 * 11-4. Adding one to bit length allows comparing downward 3604 * from the LONG_TEN_POWERS_TABLE that we need anyway. 3605 */ 3606 assert x != INFLATED; 3607 if (x < 0) 3608 x = -x; 3609 if (x < 10) // must screen for 0, might as well 10 3610 return 1; 3611 int n = 64; // not 63, to avoid needing to add 1 later 3612 int y = (int)(x >>> 32); 3613 if (y == 0) { n -= 32; y = (int)x; } 3614 if (y >>> 16 == 0) { n -= 16; y <<= 16; } 3615 if (y >>> 24 == 0) { n -= 8; y <<= 8; } 3616 if (y >>> 28 == 0) { n -= 4; y <<= 4; } 3617 if (y >>> 30 == 0) { n -= 2; y <<= 2; } 3618 int r = (((y >>> 31) + n) * 1233) >>> 12; 3619 long[] tab = LONG_TEN_POWERS_TABLE; 3620 // if r >= length, must have max possible digits for long 3621 return (r >= tab.length || x < tab[r])? r : r+1; 3622 } 3623 3624 /** 3625 * Returns the length of the absolute value of a BigInteger, in 3626 * decimal digits. 3627 * 3628 * @param b the BigInteger 3629 * @return the length of the unscaled value, in decimal digits 3630 */ 3631 private static int bigDigitLength(BigInteger b) { 3632 /* 3633 * Same idea as the long version, but we need a better 3634 * approximation of log10(2). Using 646456993/2^31 3635 * is accurate up to max possible reported bitLength. 3636 */ 3637 if (b.signum == 0) 3638 return 1; 3639 int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31); 3640 return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1; 3641 } 3642 3643 3644 /** 3645 * Remove insignificant trailing zeros from this 3646 * {@code BigDecimal} until the preferred scale is reached or no 3647 * more zeros can be removed. If the preferred scale is less than 3648 * Integer.MIN_VALUE, all the trailing zeros will be removed. 3649 * 3650 * {@code BigInteger} assistance could help, here? 3651 * 3652 * <p>WARNING: This method should only be called on new objects as 3653 * it mutates the value fields. 3654 * 3655 * @return this {@code BigDecimal} with a scale possibly reduced 3656 * to be closed to the preferred scale. 3657 */ 3658 private BigDecimal stripZerosToMatchScale(long preferredScale) { 3659 this.inflate(); 3660 BigInteger qr[]; // quotient-remainder pair 3661 while ( intVal.compareMagnitude(BigInteger.TEN) >= 0 && 3662 scale > preferredScale) { 3663 if (intVal.testBit(0)) 3664 break; // odd number cannot end in 0 3665 qr = intVal.divideAndRemainder(BigInteger.TEN); 3666 if (qr[1].signum() != 0) 3667 break; // non-0 remainder 3668 intVal=qr[0]; 3669 scale = checkScale((long)scale-1); // could Overflow 3670 if (precision > 0) // adjust precision if known 3671 precision--; 3672 } 3673 if (intVal != null) 3674 intCompact = compactValFor(intVal); 3675 return this; 3676 } 3677 3678 /** 3679 * Check a scale for Underflow or Overflow. If this BigDecimal is 3680 * nonzero, throw an exception if the scale is outof range. If this 3681 * is zero, saturate the scale to the extreme value of the right 3682 * sign if the scale is out of range. 3683 * 3684 * @param val The new scale. 3685 * @throws ArithmeticException (overflow or underflow) if the new 3686 * scale is out of range. 3687 * @return validated scale as an int. 3688 */ 3689 private int checkScale(long val) { 3690 int asInt = (int)val; 3691 if (asInt != val) { 3692 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 3693 BigInteger b; 3694 if (intCompact != 0 && 3695 ((b = intVal) == null || b.signum() != 0)) 3696 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 3697 } 3698 return asInt; 3699 } 3700 3701 /** 3702 * Round an operand; used only if digits > 0. Does not change 3703 * {@code this}; if rounding is needed a new {@code BigDecimal} 3704 * is created and returned. 3705 * 3706 * @param mc the context to use. 3707 * @throws ArithmeticException if the result is inexact but the 3708 * rounding mode is {@code UNNECESSARY}. 3709 */ 3710 private BigDecimal roundOp(MathContext mc) { 3711 BigDecimal rounded = doRound(this, mc); 3712 return rounded; 3713 } 3714 3715 /** Round this BigDecimal according to the MathContext settings; 3716 * used only if precision {@literal >} 0. 3717 * 3718 * <p>WARNING: This method should only be called on new objects as 3719 * it mutates the value fields. 3720 * 3721 * @param mc the context to use. 3722 * @throws ArithmeticException if the rounding mode is 3723 * {@code RoundingMode.UNNECESSARY} and the 3724 * {@code BigDecimal} operation would require rounding. 3725 */ 3726 private void roundThis(MathContext mc) { 3727 BigDecimal rounded = doRound(this, mc); 3728 if (rounded == this) // wasn't rounded 3729 return; 3730 this.intVal = rounded.intVal; 3731 this.intCompact = rounded.intCompact; 3732 this.scale = rounded.scale; 3733 this.precision = rounded.precision; 3734 } 3735 3736 /** 3737 * Returns a {@code BigDecimal} rounded according to the 3738 * MathContext settings; used only if {@code mc.precision > 0}. 3739 * Does not change {@code this}; if rounding is needed a new 3740 * {@code BigDecimal} is created and returned. 3741 * 3742 * @param mc the context to use. 3743 * @return a {@code BigDecimal} rounded according to the MathContext 3744 * settings. May return this, if no rounding needed. 3745 * @throws ArithmeticException if the rounding mode is 3746 * {@code RoundingMode.UNNECESSARY} and the 3747 * result is inexact. 3748 */ 3749 private static BigDecimal doRound(BigDecimal d, MathContext mc) { 3750 int mcp = mc.precision; 3751 int drop; 3752 // This might (rarely) iterate to cover the 999=>1000 case 3753 while ((drop = d.precision() - mcp) > 0) { 3754 int newScale = d.checkScale((long)d.scale - drop); 3755 int mode = mc.roundingMode.oldMode; 3756 if (drop < LONG_TEN_POWERS_TABLE.length) 3757 d = divideAndRound(d.intCompact, d.intVal, 3758 LONG_TEN_POWERS_TABLE[drop], null, 3759 newScale, mode, newScale); 3760 else 3761 d = divideAndRound(d.intCompact, d.intVal, 3762 INFLATED, bigTenToThe(drop), 3763 newScale, mode, newScale); 3764 } 3765 return d; 3766 } 3767 3768 /** 3769 * Returns the compact value for given {@code BigInteger}, or 3770 * INFLATED if too big. Relies on internal representation of 3771 * {@code BigInteger}. 3772 */ 3773 private static long compactValFor(BigInteger b) { 3774 int[] m = b.mag; 3775 int len = m.length; 3776 if (len == 0) 3777 return 0; 3778 int d = m[0]; 3779 if (len > 2 || (len == 2 && d < 0)) 3780 return INFLATED; 3781 3782 long u = (len == 2)? 3783 (((long) m[1] & LONG_MASK) + (((long)d) << 32)) : 3784 (((long)d) & LONG_MASK); 3785 return (b.signum < 0)? -u : u; 3786 } 3787 3788 private static int longCompareMagnitude(long x, long y) { 3789 if (x < 0) 3790 x = -x; 3791 if (y < 0) 3792 y = -y; 3793 return (x < y) ? -1 : ((x == y) ? 0 : 1); 3794 } 3795 3796 private static int saturateLong(long s) { 3797 int i = (int)s; 3798 return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); 3799 } 3800 3801 /* 3802 * Internal printing routine 3803 */ 3804 private static void print(String name, BigDecimal bd) { 3805 System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n", 3806 name, 3807 bd.intCompact, 3808 bd.intVal, 3809 bd.scale, 3810 bd.precision); 3811 } 3812 3813 /** 3814 * Check internal invariants of this BigDecimal. These invariants 3815 * include: 3816 * 3817 * <ul> 3818 * 3819 * <li>The object must be initialized; either intCompact must not be 3820 * INFLATED or intVal is non-null. Both of these conditions may 3821 * be true. 3822 * 3823 * <li>If both intCompact and intVal and set, their values must be 3824 * consistent. 3825 * 3826 * <li>If precision is nonzero, it must have the right value. 3827 * </ul> 3828 * 3829 * Note: Since this is an audit method, we are not supposed to change the 3830 * state of this BigDecimal object. 3831 */ 3832 private BigDecimal audit() { 3833 if (intCompact == INFLATED) { 3834 if (intVal == null) { 3835 print("audit", this); 3836 throw new AssertionError("null intVal"); 3837 } 3838 // Check precision 3839 if (precision > 0 && precision != bigDigitLength(intVal)) { 3840 print("audit", this); 3841 throw new AssertionError("precision mismatch"); 3842 } 3843 } else { 3844 if (intVal != null) { 3845 long val = intVal.longValue(); 3846 if (val != intCompact) { 3847 print("audit", this); 3848 throw new AssertionError("Inconsistent state, intCompact=" + 3849 intCompact + "\t intVal=" + val); 3850 } 3851 } 3852 // Check precision 3853 if (precision > 0 && precision != longDigitLength(intCompact)) { 3854 print("audit", this); 3855 throw new AssertionError("precision mismatch"); 3856 } 3857 } 3858 return this; 3859 } 3860 }