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><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 final BigInteger intVal; 228 229 /** 230 * The scale of this BigDecimal, as returned by {@link #scale}. 231 * 232 * @serial 233 * @see #scale 234 */ 235 private final int scale; // Note: this may have any value, so 236 // calculations must be done in longs 237 238 /** 239 * The number of decimal digits in this BigDecimal, or 0 if the 240 * number of digits are not known (lookaside information). If 241 * nonzero, the value is guaranteed correct. Use the precision() 242 * method to obtain and set the value if it might be 0. This 243 * field is mutable until set nonzero. 244 * 245 * @since 1.5 246 */ 247 private transient int precision; 248 249 /** 250 * Used to store the canonical string representation, if computed. 251 */ 252 private transient String stringCache; 253 254 /** 255 * Sentinel value for {@link #intCompact} indicating the 256 * significand information is only available from {@code intVal}. 257 */ 258 static final long INFLATED = Long.MIN_VALUE; 259 260 private static final BigInteger INFLATED_BIGINT = BigInteger.valueOf(INFLATED); 261 262 /** 263 * If the absolute value of the significand of this BigDecimal is 264 * less than or equal to {@code Long.MAX_VALUE}, the value can be 265 * compactly stored in this field and used in computations. 266 */ 267 private final transient long intCompact; 268 269 // All 18-digit base ten strings fit into a long; not all 19-digit 270 // strings will 271 private static final int MAX_COMPACT_DIGITS = 18; 272 273 /* Appease the serialization gods */ 274 private static final long serialVersionUID = 6108874887143696463L; 275 276 private static final ThreadLocal<StringBuilderHelper> 277 threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() { 278 @Override 279 protected StringBuilderHelper initialValue() { 280 return new StringBuilderHelper(); 281 } 282 }; 283 284 // Cache of common small BigDecimal values. 285 private static final BigDecimal zeroThroughTen[] = { 286 new BigDecimal(BigInteger.ZERO, 0, 0, 1), 287 new BigDecimal(BigInteger.ONE, 1, 0, 1), 288 new BigDecimal(BigInteger.valueOf(2), 2, 0, 1), 289 new BigDecimal(BigInteger.valueOf(3), 3, 0, 1), 290 new BigDecimal(BigInteger.valueOf(4), 4, 0, 1), 291 new BigDecimal(BigInteger.valueOf(5), 5, 0, 1), 292 new BigDecimal(BigInteger.valueOf(6), 6, 0, 1), 293 new BigDecimal(BigInteger.valueOf(7), 7, 0, 1), 294 new BigDecimal(BigInteger.valueOf(8), 8, 0, 1), 295 new BigDecimal(BigInteger.valueOf(9), 9, 0, 1), 296 new BigDecimal(BigInteger.TEN, 10, 0, 2), 297 }; 298 299 // Cache of zero scaled by 0 - 15 300 private static final BigDecimal[] ZERO_SCALED_BY = { 301 zeroThroughTen[0], 302 new BigDecimal(BigInteger.ZERO, 0, 1, 1), 303 new BigDecimal(BigInteger.ZERO, 0, 2, 1), 304 new BigDecimal(BigInteger.ZERO, 0, 3, 1), 305 new BigDecimal(BigInteger.ZERO, 0, 4, 1), 306 new BigDecimal(BigInteger.ZERO, 0, 5, 1), 307 new BigDecimal(BigInteger.ZERO, 0, 6, 1), 308 new BigDecimal(BigInteger.ZERO, 0, 7, 1), 309 new BigDecimal(BigInteger.ZERO, 0, 8, 1), 310 new BigDecimal(BigInteger.ZERO, 0, 9, 1), 311 new BigDecimal(BigInteger.ZERO, 0, 10, 1), 312 new BigDecimal(BigInteger.ZERO, 0, 11, 1), 313 new BigDecimal(BigInteger.ZERO, 0, 12, 1), 314 new BigDecimal(BigInteger.ZERO, 0, 13, 1), 315 new BigDecimal(BigInteger.ZERO, 0, 14, 1), 316 new BigDecimal(BigInteger.ZERO, 0, 15, 1), 317 }; 318 319 // Half of Long.MIN_VALUE & Long.MAX_VALUE. 320 private static final long HALF_LONG_MAX_VALUE = Long.MAX_VALUE / 2; 321 private static final long HALF_LONG_MIN_VALUE = Long.MIN_VALUE / 2; 322 323 // Constants 324 /** 325 * The value 0, with a scale of 0. 326 * 327 * @since 1.5 328 */ 329 public static final BigDecimal ZERO = 330 zeroThroughTen[0]; 331 332 /** 333 * The value 1, with a scale of 0. 334 * 335 * @since 1.5 336 */ 337 public static final BigDecimal ONE = 338 zeroThroughTen[1]; 339 340 /** 341 * The value 10, with a scale of 0. 342 * 343 * @since 1.5 344 */ 345 public static final BigDecimal TEN = 346 zeroThroughTen[10]; 347 348 // Constructors 349 350 /** 351 * Trusted package private constructor. 352 * Trusted simply means if val is INFLATED, intVal could not be null and 353 * if intVal is null, val could not be INFLATED. 354 */ 355 BigDecimal(BigInteger intVal, long val, int scale, int prec) { 356 this.scale = scale; 357 this.precision = prec; 358 this.intCompact = val; 359 this.intVal = intVal; 360 } 361 362 /** 363 * Translates a character array representation of a 364 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 365 * same sequence of characters as the {@link #BigDecimal(String)} 366 * constructor, while allowing a sub-array to be specified. 367 * 368 * <p>Note that if the sequence of characters is already available 369 * within a character array, using this constructor is faster than 370 * converting the {@code char} array to string and using the 371 * {@code BigDecimal(String)} constructor . 372 * 373 * @param in {@code char} array that is the source of characters. 374 * @param offset first character in the array to inspect. 375 * @param len number of characters to consider. 376 * @throws NumberFormatException if {@code in} is not a valid 377 * representation of a {@code BigDecimal} or the defined subarray 378 * is not wholly within {@code in}. 379 * @since 1.5 380 */ 381 public BigDecimal(char[] in, int offset, int len) { 382 this(in,offset,len,MathContext.UNLIMITED); 383 } 384 385 /** 386 * Translates a character array representation of a 387 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 388 * same sequence of characters as the {@link #BigDecimal(String)} 389 * constructor, while allowing a sub-array to be specified and 390 * with rounding according to the context settings. 391 * 392 * <p>Note that if the sequence of characters is already available 393 * within a character array, using this constructor is faster than 394 * converting the {@code char} array to string and using the 395 * {@code BigDecimal(String)} constructor . 396 * 397 * @param in {@code char} array that is the source of characters. 398 * @param offset first character in the array to inspect. 399 * @param len number of characters to consider.. 400 * @param mc the context to use. 401 * @throws ArithmeticException if the result is inexact but the 402 * rounding mode is {@code UNNECESSARY}. 403 * @throws NumberFormatException if {@code in} is not a valid 404 * representation of a {@code BigDecimal} or the defined subarray 405 * is not wholly within {@code in}. 406 * @since 1.5 407 */ 408 public BigDecimal(char[] in, int offset, int len, MathContext mc) { 409 // protect against huge length. 410 if (offset + len > in.length || offset < 0) 411 throw new NumberFormatException(); 412 // This is the primary string to BigDecimal constructor; all 413 // incoming strings end up here; it uses explicit (inline) 414 // parsing for speed and generates at most one intermediate 415 // (temporary) object (a char[] array) for non-compact case. 416 417 // Use locals for all fields values until completion 418 int prec = 0; // record precision value 419 int scl = 0; // record scale value 420 long rs = 0; // the compact value in long 421 BigInteger rb = null; // the inflated value in BigInteger 422 // use array bounds checking to handle too-long, len == 0, 423 // bad offset, etc. 424 try { 425 // handle the sign 426 boolean isneg = false; // assume positive 427 if (in[offset] == '-') { 428 isneg = true; // leading minus means negative 429 offset++; 430 len--; 431 } else if (in[offset] == '+') { // leading + allowed 432 offset++; 433 len--; 434 } 435 436 // should now be at numeric part of the significand 437 // int cfirst = offset; // record start of integer 438 long exp = 0; // exponent 439 char c; // current character 440 boolean dot = false; // true when there is a '.' 441 boolean isCompact = (len <= MAX_COMPACT_DIGITS); 442 // integer significand array & idx is the index to it. The array 443 // is ONLY used when we can't use a compact representation. 444 int idx = 0; 445 if (isCompact) { 446 // First compact case, we need not to preserve the character 447 // and we can just compute the value in place. 448 for (; len > 0; offset++, len--) { 449 c = in[offset]; 450 if ((c == '0')) { // have zero 451 if (prec == 0) 452 prec = 1; 453 else if (rs != 0) { 454 rs *= 10; 455 ++prec; 456 } // else digit is a redundant leading zero 457 if (dot) 458 ++scl; 459 } else if ((c >= '1' && c <= '9')) { // have digit 460 int digit = c - '0'; 461 if (prec != 1 || rs != 0) 462 ++prec; // prec unchanged if preceded by 0s 463 rs = rs * 10 + digit; 464 if (dot) 465 ++scl; 466 } else if (c == '.') { // have dot 467 // have dot 468 if (dot) // two dots 469 throw new NumberFormatException(); 470 dot = true; 471 } else if (Character.isDigit(c)) { // slow path 472 int digit = Character.digit(c, 10); 473 if (digit == 0) { 474 if (prec == 0) 475 prec = 1; 476 else if (rs != 0) { 477 rs *= 10; 478 ++prec; 479 } // else digit is a redundant leading zero 480 } else { 481 if (prec != 1 || rs != 0) 482 ++prec; // prec unchanged if preceded by 0s 483 rs = rs * 10 + digit; 484 } 485 if (dot) 486 ++scl; 487 } else if ((c == 'e') || (c == 'E')) { 488 exp = parseExp(in, offset, len); 489 // Next test is required for backwards compatibility 490 if ((int) exp != exp) // overflow 491 throw new NumberFormatException(); 492 break; // [saves a test] 493 } else { 494 throw new NumberFormatException(); 495 } 496 } 497 if (prec == 0) // no digits found 498 throw new NumberFormatException(); 499 // Adjust scale if exp is not zero. 500 if (exp != 0) { // had significant exponent 501 scl = adjustScale(scl, exp); 502 } 503 rs = isneg ? -rs : rs; 504 int mcp = mc.precision; 505 int drop; 506 if (mcp > 0 && (drop = prec - mcp) > 0) { // do rounding 507 while (drop > 0) { 508 scl = checkScaleNonZero((long) scl - drop); 509 rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 510 prec = longDigitLength(rs); 511 drop = prec - mcp; 512 } 513 } 514 } else { 515 char coeff[] = new char[len]; 516 for (; len > 0; offset++, len--) { 517 c = in[offset]; 518 // have digit 519 if ((c >= '0' && c <= '9') || Character.isDigit(c)) { 520 // First compact case, we need not to preserve the character 521 // and we can just compute the value in place. 522 if (c == '0' || Character.digit(c, 10) == 0) { 523 if (prec == 0) { 524 coeff[idx] = c; 525 prec = 1; 526 } else if (idx != 0) { 527 coeff[idx++] = c; 528 ++prec; 529 } // else c must be a redundant leading zero 530 } else { 531 if (prec != 1 || idx != 0) 532 ++prec; // prec unchanged if preceded by 0s 533 coeff[idx++] = c; 534 } 535 if (dot) 536 ++scl; 537 continue; 538 } 539 // have dot 540 if (c == '.') { 541 // have dot 542 if (dot) // two dots 543 throw new NumberFormatException(); 544 dot = true; 545 continue; 546 } 547 // exponent expected 548 if ((c != 'e') && (c != 'E')) 549 throw new NumberFormatException(); 550 exp = parseExp(in, offset, len); 551 // Next test is required for backwards compatibility 552 if ((int) exp != exp) // overflow 553 throw new NumberFormatException(); 554 break; // [saves a test] 555 } 556 // here when no characters left 557 if (prec == 0) // no digits found 558 throw new NumberFormatException(); 559 // Adjust scale if exp is not zero. 560 if (exp != 0) { // had significant exponent 561 scl = adjustScale(scl, exp); 562 } 563 // Remove leading zeros from precision (digits count) 564 rb = new BigInteger(coeff, isneg ? -1 : 1, prec); 565 rs = compactValFor(rb); 566 int mcp = mc.precision; 567 if (mcp > 0 && (prec > mcp)) { 568 if (rs == INFLATED) { 569 int drop = prec - mcp; 570 while (drop > 0) { 571 scl = checkScaleNonZero((long) scl - drop); 572 rb = divideAndRoundByTenPow(rb, drop, mc.roundingMode.oldMode); 573 rs = compactValFor(rb); 574 if (rs != INFLATED) { 575 prec = longDigitLength(rs); 576 break; 577 } 578 prec = bigDigitLength(rb); 579 drop = prec - mcp; 580 } 581 } 582 if (rs != INFLATED) { 583 int drop = prec - mcp; 584 while (drop > 0) { 585 scl = checkScaleNonZero((long) scl - drop); 586 rs = divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 587 prec = longDigitLength(rs); 588 drop = prec - mcp; 589 } 590 rb = null; 591 } 592 } 593 } 594 } catch (ArrayIndexOutOfBoundsException e) { 595 throw new NumberFormatException(); 596 } catch (NegativeArraySizeException e) { 597 throw new NumberFormatException(); 598 } 599 this.scale = scl; 600 this.precision = prec; 601 this.intCompact = rs; 602 this.intVal = rb; 603 } 604 605 private int adjustScale(int scl, long exp) { 606 long adjustedScale = scl - exp; 607 if (adjustedScale > Integer.MAX_VALUE || adjustedScale < Integer.MIN_VALUE) 608 throw new NumberFormatException("Scale out of range."); 609 scl = (int) adjustedScale; 610 return scl; 611 } 612 613 /* 614 * parse exponent 615 */ 616 private static long parseExp(char[] in, int offset, int len){ 617 long exp = 0; 618 offset++; 619 char c = in[offset]; 620 len--; 621 boolean negexp = (c == '-'); 622 // optional sign 623 if (negexp || c == '+') { 624 offset++; 625 c = in[offset]; 626 len--; 627 } 628 if (len <= 0) // no exponent digits 629 throw new NumberFormatException(); 630 // skip leading zeros in the exponent 631 while (len > 10 && (c=='0' || (Character.digit(c, 10) == 0))) { 632 offset++; 633 c = in[offset]; 634 len--; 635 } 636 if (len > 10) // too many nonzero exponent digits 637 throw new NumberFormatException(); 638 // c now holds first digit of exponent 639 for (;; len--) { 640 int v; 641 if (c >= '0' && c <= '9') { 642 v = c - '0'; 643 } else { 644 v = Character.digit(c, 10); 645 if (v < 0) // not a digit 646 throw new NumberFormatException(); 647 } 648 exp = exp * 10 + v; 649 if (len == 1) 650 break; // that was final character 651 offset++; 652 c = in[offset]; 653 } 654 if (negexp) // apply sign 655 exp = -exp; 656 return exp; 657 } 658 659 /** 660 * Translates a character array representation of a 661 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 662 * same sequence of characters as the {@link #BigDecimal(String)} 663 * constructor. 664 * 665 * <p>Note that if the sequence of characters is already available 666 * as a character array, using this constructor is faster than 667 * converting the {@code char} array to string and using the 668 * {@code BigDecimal(String)} constructor . 669 * 670 * @param in {@code char} array that is the source of characters. 671 * @throws NumberFormatException if {@code in} is not a valid 672 * representation of a {@code BigDecimal}. 673 * @since 1.5 674 */ 675 public BigDecimal(char[] in) { 676 this(in, 0, in.length); 677 } 678 679 /** 680 * Translates a character array representation of a 681 * {@code BigDecimal} into a {@code BigDecimal}, accepting the 682 * same sequence of characters as the {@link #BigDecimal(String)} 683 * constructor and with rounding according to the context 684 * settings. 685 * 686 * <p>Note that if the sequence of characters is already available 687 * as a character array, using this constructor is faster than 688 * converting the {@code char} array to string and using the 689 * {@code BigDecimal(String)} constructor . 690 * 691 * @param in {@code char} array that is the source of characters. 692 * @param mc the context to use. 693 * @throws ArithmeticException if the result is inexact but the 694 * rounding mode is {@code UNNECESSARY}. 695 * @throws NumberFormatException if {@code in} is not a valid 696 * representation of a {@code BigDecimal}. 697 * @since 1.5 698 */ 699 public BigDecimal(char[] in, MathContext mc) { 700 this(in, 0, in.length, mc); 701 } 702 703 /** 704 * Translates the string representation of a {@code BigDecimal} 705 * into a {@code BigDecimal}. The string representation consists 706 * of an optional sign, {@code '+'} (<tt> '\u002B'</tt>) or 707 * {@code '-'} (<tt>'\u002D'</tt>), followed by a sequence of 708 * zero or more decimal digits ("the integer"), optionally 709 * followed by a fraction, optionally followed by an exponent. 710 * 711 * <p>The fraction consists of a decimal point followed by zero 712 * or more decimal digits. The string must contain at least one 713 * digit in either the integer or the fraction. The number formed 714 * by the sign, the integer and the fraction is referred to as the 715 * <i>significand</i>. 716 * 717 * <p>The exponent consists of the character {@code 'e'} 718 * (<tt>'\u0065'</tt>) or {@code 'E'} (<tt>'\u0045'</tt>) 719 * followed by one or more decimal digits. The value of the 720 * exponent must lie between -{@link Integer#MAX_VALUE} ({@link 721 * Integer#MIN_VALUE}+1) and {@link Integer#MAX_VALUE}, inclusive. 722 * 723 * <p>More formally, the strings this constructor accepts are 724 * described by the following grammar: 725 * <blockquote> 726 * <dl> 727 * <dt><i>BigDecimalString:</i> 728 * <dd><i>Sign<sub>opt</sub> Significand Exponent<sub>opt</sub></i> 729 * <p> 730 * <dt><i>Sign:</i> 731 * <dd>{@code +} 732 * <dd>{@code -} 733 * <p> 734 * <dt><i>Significand:</i> 735 * <dd><i>IntegerPart</i> {@code .} <i>FractionPart<sub>opt</sub></i> 736 * <dd>{@code .} <i>FractionPart</i> 737 * <dd><i>IntegerPart</i> 738 * <p> 739 * <dt><i>IntegerPart:</i> 740 * <dd><i>Digits</i> 741 * <p> 742 * <dt><i>FractionPart:</i> 743 * <dd><i>Digits</i> 744 * <p> 745 * <dt><i>Exponent:</i> 746 * <dd><i>ExponentIndicator SignedInteger</i> 747 * <p> 748 * <dt><i>ExponentIndicator:</i> 749 * <dd>{@code e} 750 * <dd>{@code E} 751 * <p> 752 * <dt><i>SignedInteger:</i> 753 * <dd><i>Sign<sub>opt</sub> Digits</i> 754 * <p> 755 * <dt><i>Digits:</i> 756 * <dd><i>Digit</i> 757 * <dd><i>Digits Digit</i> 758 * <p> 759 * <dt><i>Digit:</i> 760 * <dd>any character for which {@link Character#isDigit} 761 * returns {@code true}, including 0, 1, 2 ... 762 * </dl> 763 * </blockquote> 764 * 765 * <p>The scale of the returned {@code BigDecimal} will be the 766 * number of digits in the fraction, or zero if the string 767 * contains no decimal point, subject to adjustment for any 768 * exponent; if the string contains an exponent, the exponent is 769 * subtracted from the scale. The value of the resulting scale 770 * must lie between {@code Integer.MIN_VALUE} and 771 * {@code Integer.MAX_VALUE}, inclusive. 772 * 773 * <p>The character-to-digit mapping is provided by {@link 774 * java.lang.Character#digit} set to convert to radix 10. The 775 * String may not contain any extraneous characters (whitespace, 776 * for example). 777 * 778 * <p><b>Examples:</b><br> 779 * The value of the returned {@code BigDecimal} is equal to 780 * <i>significand</i> × 10<sup> <i>exponent</i></sup>. 781 * For each string on the left, the resulting representation 782 * [{@code BigInteger}, {@code scale}] is shown on the right. 783 * <pre> 784 * "0" [0,0] 785 * "0.00" [0,2] 786 * "123" [123,0] 787 * "-123" [-123,0] 788 * "1.23E3" [123,-1] 789 * "1.23E+3" [123,-1] 790 * "12.3E+7" [123,-6] 791 * "12.0" [120,1] 792 * "12.3" [123,1] 793 * "0.00123" [123,5] 794 * "-1.23E-12" [-123,14] 795 * "1234.5E-4" [12345,5] 796 * "0E+7" [0,-7] 797 * "-0" [0,0] 798 * </pre> 799 * 800 * <p>Note: For values other than {@code float} and 801 * {@code double} NaN and ±Infinity, this constructor is 802 * compatible with the values returned by {@link Float#toString} 803 * and {@link Double#toString}. This is generally the preferred 804 * way to convert a {@code float} or {@code double} into a 805 * BigDecimal, as it doesn't suffer from the unpredictability of 806 * the {@link #BigDecimal(double)} constructor. 807 * 808 * @param val String representation of {@code BigDecimal}. 809 * 810 * @throws NumberFormatException if {@code val} is not a valid 811 * representation of a {@code BigDecimal}. 812 */ 813 public BigDecimal(String val) { 814 this(val.toCharArray(), 0, val.length()); 815 } 816 817 /** 818 * Translates the string representation of a {@code BigDecimal} 819 * into a {@code BigDecimal}, accepting the same strings as the 820 * {@link #BigDecimal(String)} constructor, with rounding 821 * according to the context settings. 822 * 823 * @param val string representation of a {@code BigDecimal}. 824 * @param mc the context to use. 825 * @throws ArithmeticException if the result is inexact but the 826 * rounding mode is {@code UNNECESSARY}. 827 * @throws NumberFormatException if {@code val} is not a valid 828 * representation of a BigDecimal. 829 * @since 1.5 830 */ 831 public BigDecimal(String val, MathContext mc) { 832 this(val.toCharArray(), 0, val.length(), mc); 833 } 834 835 /** 836 * Translates a {@code double} into a {@code BigDecimal} which 837 * is the exact decimal representation of the {@code double}'s 838 * binary floating-point value. The scale of the returned 839 * {@code BigDecimal} is the smallest value such that 840 * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 841 * <p> 842 * <b>Notes:</b> 843 * <ol> 844 * <li> 845 * The results of this constructor can be somewhat unpredictable. 846 * One might assume that writing {@code new BigDecimal(0.1)} in 847 * Java creates a {@code BigDecimal} which is exactly equal to 848 * 0.1 (an unscaled value of 1, with a scale of 1), but it is 849 * actually equal to 850 * 0.1000000000000000055511151231257827021181583404541015625. 851 * This is because 0.1 cannot be represented exactly as a 852 * {@code double} (or, for that matter, as a binary fraction of 853 * any finite length). Thus, the value that is being passed 854 * <i>in</i> to the constructor is not exactly equal to 0.1, 855 * appearances notwithstanding. 856 * 857 * <li> 858 * The {@code String} constructor, on the other hand, is 859 * perfectly predictable: writing {@code new BigDecimal("0.1")} 860 * creates a {@code BigDecimal} which is <i>exactly</i> equal to 861 * 0.1, as one would expect. Therefore, it is generally 862 * recommended that the {@linkplain #BigDecimal(String) 863 * <tt>String</tt> constructor} be used in preference to this one. 864 * 865 * <li> 866 * When a {@code double} must be used as a source for a 867 * {@code BigDecimal}, note that this constructor provides an 868 * exact conversion; it does not give the same result as 869 * converting the {@code double} to a {@code String} using the 870 * {@link Double#toString(double)} method and then using the 871 * {@link #BigDecimal(String)} constructor. To get that result, 872 * use the {@code static} {@link #valueOf(double)} method. 873 * </ol> 874 * 875 * @param val {@code double} value to be converted to 876 * {@code BigDecimal}. 877 * @throws NumberFormatException if {@code val} is infinite or NaN. 878 */ 879 public BigDecimal(double val) { 880 this(val,MathContext.UNLIMITED); 881 } 882 883 /** 884 * Translates a {@code double} into a {@code BigDecimal}, with 885 * rounding according to the context settings. The scale of the 886 * {@code BigDecimal} is the smallest value such that 887 * <tt>(10<sup>scale</sup> × val)</tt> is an integer. 888 * 889 * <p>The results of this constructor can be somewhat unpredictable 890 * and its use is generally not recommended; see the notes under 891 * the {@link #BigDecimal(double)} constructor. 892 * 893 * @param val {@code double} 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 * RoundingMode is UNNECESSARY. 898 * @throws NumberFormatException if {@code val} is infinite or NaN. 899 * @since 1.5 900 */ 901 public BigDecimal(double val, MathContext mc) { 902 if (Double.isInfinite(val) || Double.isNaN(val)) 903 throw new NumberFormatException("Infinite or NaN"); 904 // Translate the double into sign, exponent and significand, according 905 // to the formulae in JLS, Section 20.10.22. 906 long valBits = Double.doubleToLongBits(val); 907 int sign = ((valBits >> 63) == 0 ? 1 : -1); 908 int exponent = (int) ((valBits >> 52) & 0x7ffL); 909 long significand = (exponent == 0 910 ? (valBits & ((1L << 52) - 1)) << 1 911 : (valBits & ((1L << 52) - 1)) | (1L << 52)); 912 exponent -= 1075; 913 // At this point, val == sign * significand * 2**exponent. 914 915 /* 916 * Special case zero to supress nonterminating normalization and bogus 917 * scale calculation. 918 */ 919 if (significand == 0) { 920 this.intVal = BigInteger.ZERO; 921 this.scale = 0; 922 this.intCompact = 0; 923 this.precision = 1; 924 return; 925 } 926 // Normalize 927 while ((significand & 1) == 0) { // i.e., significand is even 928 significand >>= 1; 929 exponent++; 930 } 931 int scale = 0; 932 // Calculate intVal and scale 933 BigInteger intVal; 934 long compactVal = sign * significand; 935 if (exponent == 0) { 936 intVal = (compactVal == INFLATED) ? INFLATED_BIGINT : null; 937 } else { 938 if (exponent < 0) { 939 intVal = BigInteger.valueOf(5).pow(-exponent).multiply(compactVal); 940 scale = -exponent; 941 } else { // (exponent > 0) 942 intVal = BigInteger.valueOf(2).pow(exponent).multiply(compactVal); 943 } 944 compactVal = compactValFor(intVal); 945 } 946 int prec = 0; 947 int mcp = mc.precision; 948 if (mcp > 0) { // do rounding 949 int mode = mc.roundingMode.oldMode; 950 int drop; 951 if (compactVal == INFLATED) { 952 prec = bigDigitLength(intVal); 953 drop = prec - mcp; 954 while (drop > 0) { 955 scale = checkScaleNonZero((long) scale - drop); 956 intVal = divideAndRoundByTenPow(intVal, drop, mode); 957 compactVal = compactValFor(intVal); 958 if (compactVal != INFLATED) { 959 break; 960 } 961 prec = bigDigitLength(intVal); 962 drop = prec - mcp; 963 } 964 } 965 if (compactVal != INFLATED) { 966 prec = longDigitLength(compactVal); 967 drop = prec - mcp; 968 while (drop > 0) { 969 scale = checkScaleNonZero((long) scale - drop); 970 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 971 prec = longDigitLength(compactVal); 972 drop = prec - mcp; 973 } 974 intVal = null; 975 } 976 } 977 this.intVal = intVal; 978 this.intCompact = compactVal; 979 this.scale = scale; 980 this.precision = prec; 981 } 982 983 /** 984 * Translates a {@code BigInteger} into a {@code BigDecimal}. 985 * The scale of the {@code BigDecimal} is zero. 986 * 987 * @param val {@code BigInteger} value to be converted to 988 * {@code BigDecimal}. 989 */ 990 public BigDecimal(BigInteger val) { 991 scale = 0; 992 intVal = val; 993 intCompact = compactValFor(val); 994 } 995 996 /** 997 * Translates a {@code BigInteger} into a {@code BigDecimal} 998 * rounding according to the context settings. The scale of the 999 * {@code BigDecimal} is zero. 1000 * 1001 * @param val {@code BigInteger} value to be converted to 1002 * {@code BigDecimal}. 1003 * @param mc the context to use. 1004 * @throws ArithmeticException if the result is inexact but the 1005 * rounding mode is {@code UNNECESSARY}. 1006 * @since 1.5 1007 */ 1008 public BigDecimal(BigInteger val, MathContext mc) { 1009 this(val,0,mc); 1010 } 1011 1012 /** 1013 * Translates a {@code BigInteger} unscaled value and an 1014 * {@code int} scale into a {@code BigDecimal}. The value of 1015 * the {@code BigDecimal} is 1016 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 1017 * 1018 * @param unscaledVal unscaled value of the {@code BigDecimal}. 1019 * @param scale scale of the {@code BigDecimal}. 1020 */ 1021 public BigDecimal(BigInteger unscaledVal, int scale) { 1022 // Negative scales are now allowed 1023 this.intVal = unscaledVal; 1024 this.intCompact = compactValFor(unscaledVal); 1025 this.scale = scale; 1026 } 1027 1028 /** 1029 * Translates a {@code BigInteger} unscaled value and an 1030 * {@code int} scale into a {@code BigDecimal}, with rounding 1031 * according to the context settings. The value of the 1032 * {@code BigDecimal} is <tt>(unscaledVal × 1033 * 10<sup>-scale</sup>)</tt>, rounded according to the 1034 * {@code precision} and rounding mode settings. 1035 * 1036 * @param unscaledVal unscaled value of the {@code BigDecimal}. 1037 * @param scale scale of the {@code BigDecimal}. 1038 * @param mc the context to use. 1039 * @throws ArithmeticException if the result is inexact but the 1040 * rounding mode is {@code UNNECESSARY}. 1041 * @since 1.5 1042 */ 1043 public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) { 1044 long compactVal = compactValFor(unscaledVal); 1045 int mcp = mc.precision; 1046 int prec = 0; 1047 if (mcp > 0) { // do rounding 1048 int mode = mc.roundingMode.oldMode; 1049 if (compactVal == INFLATED) { 1050 prec = bigDigitLength(unscaledVal); 1051 int drop = prec - mcp; 1052 while (drop > 0) { 1053 scale = checkScaleNonZero((long) scale - drop); 1054 unscaledVal = divideAndRoundByTenPow(unscaledVal, drop, mode); 1055 compactVal = compactValFor(unscaledVal); 1056 if (compactVal != INFLATED) { 1057 break; 1058 } 1059 prec = bigDigitLength(unscaledVal); 1060 drop = prec - mcp; 1061 } 1062 } 1063 if (compactVal != INFLATED) { 1064 prec = longDigitLength(compactVal); 1065 int drop = prec - mcp; // drop can't be more than 18 1066 while (drop > 0) { 1067 scale = checkScaleNonZero((long) scale - drop); 1068 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mode); 1069 prec = longDigitLength(compactVal); 1070 drop = prec - mcp; 1071 } 1072 unscaledVal = null; 1073 } 1074 } 1075 this.intVal = unscaledVal; 1076 this.intCompact = compactVal; 1077 this.scale = scale; 1078 this.precision = prec; 1079 } 1080 1081 /** 1082 * Translates an {@code int} into a {@code BigDecimal}. The 1083 * scale of the {@code BigDecimal} is zero. 1084 * 1085 * @param val {@code int} value to be converted to 1086 * {@code BigDecimal}. 1087 * @since 1.5 1088 */ 1089 public BigDecimal(int val) { 1090 this.intCompact = val; 1091 this.scale = 0; 1092 this.intVal = null; 1093 } 1094 1095 /** 1096 * Translates an {@code int} into a {@code BigDecimal}, with 1097 * rounding according to the context settings. The scale of the 1098 * {@code BigDecimal}, before any rounding, is zero. 1099 * 1100 * @param val {@code int} value to be converted to {@code BigDecimal}. 1101 * @param mc the context to use. 1102 * @throws ArithmeticException if the result is inexact but the 1103 * rounding mode is {@code UNNECESSARY}. 1104 * @since 1.5 1105 */ 1106 public BigDecimal(int val, MathContext mc) { 1107 int mcp = mc.precision; 1108 long compactVal = val; 1109 int scale = 0; 1110 int prec = 0; 1111 if (mcp > 0) { // do rounding 1112 prec = longDigitLength(compactVal); 1113 int drop = prec - mcp; // drop can't be more than 18 1114 while (drop > 0) { 1115 scale = checkScaleNonZero((long) scale - drop); 1116 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 1117 prec = longDigitLength(compactVal); 1118 drop = prec - mcp; 1119 } 1120 } 1121 this.intVal = null; 1122 this.intCompact = compactVal; 1123 this.scale = scale; 1124 this.precision = prec; 1125 } 1126 1127 /** 1128 * Translates a {@code long} into a {@code BigDecimal}. The 1129 * scale of the {@code BigDecimal} is zero. 1130 * 1131 * @param val {@code long} value to be converted to {@code BigDecimal}. 1132 * @since 1.5 1133 */ 1134 public BigDecimal(long val) { 1135 this.intCompact = val; 1136 this.intVal = (val == INFLATED) ? INFLATED_BIGINT : null; 1137 this.scale = 0; 1138 } 1139 1140 /** 1141 * Translates a {@code long} into a {@code BigDecimal}, with 1142 * rounding according to the context settings. The scale of the 1143 * {@code BigDecimal}, before any rounding, is zero. 1144 * 1145 * @param val {@code long} value to be converted to {@code BigDecimal}. 1146 * @param mc the context to use. 1147 * @throws ArithmeticException if the result is inexact but the 1148 * rounding mode is {@code UNNECESSARY}. 1149 * @since 1.5 1150 */ 1151 public BigDecimal(long val, MathContext mc) { 1152 int mcp = mc.precision; 1153 int mode = mc.roundingMode.oldMode; 1154 int prec = 0; 1155 int scale = 0; 1156 BigInteger intVal = (val == INFLATED) ? INFLATED_BIGINT : null; 1157 if (mcp > 0) { // do rounding 1158 if (val == INFLATED) { 1159 prec = 19; 1160 int drop = prec - mcp; 1161 while (drop > 0) { 1162 scale = checkScaleNonZero((long) scale - drop); 1163 intVal = divideAndRoundByTenPow(intVal, drop, mode); 1164 val = compactValFor(intVal); 1165 if (val != INFLATED) { 1166 break; 1167 } 1168 prec = bigDigitLength(intVal); 1169 drop = prec - mcp; 1170 } 1171 } 1172 if (val != INFLATED) { 1173 prec = longDigitLength(val); 1174 int drop = prec - mcp; 1175 while (drop > 0) { 1176 scale = checkScaleNonZero((long) scale - drop); 1177 val = divideAndRound(val, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 1178 prec = longDigitLength(val); 1179 drop = prec - mcp; 1180 } 1181 intVal = null; 1182 } 1183 } 1184 this.intVal = intVal; 1185 this.intCompact = val; 1186 this.scale = scale; 1187 this.precision = prec; 1188 } 1189 1190 // Static Factory Methods 1191 1192 /** 1193 * Translates a {@code long} unscaled value and an 1194 * {@code int} scale into a {@code BigDecimal}. This 1195 * {@literal "static factory method"} is provided in preference to 1196 * a ({@code long}, {@code int}) constructor because it 1197 * allows for reuse of frequently used {@code BigDecimal} values.. 1198 * 1199 * @param unscaledVal unscaled value of the {@code BigDecimal}. 1200 * @param scale scale of the {@code BigDecimal}. 1201 * @return a {@code BigDecimal} whose value is 1202 * <tt>(unscaledVal × 10<sup>-scale</sup>)</tt>. 1203 */ 1204 public static BigDecimal valueOf(long unscaledVal, int scale) { 1205 if (scale == 0) 1206 return valueOf(unscaledVal); 1207 else if (unscaledVal == 0) { 1208 return zeroValueOf(scale); 1209 } 1210 return new BigDecimal(unscaledVal == INFLATED ? 1211 INFLATED_BIGINT : null, 1212 unscaledVal, scale, 0); 1213 } 1214 1215 /** 1216 * Translates a {@code long} value into a {@code BigDecimal} 1217 * with a scale of zero. This {@literal "static factory method"} 1218 * is provided in preference to a ({@code long}) constructor 1219 * because it allows for reuse of frequently used 1220 * {@code BigDecimal} values. 1221 * 1222 * @param val value of the {@code BigDecimal}. 1223 * @return a {@code BigDecimal} whose value is {@code val}. 1224 */ 1225 public static BigDecimal valueOf(long val) { 1226 if (val >= 0 && val < zeroThroughTen.length) 1227 return zeroThroughTen[(int)val]; 1228 else if (val != INFLATED) 1229 return new BigDecimal(null, val, 0, 0); 1230 return new BigDecimal(INFLATED_BIGINT, val, 0, 0); 1231 } 1232 1233 static BigDecimal valueOf(long unscaledVal, int scale, int prec) { 1234 if (scale == 0 && unscaledVal >= 0 && unscaledVal < zeroThroughTen.length) { 1235 return zeroThroughTen[(int) unscaledVal]; 1236 } else if (unscaledVal == 0) { 1237 return zeroValueOf(scale); 1238 } 1239 return new BigDecimal(unscaledVal == INFLATED ? INFLATED_BIGINT : null, 1240 unscaledVal, scale, prec); 1241 } 1242 1243 static BigDecimal valueOf(BigInteger intVal, int scale, int prec) { 1244 long val = compactValFor(intVal); 1245 if (val == 0) { 1246 return zeroValueOf(scale); 1247 } else if (scale == 0 && val >= 0 && val < zeroThroughTen.length) { 1248 return zeroThroughTen[(int) val]; 1249 } 1250 return new BigDecimal(intVal, val, scale, prec); 1251 } 1252 1253 static BigDecimal zeroValueOf(int scale) { 1254 if (scale >= 0 && scale < ZERO_SCALED_BY.length) 1255 return ZERO_SCALED_BY[scale]; 1256 else 1257 return new BigDecimal(BigInteger.ZERO, 0, scale, 1); 1258 } 1259 1260 /** 1261 * Translates a {@code double} into a {@code BigDecimal}, using 1262 * the {@code double}'s canonical string representation provided 1263 * by the {@link Double#toString(double)} method. 1264 * 1265 * <p><b>Note:</b> This is generally the preferred way to convert 1266 * a {@code double} (or {@code float}) into a 1267 * {@code BigDecimal}, as the value returned is equal to that 1268 * resulting from constructing a {@code BigDecimal} from the 1269 * result of using {@link Double#toString(double)}. 1270 * 1271 * @param val {@code double} to convert to a {@code BigDecimal}. 1272 * @return a {@code BigDecimal} whose value is equal to or approximately 1273 * equal to the value of {@code val}. 1274 * @throws NumberFormatException if {@code val} is infinite or NaN. 1275 * @since 1.5 1276 */ 1277 public static BigDecimal valueOf(double val) { 1278 // Reminder: a zero double returns '0.0', so we cannot fastpath 1279 // to use the constant ZERO. This might be important enough to 1280 // justify a factory approach, a cache, or a few private 1281 // constants, later. 1282 return new BigDecimal(Double.toString(val)); 1283 } 1284 1285 // Arithmetic Operations 1286 /** 1287 * Returns a {@code BigDecimal} whose value is {@code (this + 1288 * augend)}, and whose scale is {@code max(this.scale(), 1289 * augend.scale())}. 1290 * 1291 * @param augend value to be added to this {@code BigDecimal}. 1292 * @return {@code this + augend} 1293 */ 1294 public BigDecimal add(BigDecimal augend) { 1295 if (this.intCompact != INFLATED) { 1296 if ((augend.intCompact != INFLATED)) { 1297 return add(this.intCompact, this.scale, augend.intCompact, augend.scale); 1298 } else { 1299 return add(this.intCompact, this.scale, augend.intVal, augend.scale); 1300 } 1301 } else { 1302 if ((augend.intCompact != INFLATED)) { 1303 return add(augend.intCompact, augend.scale, this.intVal, this.scale); 1304 } else { 1305 return add(this.intVal, this.scale, augend.intVal, augend.scale); 1306 } 1307 } 1308 } 1309 1310 /** 1311 * Returns a {@code BigDecimal} whose value is {@code (this + augend)}, 1312 * with rounding according to the context settings. 1313 * 1314 * If either number is zero and the precision setting is nonzero then 1315 * the other number, rounded if necessary, is used as the result. 1316 * 1317 * @param augend value to be added to this {@code BigDecimal}. 1318 * @param mc the context to use. 1319 * @return {@code this + augend}, rounded as necessary. 1320 * @throws ArithmeticException if the result is inexact but the 1321 * rounding mode is {@code UNNECESSARY}. 1322 * @since 1.5 1323 */ 1324 public BigDecimal add(BigDecimal augend, MathContext mc) { 1325 if (mc.precision == 0) 1326 return add(augend); 1327 BigDecimal lhs = this; 1328 1329 // If either number is zero then the other number, rounded and 1330 // scaled if necessary, is used as the result. 1331 { 1332 boolean lhsIsZero = lhs.signum() == 0; 1333 boolean augendIsZero = augend.signum() == 0; 1334 1335 if (lhsIsZero || augendIsZero) { 1336 int preferredScale = Math.max(lhs.scale(), augend.scale()); 1337 BigDecimal result; 1338 // Could use a factory for zero instead of a new object 1339 if (lhsIsZero && augendIsZero) 1340 return zeroValueOf(preferredScale); 1341 result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc); 1342 1343 if (result.scale() == preferredScale) 1344 return result; 1345 else if (result.scale() > preferredScale) { 1346 return stripZerosToMatchScale(result.intVal, result.intCompact, result.scale, preferredScale); 1347 } else { // result.scale < preferredScale 1348 int precisionDiff = mc.precision - result.precision(); 1349 int scaleDiff = preferredScale - result.scale(); 1350 1351 if (precisionDiff >= scaleDiff) 1352 return result.setScale(preferredScale); // can achieve target scale 1353 else 1354 return result.setScale(result.scale() + precisionDiff); 1355 } 1356 } 1357 } 1358 1359 long padding = (long) lhs.scale - augend.scale; 1360 if (padding != 0) { // scales differ; alignment needed 1361 BigDecimal arg[] = preAlign(lhs, augend, padding, mc); 1362 matchScale(arg); 1363 lhs = arg[0]; 1364 augend = arg[1]; 1365 } 1366 return doRound(lhs.inflated().add(augend.inflated()), lhs.scale, mc); 1367 } 1368 1369 /** 1370 * Returns an array of length two, the sum of whose entries is 1371 * equal to the rounded sum of the {@code BigDecimal} arguments. 1372 * 1373 * <p>If the digit positions of the arguments have a sufficient 1374 * gap between them, the value smaller in magnitude can be 1375 * condensed into a {@literal "sticky bit"} and the end result will 1376 * round the same way <em>if</em> the precision of the final 1377 * result does not include the high order digit of the small 1378 * magnitude operand. 1379 * 1380 * <p>Note that while strictly speaking this is an optimization, 1381 * it makes a much wider range of additions practical. 1382 * 1383 * <p>This corresponds to a pre-shift operation in a fixed 1384 * precision floating-point adder; this method is complicated by 1385 * variable precision of the result as determined by the 1386 * MathContext. A more nuanced operation could implement a 1387 * {@literal "right shift"} on the smaller magnitude operand so 1388 * that the number of digits of the smaller operand could be 1389 * reduced even though the significands partially overlapped. 1390 */ 1391 private BigDecimal[] preAlign(BigDecimal lhs, BigDecimal augend, long padding, MathContext mc) { 1392 assert padding != 0; 1393 BigDecimal big; 1394 BigDecimal small; 1395 1396 if (padding < 0) { // lhs is big; augend is small 1397 big = lhs; 1398 small = augend; 1399 } else { // lhs is small; augend is big 1400 big = augend; 1401 small = lhs; 1402 } 1403 1404 /* 1405 * This is the estimated scale of an ulp of the result; it assumes that 1406 * the result doesn't have a carry-out on a true add (e.g. 999 + 1 => 1407 * 1000) or any subtractive cancellation on borrowing (e.g. 100 - 1.2 => 1408 * 98.8) 1409 */ 1410 long estResultUlpScale = (long) big.scale - big.precision() + mc.precision; 1411 1412 /* 1413 * The low-order digit position of big is big.scale(). This 1414 * is true regardless of whether big has a positive or 1415 * negative scale. The high-order digit position of small is 1416 * small.scale - (small.precision() - 1). To do the full 1417 * condensation, the digit positions of big and small must be 1418 * disjoint *and* the digit positions of small should not be 1419 * directly visible in the result. 1420 */ 1421 long smallHighDigitPos = (long) small.scale - small.precision() + 1; 1422 if (smallHighDigitPos > big.scale + 2 && // big and small disjoint 1423 smallHighDigitPos > estResultUlpScale + 2) { // small digits not visible 1424 small = BigDecimal.valueOf(small.signum(), this.checkScale(Math.max(big.scale, estResultUlpScale) + 3)); 1425 } 1426 1427 // Since addition is symmetric, preserving input order in 1428 // returned operands doesn't matter 1429 BigDecimal[] result = {big, small}; 1430 return result; 1431 } 1432 1433 /** 1434 * Returns a {@code BigDecimal} whose value is {@code (this - 1435 * subtrahend)}, and whose scale is {@code max(this.scale(), 1436 * subtrahend.scale())}. 1437 * 1438 * @param subtrahend value to be subtracted from this {@code BigDecimal}. 1439 * @return {@code this - subtrahend} 1440 */ 1441 public BigDecimal subtract(BigDecimal subtrahend) { 1442 if (this.intCompact != INFLATED) { 1443 if ((subtrahend.intCompact != INFLATED)) { 1444 return add(this.intCompact, this.scale, -subtrahend.intCompact, subtrahend.scale); 1445 } else { 1446 return add(this.intCompact, this.scale, subtrahend.intVal.negate(), subtrahend.scale); 1447 } 1448 } else { 1449 if ((subtrahend.intCompact != INFLATED)) { 1450 // Pair of subtrahend values given before pair of 1451 // values from this BigDecimal to avoid need for 1452 // method overloading on the specialized add method 1453 return add(-subtrahend.intCompact, subtrahend.scale, this.intVal, this.scale); 1454 } else { 1455 return add(this.intVal, this.scale, subtrahend.intVal.negate(), subtrahend.scale); 1456 } 1457 } 1458 } 1459 1460 /** 1461 * Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)}, 1462 * with rounding according to the context settings. 1463 * 1464 * If {@code subtrahend} is zero then this, rounded if necessary, is used as the 1465 * result. If this is zero then the result is {@code subtrahend.negate(mc)}. 1466 * 1467 * @param subtrahend value to be subtracted from this {@code BigDecimal}. 1468 * @param mc the context to use. 1469 * @return {@code this - subtrahend}, rounded as necessary. 1470 * @throws ArithmeticException if the result is inexact but the 1471 * rounding mode is {@code UNNECESSARY}. 1472 * @since 1.5 1473 */ 1474 public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) { 1475 if (mc.precision == 0) 1476 return subtract(subtrahend); 1477 // share the special rounding code in add() 1478 return add(subtrahend.negate(), mc); 1479 } 1480 1481 /** 1482 * Returns a {@code BigDecimal} whose value is <tt>(this × 1483 * multiplicand)</tt>, and whose scale is {@code (this.scale() + 1484 * multiplicand.scale())}. 1485 * 1486 * @param multiplicand value to be multiplied by this {@code BigDecimal}. 1487 * @return {@code this * multiplicand} 1488 */ 1489 public BigDecimal multiply(BigDecimal multiplicand) { 1490 int productScale = checkScale((long) scale + multiplicand.scale); 1491 if (this.intCompact != INFLATED) { 1492 if ((multiplicand.intCompact != INFLATED)) { 1493 return multiply(this.intCompact, multiplicand.intCompact, productScale); 1494 } else { 1495 return multiply(this.intCompact, multiplicand.intVal, productScale); 1496 } 1497 } else { 1498 if ((multiplicand.intCompact != INFLATED)) { 1499 return multiply(multiplicand.intCompact, this.intVal, productScale); 1500 } else { 1501 return multiply(this.intVal, multiplicand.intVal, productScale); 1502 } 1503 } 1504 } 1505 1506 /** 1507 * Returns a {@code BigDecimal} whose value is <tt>(this × 1508 * multiplicand)</tt>, with rounding according to the context settings. 1509 * 1510 * @param multiplicand value to be multiplied by this {@code BigDecimal}. 1511 * @param mc the context to use. 1512 * @return {@code this * multiplicand}, rounded as necessary. 1513 * @throws ArithmeticException if the result is inexact but the 1514 * rounding mode is {@code UNNECESSARY}. 1515 * @since 1.5 1516 */ 1517 public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { 1518 if (mc.precision == 0) 1519 return multiply(multiplicand); 1520 int productScale = checkScale((long) scale + multiplicand.scale); 1521 if (this.intCompact != INFLATED) { 1522 if ((multiplicand.intCompact != INFLATED)) { 1523 return multiplyAndRound(this.intCompact, multiplicand.intCompact, productScale, mc); 1524 } else { 1525 return multiplyAndRound(this.intCompact, multiplicand.intVal, productScale, mc); 1526 } 1527 } else { 1528 if ((multiplicand.intCompact != INFLATED)) { 1529 return multiplyAndRound(multiplicand.intCompact, this.intVal, productScale, mc); 1530 } else { 1531 return multiplyAndRound(this.intVal, multiplicand.intVal, productScale, mc); 1532 } 1533 } 1534 } 1535 1536 /** 1537 * Returns a {@code BigDecimal} whose value is {@code (this / 1538 * divisor)}, and whose scale is as specified. If rounding must 1539 * be performed to generate a result with the specified scale, the 1540 * specified rounding mode is applied. 1541 * 1542 * <p>The new {@link #divide(BigDecimal, int, RoundingMode)} method 1543 * should be used in preference to this legacy method. 1544 * 1545 * @param divisor value by which this {@code BigDecimal} is to be divided. 1546 * @param scale scale of the {@code BigDecimal} quotient to be returned. 1547 * @param roundingMode rounding mode to apply. 1548 * @return {@code this / divisor} 1549 * @throws ArithmeticException if {@code divisor} is zero, 1550 * {@code roundingMode==ROUND_UNNECESSARY} and 1551 * the specified scale is insufficient to represent the result 1552 * of the division exactly. 1553 * @throws IllegalArgumentException if {@code roundingMode} does not 1554 * represent a valid rounding mode. 1555 * @see #ROUND_UP 1556 * @see #ROUND_DOWN 1557 * @see #ROUND_CEILING 1558 * @see #ROUND_FLOOR 1559 * @see #ROUND_HALF_UP 1560 * @see #ROUND_HALF_DOWN 1561 * @see #ROUND_HALF_EVEN 1562 * @see #ROUND_UNNECESSARY 1563 */ 1564 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { 1565 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 1566 throw new IllegalArgumentException("Invalid rounding mode"); 1567 if (this.intCompact != INFLATED) { 1568 if ((divisor.intCompact != INFLATED)) { 1569 return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode); 1570 } else { 1571 return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode); 1572 } 1573 } else { 1574 if ((divisor.intCompact != INFLATED)) { 1575 return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode); 1576 } else { 1577 return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode); 1578 } 1579 } 1580 } 1581 1582 /** 1583 * Returns a {@code BigDecimal} whose value is {@code (this / 1584 * divisor)}, and whose scale is as specified. If rounding must 1585 * be performed to generate a result with the specified scale, the 1586 * specified rounding mode is applied. 1587 * 1588 * @param divisor value by which this {@code BigDecimal} is to be divided. 1589 * @param scale scale of the {@code BigDecimal} quotient to be returned. 1590 * @param roundingMode rounding mode to apply. 1591 * @return {@code this / divisor} 1592 * @throws ArithmeticException if {@code divisor} is zero, 1593 * {@code roundingMode==RoundingMode.UNNECESSARY} and 1594 * the specified scale is insufficient to represent the result 1595 * of the division exactly. 1596 * @since 1.5 1597 */ 1598 public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { 1599 return divide(divisor, scale, roundingMode.oldMode); 1600 } 1601 1602 /** 1603 * Returns a {@code BigDecimal} whose value is {@code (this / 1604 * divisor)}, and whose scale is {@code this.scale()}. If 1605 * rounding must be performed to generate a result with the given 1606 * scale, the specified rounding mode is applied. 1607 * 1608 * <p>The new {@link #divide(BigDecimal, RoundingMode)} method 1609 * should be used in preference to this legacy method. 1610 * 1611 * @param divisor value by which this {@code BigDecimal} is to be divided. 1612 * @param roundingMode rounding mode to apply. 1613 * @return {@code this / divisor} 1614 * @throws ArithmeticException if {@code divisor==0}, or 1615 * {@code roundingMode==ROUND_UNNECESSARY} and 1616 * {@code this.scale()} is insufficient to represent the result 1617 * of the division exactly. 1618 * @throws IllegalArgumentException if {@code roundingMode} does not 1619 * represent a valid rounding mode. 1620 * @see #ROUND_UP 1621 * @see #ROUND_DOWN 1622 * @see #ROUND_CEILING 1623 * @see #ROUND_FLOOR 1624 * @see #ROUND_HALF_UP 1625 * @see #ROUND_HALF_DOWN 1626 * @see #ROUND_HALF_EVEN 1627 * @see #ROUND_UNNECESSARY 1628 */ 1629 public BigDecimal divide(BigDecimal divisor, int roundingMode) { 1630 return this.divide(divisor, scale, roundingMode); 1631 } 1632 1633 /** 1634 * Returns a {@code BigDecimal} whose value is {@code (this / 1635 * divisor)}, and whose scale is {@code this.scale()}. If 1636 * rounding must be performed to generate a result with the given 1637 * scale, the specified rounding mode is applied. 1638 * 1639 * @param divisor value by which this {@code BigDecimal} is to be divided. 1640 * @param roundingMode rounding mode to apply. 1641 * @return {@code this / divisor} 1642 * @throws ArithmeticException if {@code divisor==0}, or 1643 * {@code roundingMode==RoundingMode.UNNECESSARY} and 1644 * {@code this.scale()} is insufficient to represent the result 1645 * of the division exactly. 1646 * @since 1.5 1647 */ 1648 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { 1649 return this.divide(divisor, scale, roundingMode.oldMode); 1650 } 1651 1652 /** 1653 * Returns a {@code BigDecimal} whose value is {@code (this / 1654 * divisor)}, and whose preferred scale is {@code (this.scale() - 1655 * divisor.scale())}; if the exact quotient cannot be 1656 * represented (because it has a non-terminating decimal 1657 * expansion) an {@code ArithmeticException} is thrown. 1658 * 1659 * @param divisor value by which this {@code BigDecimal} is to be divided. 1660 * @throws ArithmeticException if the exact quotient does not have a 1661 * terminating decimal expansion 1662 * @return {@code this / divisor} 1663 * @since 1.5 1664 * @author Joseph D. Darcy 1665 */ 1666 public BigDecimal divide(BigDecimal divisor) { 1667 /* 1668 * Handle zero cases first. 1669 */ 1670 if (divisor.signum() == 0) { // x/0 1671 if (this.signum() == 0) // 0/0 1672 throw new ArithmeticException("Division undefined"); // NaN 1673 throw new ArithmeticException("Division by zero"); 1674 } 1675 1676 // Calculate preferred scale 1677 int preferredScale = saturateLong((long) this.scale - divisor.scale); 1678 1679 if (this.signum() == 0) // 0/y 1680 return zeroValueOf(preferredScale); 1681 else { 1682 /* 1683 * If the quotient this/divisor has a terminating decimal 1684 * expansion, the expansion can have no more than 1685 * (a.precision() + ceil(10*b.precision)/3) digits. 1686 * Therefore, create a MathContext object with this 1687 * precision and do a divide with the UNNECESSARY rounding 1688 * mode. 1689 */ 1690 MathContext mc = new MathContext( (int)Math.min(this.precision() + 1691 (long)Math.ceil(10.0*divisor.precision()/3.0), 1692 Integer.MAX_VALUE), 1693 RoundingMode.UNNECESSARY); 1694 BigDecimal quotient; 1695 try { 1696 quotient = this.divide(divisor, mc); 1697 } catch (ArithmeticException e) { 1698 throw new ArithmeticException("Non-terminating decimal expansion; " + 1699 "no exact representable decimal result."); 1700 } 1701 1702 int quotientScale = quotient.scale(); 1703 1704 // divide(BigDecimal, mc) tries to adjust the quotient to 1705 // the desired one by removing trailing zeros; since the 1706 // exact divide method does not have an explicit digit 1707 // limit, we can add zeros too. 1708 if (preferredScale > quotientScale) 1709 return quotient.setScale(preferredScale, ROUND_UNNECESSARY); 1710 1711 return quotient; 1712 } 1713 } 1714 1715 /** 1716 * Returns a {@code BigDecimal} whose value is {@code (this / 1717 * divisor)}, with rounding according to the context settings. 1718 * 1719 * @param divisor value by which this {@code BigDecimal} is to be divided. 1720 * @param mc the context to use. 1721 * @return {@code this / divisor}, rounded as necessary. 1722 * @throws ArithmeticException if the result is inexact but the 1723 * rounding mode is {@code UNNECESSARY} or 1724 * {@code mc.precision == 0} and the quotient has a 1725 * non-terminating decimal expansion. 1726 * @since 1.5 1727 */ 1728 public BigDecimal divide(BigDecimal divisor, MathContext mc) { 1729 int mcp = mc.precision; 1730 if (mcp == 0) 1731 return divide(divisor); 1732 1733 BigDecimal dividend = this; 1734 long preferredScale = (long)dividend.scale - divisor.scale; 1735 // Now calculate the answer. We use the existing 1736 // divide-and-round method, but as this rounds to scale we have 1737 // to normalize the values here to achieve the desired result. 1738 // For x/y we first handle y=0 and x=0, and then normalize x and 1739 // y to give x' and y' with the following constraints: 1740 // (a) 0.1 <= x' < 1 1741 // (b) x' <= y' < 10*x' 1742 // Dividing x'/y' with the required scale set to mc.precision then 1743 // will give a result in the range 0.1 to 1 rounded to exactly 1744 // the right number of digits (except in the case of a result of 1745 // 1.000... which can arise when x=y, or when rounding overflows 1746 // The 1.000... case will reduce properly to 1. 1747 if (divisor.signum() == 0) { // x/0 1748 if (dividend.signum() == 0) // 0/0 1749 throw new ArithmeticException("Division undefined"); // NaN 1750 throw new ArithmeticException("Division by zero"); 1751 } 1752 if (dividend.signum() == 0) // 0/y 1753 return zeroValueOf(saturateLong(preferredScale)); 1754 int xscale = dividend.precision(); 1755 int yscale = divisor.precision(); 1756 if(dividend.intCompact!=INFLATED) { 1757 if(divisor.intCompact!=INFLATED) { 1758 return divide(dividend.intCompact, xscale, divisor.intCompact, yscale, preferredScale, mc); 1759 } else { 1760 return divide(dividend.intCompact, xscale, divisor.intVal, yscale, preferredScale, mc); 1761 } 1762 } else { 1763 if(divisor.intCompact!=INFLATED) { 1764 return divide(dividend.intVal, xscale, divisor.intCompact, yscale, preferredScale, mc); 1765 } else { 1766 return divide(dividend.intVal, xscale, divisor.intVal, yscale, preferredScale, mc); 1767 } 1768 } 1769 } 1770 1771 /** 1772 * Returns a {@code BigDecimal} whose value is the integer part 1773 * of the quotient {@code (this / divisor)} rounded down. The 1774 * preferred scale of the result is {@code (this.scale() - 1775 * divisor.scale())}. 1776 * 1777 * @param divisor value by which this {@code BigDecimal} is to be divided. 1778 * @return The integer part of {@code this / divisor}. 1779 * @throws ArithmeticException if {@code divisor==0} 1780 * @since 1.5 1781 */ 1782 public BigDecimal divideToIntegralValue(BigDecimal divisor) { 1783 // Calculate preferred scale 1784 int preferredScale = saturateLong((long) this.scale - divisor.scale); 1785 if (this.compareMagnitude(divisor) < 0) { 1786 // much faster when this << divisor 1787 return zeroValueOf(preferredScale); 1788 } 1789 1790 if (this.signum() == 0 && divisor.signum() != 0) 1791 return this.setScale(preferredScale, ROUND_UNNECESSARY); 1792 1793 // Perform a divide with enough digits to round to a correct 1794 // integer value; then remove any fractional digits 1795 1796 int maxDigits = (int)Math.min(this.precision() + 1797 (long)Math.ceil(10.0*divisor.precision()/3.0) + 1798 Math.abs((long)this.scale() - divisor.scale()) + 2, 1799 Integer.MAX_VALUE); 1800 BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits, 1801 RoundingMode.DOWN)); 1802 if (quotient.scale > 0) { 1803 quotient = quotient.setScale(0, RoundingMode.DOWN); 1804 quotient = stripZerosToMatchScale(quotient.intVal, quotient.intCompact, quotient.scale, preferredScale); 1805 } 1806 1807 if (quotient.scale < preferredScale) { 1808 // pad with zeros if necessary 1809 quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY); 1810 } 1811 1812 return quotient; 1813 } 1814 1815 /** 1816 * Returns a {@code BigDecimal} whose value is the integer part 1817 * of {@code (this / divisor)}. Since the integer part of the 1818 * exact quotient does not depend on the rounding mode, the 1819 * rounding mode does not affect the values returned by this 1820 * method. The preferred scale of the result is 1821 * {@code (this.scale() - divisor.scale())}. An 1822 * {@code ArithmeticException} is thrown if the integer part of 1823 * the exact quotient needs more than {@code mc.precision} 1824 * digits. 1825 * 1826 * @param divisor value by which this {@code BigDecimal} is to be divided. 1827 * @param mc the context to use. 1828 * @return The integer part of {@code this / divisor}. 1829 * @throws ArithmeticException if {@code divisor==0} 1830 * @throws ArithmeticException if {@code mc.precision} {@literal >} 0 and the result 1831 * requires a precision of more than {@code mc.precision} digits. 1832 * @since 1.5 1833 * @author Joseph D. Darcy 1834 */ 1835 public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { 1836 if (mc.precision == 0 || // exact result 1837 (this.compareMagnitude(divisor) < 0)) // zero result 1838 return divideToIntegralValue(divisor); 1839 1840 // Calculate preferred scale 1841 int preferredScale = saturateLong((long)this.scale - divisor.scale); 1842 1843 /* 1844 * Perform a normal divide to mc.precision digits. If the 1845 * remainder has absolute value less than the divisor, the 1846 * integer portion of the quotient fits into mc.precision 1847 * digits. Next, remove any fractional digits from the 1848 * quotient and adjust the scale to the preferred value. 1849 */ 1850 BigDecimal result = this.divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN)); 1851 1852 if (result.scale() < 0) { 1853 /* 1854 * Result is an integer. See if quotient represents the 1855 * full integer portion of the exact quotient; if it does, 1856 * the computed remainder will be less than the divisor. 1857 */ 1858 BigDecimal product = result.multiply(divisor); 1859 // If the quotient is the full integer value, 1860 // |dividend-product| < |divisor|. 1861 if (this.subtract(product).compareMagnitude(divisor) >= 0) { 1862 throw new ArithmeticException("Division impossible"); 1863 } 1864 } else if (result.scale() > 0) { 1865 /* 1866 * Integer portion of quotient will fit into precision 1867 * digits; recompute quotient to scale 0 to avoid double 1868 * rounding and then try to adjust, if necessary. 1869 */ 1870 result = result.setScale(0, RoundingMode.DOWN); 1871 } 1872 // else result.scale() == 0; 1873 1874 int precisionDiff; 1875 if ((preferredScale > result.scale()) && 1876 (precisionDiff = mc.precision - result.precision()) > 0) { 1877 return result.setScale(result.scale() + 1878 Math.min(precisionDiff, preferredScale - result.scale) ); 1879 } else { 1880 return stripZerosToMatchScale(result.intVal,result.intCompact,result.scale,preferredScale); 1881 } 1882 } 1883 1884 /** 1885 * Returns a {@code BigDecimal} whose value is {@code (this % divisor)}. 1886 * 1887 * <p>The remainder is given by 1888 * {@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}. 1889 * Note that this is not the modulo operation (the result can be 1890 * negative). 1891 * 1892 * @param divisor value by which this {@code BigDecimal} is to be divided. 1893 * @return {@code this % divisor}. 1894 * @throws ArithmeticException if {@code divisor==0} 1895 * @since 1.5 1896 */ 1897 public BigDecimal remainder(BigDecimal divisor) { 1898 BigDecimal divrem[] = this.divideAndRemainder(divisor); 1899 return divrem[1]; 1900 } 1901 1902 1903 /** 1904 * Returns a {@code BigDecimal} whose value is {@code (this % 1905 * divisor)}, with rounding according to the context settings. 1906 * The {@code MathContext} settings affect the implicit divide 1907 * used to compute the remainder. The remainder computation 1908 * itself is by definition exact. Therefore, the remainder may 1909 * contain more than {@code mc.getPrecision()} digits. 1910 * 1911 * <p>The remainder is given by 1912 * {@code this.subtract(this.divideToIntegralValue(divisor, 1913 * mc).multiply(divisor))}. Note that this is not the modulo 1914 * operation (the result can be negative). 1915 * 1916 * @param divisor value by which this {@code BigDecimal} is to be divided. 1917 * @param mc the context to use. 1918 * @return {@code this % divisor}, rounded as necessary. 1919 * @throws ArithmeticException if {@code divisor==0} 1920 * @throws ArithmeticException if the result is inexact but the 1921 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 1922 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 1923 * require a precision of more than {@code mc.precision} digits. 1924 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1925 * @since 1.5 1926 */ 1927 public BigDecimal remainder(BigDecimal divisor, MathContext mc) { 1928 BigDecimal divrem[] = this.divideAndRemainder(divisor, mc); 1929 return divrem[1]; 1930 } 1931 1932 /** 1933 * Returns a two-element {@code BigDecimal} array containing the 1934 * result of {@code divideToIntegralValue} followed by the result of 1935 * {@code remainder} on the two operands. 1936 * 1937 * <p>Note that if both the integer quotient and remainder are 1938 * needed, this method is faster than using the 1939 * {@code divideToIntegralValue} and {@code remainder} methods 1940 * separately because the division need only be carried out once. 1941 * 1942 * @param divisor value by which this {@code BigDecimal} is to be divided, 1943 * and the remainder computed. 1944 * @return a two element {@code BigDecimal} array: the quotient 1945 * (the result of {@code divideToIntegralValue}) is the initial element 1946 * and the remainder is the final element. 1947 * @throws ArithmeticException if {@code divisor==0} 1948 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1949 * @see #remainder(java.math.BigDecimal, java.math.MathContext) 1950 * @since 1.5 1951 */ 1952 public BigDecimal[] divideAndRemainder(BigDecimal divisor) { 1953 // we use the identity x = i * y + r to determine r 1954 BigDecimal[] result = new BigDecimal[2]; 1955 1956 result[0] = this.divideToIntegralValue(divisor); 1957 result[1] = this.subtract(result[0].multiply(divisor)); 1958 return result; 1959 } 1960 1961 /** 1962 * Returns a two-element {@code BigDecimal} array containing the 1963 * result of {@code divideToIntegralValue} followed by the result of 1964 * {@code remainder} on the two operands calculated with rounding 1965 * according to the context settings. 1966 * 1967 * <p>Note that if both the integer quotient and remainder are 1968 * needed, this method is faster than using the 1969 * {@code divideToIntegralValue} and {@code remainder} methods 1970 * separately because the division need only be carried out once. 1971 * 1972 * @param divisor value by which this {@code BigDecimal} is to be divided, 1973 * and the remainder computed. 1974 * @param mc the context to use. 1975 * @return a two element {@code BigDecimal} array: the quotient 1976 * (the result of {@code divideToIntegralValue}) is the 1977 * initial element and the remainder is the final element. 1978 * @throws ArithmeticException if {@code divisor==0} 1979 * @throws ArithmeticException if the result is inexact but the 1980 * rounding mode is {@code UNNECESSARY}, or {@code mc.precision} 1981 * {@literal >} 0 and the result of {@code this.divideToIntgralValue(divisor)} would 1982 * require a precision of more than {@code mc.precision} digits. 1983 * @see #divideToIntegralValue(java.math.BigDecimal, java.math.MathContext) 1984 * @see #remainder(java.math.BigDecimal, java.math.MathContext) 1985 * @since 1.5 1986 */ 1987 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { 1988 if (mc.precision == 0) 1989 return divideAndRemainder(divisor); 1990 1991 BigDecimal[] result = new BigDecimal[2]; 1992 BigDecimal lhs = this; 1993 1994 result[0] = lhs.divideToIntegralValue(divisor, mc); 1995 result[1] = lhs.subtract(result[0].multiply(divisor)); 1996 return result; 1997 } 1998 1999 /** 2000 * Returns a {@code BigDecimal} whose value is 2001 * <tt>(this<sup>n</sup>)</tt>, The power is computed exactly, to 2002 * unlimited precision. 2003 * 2004 * <p>The parameter {@code n} must be in the range 0 through 2005 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link 2006 * #ONE}. 2007 * 2008 * Note that future releases may expand the allowable exponent 2009 * range of this method. 2010 * 2011 * @param n power to raise this {@code BigDecimal} to. 2012 * @return <tt>this<sup>n</sup></tt> 2013 * @throws ArithmeticException if {@code n} is out of range. 2014 * @since 1.5 2015 */ 2016 public BigDecimal pow(int n) { 2017 if (n < 0 || n > 999999999) 2018 throw new ArithmeticException("Invalid operation"); 2019 // No need to calculate pow(n) if result will over/underflow. 2020 // Don't attempt to support "supernormal" numbers. 2021 int newScale = checkScale((long)scale * n); 2022 return new BigDecimal(this.inflated().pow(n), newScale); 2023 } 2024 2025 2026 /** 2027 * Returns a {@code BigDecimal} whose value is 2028 * <tt>(this<sup>n</sup>)</tt>. The current implementation uses 2029 * the core algorithm defined in ANSI standard X3.274-1996 with 2030 * rounding according to the context settings. In general, the 2031 * returned numerical value is within two ulps of the exact 2032 * numerical value for the chosen precision. Note that future 2033 * releases may use a different algorithm with a decreased 2034 * allowable error bound and increased allowable exponent range. 2035 * 2036 * <p>The X3.274-1996 algorithm is: 2037 * 2038 * <ul> 2039 * <li> An {@code ArithmeticException} exception is thrown if 2040 * <ul> 2041 * <li>{@code abs(n) > 999999999} 2042 * <li>{@code mc.precision == 0} and {@code n < 0} 2043 * <li>{@code mc.precision > 0} and {@code n} has more than 2044 * {@code mc.precision} decimal digits 2045 * </ul> 2046 * 2047 * <li> if {@code n} is zero, {@link #ONE} is returned even if 2048 * {@code this} is zero, otherwise 2049 * <ul> 2050 * <li> if {@code n} is positive, the result is calculated via 2051 * the repeated squaring technique into a single accumulator. 2052 * The individual multiplications with the accumulator use the 2053 * same math context settings as in {@code mc} except for a 2054 * precision increased to {@code mc.precision + elength + 1} 2055 * where {@code elength} is the number of decimal digits in 2056 * {@code n}. 2057 * 2058 * <li> if {@code n} is negative, the result is calculated as if 2059 * {@code n} were positive; this value is then divided into one 2060 * using the working precision specified above. 2061 * 2062 * <li> The final value from either the positive or negative case 2063 * is then rounded to the destination precision. 2064 * </ul> 2065 * </ul> 2066 * 2067 * @param n power to raise this {@code BigDecimal} to. 2068 * @param mc the context to use. 2069 * @return <tt>this<sup>n</sup></tt> using the ANSI standard X3.274-1996 2070 * algorithm 2071 * @throws ArithmeticException if the result is inexact but the 2072 * rounding mode is {@code UNNECESSARY}, or {@code n} is out 2073 * of range. 2074 * @since 1.5 2075 */ 2076 public BigDecimal pow(int n, MathContext mc) { 2077 if (mc.precision == 0) 2078 return pow(n); 2079 if (n < -999999999 || n > 999999999) 2080 throw new ArithmeticException("Invalid operation"); 2081 if (n == 0) 2082 return ONE; // x**0 == 1 in X3.274 2083 BigDecimal lhs = this; 2084 MathContext workmc = mc; // working settings 2085 int mag = Math.abs(n); // magnitude of n 2086 if (mc.precision > 0) { 2087 int elength = longDigitLength(mag); // length of n in digits 2088 if (elength > mc.precision) // X3.274 rule 2089 throw new ArithmeticException("Invalid operation"); 2090 workmc = new MathContext(mc.precision + elength + 1, 2091 mc.roundingMode); 2092 } 2093 // ready to carry out power calculation... 2094 BigDecimal acc = ONE; // accumulator 2095 boolean seenbit = false; // set once we've seen a 1-bit 2096 for (int i=1;;i++) { // for each bit [top bit ignored] 2097 mag += mag; // shift left 1 bit 2098 if (mag < 0) { // top bit is set 2099 seenbit = true; // OK, we're off 2100 acc = acc.multiply(lhs, workmc); // acc=acc*x 2101 } 2102 if (i == 31) 2103 break; // that was the last bit 2104 if (seenbit) 2105 acc=acc.multiply(acc, workmc); // acc=acc*acc [square] 2106 // else (!seenbit) no point in squaring ONE 2107 } 2108 // if negative n, calculate the reciprocal using working precision 2109 if (n < 0) // [hence mc.precision>0] 2110 acc=ONE.divide(acc, workmc); 2111 // round to final precision and strip zeros 2112 return doRound(acc, mc); 2113 } 2114 2115 /** 2116 * Returns a {@code BigDecimal} whose value is the absolute value 2117 * of this {@code BigDecimal}, and whose scale is 2118 * {@code this.scale()}. 2119 * 2120 * @return {@code abs(this)} 2121 */ 2122 public BigDecimal abs() { 2123 return (signum() < 0 ? negate() : this); 2124 } 2125 2126 /** 2127 * Returns a {@code BigDecimal} whose value is the absolute value 2128 * of this {@code BigDecimal}, with rounding according to the 2129 * context settings. 2130 * 2131 * @param mc the context to use. 2132 * @return {@code abs(this)}, rounded as necessary. 2133 * @throws ArithmeticException if the result is inexact but the 2134 * rounding mode is {@code UNNECESSARY}. 2135 * @since 1.5 2136 */ 2137 public BigDecimal abs(MathContext mc) { 2138 return (signum() < 0 ? negate(mc) : plus(mc)); 2139 } 2140 2141 /** 2142 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2143 * and whose scale is {@code this.scale()}. 2144 * 2145 * @return {@code -this}. 2146 */ 2147 public BigDecimal negate() { 2148 if (intCompact == INFLATED) { 2149 return new BigDecimal(intVal.negate(), INFLATED, scale, precision); 2150 } else { 2151 return valueOf(-intCompact, scale, precision); 2152 } 2153 } 2154 2155 /** 2156 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2157 * with rounding according to the context settings. 2158 * 2159 * @param mc the context to use. 2160 * @return {@code -this}, rounded as necessary. 2161 * @throws ArithmeticException if the result is inexact but the 2162 * rounding mode is {@code UNNECESSARY}. 2163 * @since 1.5 2164 */ 2165 public BigDecimal negate(MathContext mc) { 2166 return negate().plus(mc); 2167 } 2168 2169 /** 2170 * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose 2171 * scale is {@code this.scale()}. 2172 * 2173 * <p>This method, which simply returns this {@code BigDecimal} 2174 * is included for symmetry with the unary minus method {@link 2175 * #negate()}. 2176 * 2177 * @return {@code this}. 2178 * @see #negate() 2179 * @since 1.5 2180 */ 2181 public BigDecimal plus() { 2182 return this; 2183 } 2184 2185 /** 2186 * Returns a {@code BigDecimal} whose value is {@code (+this)}, 2187 * with rounding according to the context settings. 2188 * 2189 * <p>The effect of this method is identical to that of the {@link 2190 * #round(MathContext)} method. 2191 * 2192 * @param mc the context to use. 2193 * @return {@code this}, rounded as necessary. A zero result will 2194 * have a scale of 0. 2195 * @throws ArithmeticException if the result is inexact but the 2196 * rounding mode is {@code UNNECESSARY}. 2197 * @see #round(MathContext) 2198 * @since 1.5 2199 */ 2200 public BigDecimal plus(MathContext mc) { 2201 if (mc.precision == 0) // no rounding please 2202 return this; 2203 return doRound(this, mc); 2204 } 2205 2206 /** 2207 * Returns the signum function of this {@code BigDecimal}. 2208 * 2209 * @return -1, 0, or 1 as the value of this {@code BigDecimal} 2210 * is negative, zero, or positive. 2211 */ 2212 public int signum() { 2213 return (intCompact != INFLATED)? 2214 Long.signum(intCompact): 2215 intVal.signum(); 2216 } 2217 2218 /** 2219 * Returns the <i>scale</i> of this {@code BigDecimal}. If zero 2220 * or positive, the scale is the number of digits to the right of 2221 * the decimal point. If negative, the unscaled value of the 2222 * number is multiplied by ten to the power of the negation of the 2223 * scale. For example, a scale of {@code -3} means the unscaled 2224 * value is multiplied by 1000. 2225 * 2226 * @return the scale of this {@code BigDecimal}. 2227 */ 2228 public int scale() { 2229 return scale; 2230 } 2231 2232 /** 2233 * Returns the <i>precision</i> of this {@code BigDecimal}. (The 2234 * precision is the number of digits in the unscaled value.) 2235 * 2236 * <p>The precision of a zero value is 1. 2237 * 2238 * @return the precision of this {@code BigDecimal}. 2239 * @since 1.5 2240 */ 2241 public int precision() { 2242 int result = precision; 2243 if (result == 0) { 2244 long s = intCompact; 2245 if (s != INFLATED) 2246 result = longDigitLength(s); 2247 else 2248 result = bigDigitLength(intVal); 2249 precision = result; 2250 } 2251 return result; 2252 } 2253 2254 2255 /** 2256 * Returns a {@code BigInteger} whose value is the <i>unscaled 2257 * value</i> of this {@code BigDecimal}. (Computes <tt>(this * 2258 * 10<sup>this.scale()</sup>)</tt>.) 2259 * 2260 * @return the unscaled value of this {@code BigDecimal}. 2261 * @since 1.2 2262 */ 2263 public BigInteger unscaledValue() { 2264 return this.inflated(); 2265 } 2266 2267 // Rounding Modes 2268 2269 /** 2270 * Rounding mode to round away from zero. Always increments the 2271 * digit prior to a nonzero discarded fraction. Note that this rounding 2272 * mode never decreases the magnitude of the calculated value. 2273 */ 2274 public final static int ROUND_UP = 0; 2275 2276 /** 2277 * Rounding mode to round towards zero. Never increments the digit 2278 * prior to a discarded fraction (i.e., truncates). Note that this 2279 * rounding mode never increases the magnitude of the calculated value. 2280 */ 2281 public final static int ROUND_DOWN = 1; 2282 2283 /** 2284 * Rounding mode to round towards positive infinity. If the 2285 * {@code BigDecimal} is positive, behaves as for 2286 * {@code ROUND_UP}; if negative, behaves as for 2287 * {@code ROUND_DOWN}. Note that this rounding mode never 2288 * decreases the calculated value. 2289 */ 2290 public final static int ROUND_CEILING = 2; 2291 2292 /** 2293 * Rounding mode to round towards negative infinity. If the 2294 * {@code BigDecimal} is positive, behave as for 2295 * {@code ROUND_DOWN}; if negative, behave as for 2296 * {@code ROUND_UP}. Note that this rounding mode never 2297 * increases the calculated value. 2298 */ 2299 public final static int ROUND_FLOOR = 3; 2300 2301 /** 2302 * Rounding mode to round towards {@literal "nearest neighbor"} 2303 * unless both neighbors are equidistant, in which case round up. 2304 * Behaves as for {@code ROUND_UP} if the discarded fraction is 2305 * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note 2306 * that this is the rounding mode that most of us were taught in 2307 * grade school. 2308 */ 2309 public final static int ROUND_HALF_UP = 4; 2310 2311 /** 2312 * Rounding mode to round towards {@literal "nearest neighbor"} 2313 * unless both neighbors are equidistant, in which case round 2314 * down. Behaves as for {@code ROUND_UP} if the discarded 2315 * fraction is {@literal >} 0.5; otherwise, behaves as for 2316 * {@code ROUND_DOWN}. 2317 */ 2318 public final static int ROUND_HALF_DOWN = 5; 2319 2320 /** 2321 * Rounding mode to round towards the {@literal "nearest neighbor"} 2322 * unless both neighbors are equidistant, in which case, round 2323 * towards the even neighbor. Behaves as for 2324 * {@code ROUND_HALF_UP} if the digit to the left of the 2325 * discarded fraction is odd; behaves as for 2326 * {@code ROUND_HALF_DOWN} if it's even. Note that this is the 2327 * rounding mode that minimizes cumulative error when applied 2328 * repeatedly over a sequence of calculations. 2329 */ 2330 public final static int ROUND_HALF_EVEN = 6; 2331 2332 /** 2333 * Rounding mode to assert that the requested operation has an exact 2334 * result, hence no rounding is necessary. If this rounding mode is 2335 * specified on an operation that yields an inexact result, an 2336 * {@code ArithmeticException} is thrown. 2337 */ 2338 public final static int ROUND_UNNECESSARY = 7; 2339 2340 2341 // Scaling/Rounding Operations 2342 2343 /** 2344 * Returns a {@code BigDecimal} rounded according to the 2345 * {@code MathContext} settings. If the precision setting is 0 then 2346 * no rounding takes place. 2347 * 2348 * <p>The effect of this method is identical to that of the 2349 * {@link #plus(MathContext)} method. 2350 * 2351 * @param mc the context to use. 2352 * @return a {@code BigDecimal} rounded according to the 2353 * {@code MathContext} settings. 2354 * @throws ArithmeticException if the rounding mode is 2355 * {@code UNNECESSARY} and the 2356 * {@code BigDecimal} operation would require rounding. 2357 * @see #plus(MathContext) 2358 * @since 1.5 2359 */ 2360 public BigDecimal round(MathContext mc) { 2361 return plus(mc); 2362 } 2363 2364 /** 2365 * Returns a {@code BigDecimal} whose scale is the specified 2366 * value, and whose unscaled value is determined by multiplying or 2367 * dividing this {@code BigDecimal}'s unscaled value by the 2368 * appropriate power of ten to maintain its overall value. If the 2369 * scale is reduced by the operation, the unscaled value must be 2370 * divided (rather than multiplied), and the value may be changed; 2371 * in this case, the specified rounding mode is applied to the 2372 * division. 2373 * 2374 * <p>Note that since BigDecimal objects are immutable, calls of 2375 * this method do <i>not</i> result in the original object being 2376 * modified, contrary to the usual convention of having methods 2377 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 2378 * Instead, {@code setScale} returns an object with the proper 2379 * scale; the returned object may or may not be newly allocated. 2380 * 2381 * @param newScale scale of the {@code BigDecimal} value to be returned. 2382 * @param roundingMode The rounding mode to apply. 2383 * @return a {@code BigDecimal} whose scale is the specified value, 2384 * and whose unscaled value is determined by multiplying or 2385 * dividing this {@code BigDecimal}'s unscaled value by the 2386 * appropriate power of ten to maintain its overall value. 2387 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} 2388 * and the specified scaling operation would require 2389 * rounding. 2390 * @see RoundingMode 2391 * @since 1.5 2392 */ 2393 public BigDecimal setScale(int newScale, RoundingMode roundingMode) { 2394 return setScale(newScale, roundingMode.oldMode); 2395 } 2396 2397 /** 2398 * Returns a {@code BigDecimal} whose scale is the specified 2399 * value, and whose unscaled value is determined by multiplying or 2400 * dividing this {@code BigDecimal}'s unscaled value by the 2401 * appropriate power of ten to maintain its overall value. If the 2402 * scale is reduced by the operation, the unscaled value must be 2403 * divided (rather than multiplied), and the value may be changed; 2404 * in this case, the specified rounding mode is applied to the 2405 * division. 2406 * 2407 * <p>Note that since BigDecimal objects are immutable, calls of 2408 * this method do <i>not</i> result in the original object being 2409 * modified, contrary to the usual convention of having methods 2410 * named <tt>set<i>X</i></tt> mutate field <i>{@code X}</i>. 2411 * Instead, {@code setScale} returns an object with the proper 2412 * scale; the returned object may or may not be newly allocated. 2413 * 2414 * <p>The new {@link #setScale(int, RoundingMode)} method should 2415 * be used in preference to this legacy method. 2416 * 2417 * @param newScale scale of the {@code BigDecimal} value to be returned. 2418 * @param roundingMode The rounding mode to apply. 2419 * @return a {@code BigDecimal} whose scale is the specified value, 2420 * and whose unscaled value is determined by multiplying or 2421 * dividing this {@code BigDecimal}'s unscaled value by the 2422 * appropriate power of ten to maintain its overall value. 2423 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} 2424 * and the specified scaling operation would require 2425 * rounding. 2426 * @throws IllegalArgumentException if {@code roundingMode} does not 2427 * represent a valid rounding mode. 2428 * @see #ROUND_UP 2429 * @see #ROUND_DOWN 2430 * @see #ROUND_CEILING 2431 * @see #ROUND_FLOOR 2432 * @see #ROUND_HALF_UP 2433 * @see #ROUND_HALF_DOWN 2434 * @see #ROUND_HALF_EVEN 2435 * @see #ROUND_UNNECESSARY 2436 */ 2437 public BigDecimal setScale(int newScale, int roundingMode) { 2438 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 2439 throw new IllegalArgumentException("Invalid rounding mode"); 2440 2441 int oldScale = this.scale; 2442 if (newScale == oldScale) // easy case 2443 return this; 2444 if (this.signum() == 0) // zero can have any scale 2445 return zeroValueOf(newScale); 2446 if(this.intCompact!=INFLATED) { 2447 long rs = this.intCompact; 2448 if (newScale > oldScale) { 2449 int raise = checkScale((long) newScale - oldScale); 2450 if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) { 2451 return valueOf(rs,newScale); 2452 } 2453 BigInteger rb = bigMultiplyPowerTen(raise); 2454 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0); 2455 } else { 2456 // newScale < oldScale -- drop some digits 2457 // Can't predict the precision due to the effect of rounding. 2458 int drop = checkScale((long) oldScale - newScale); 2459 if (drop < LONG_TEN_POWERS_TABLE.length) { 2460 return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale); 2461 } else { 2462 return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale); 2463 } 2464 } 2465 } else { 2466 if (newScale > oldScale) { 2467 int raise = checkScale((long) newScale - oldScale); 2468 BigInteger rb = bigMultiplyPowerTen(this.intVal,raise); 2469 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0); 2470 } else { 2471 // newScale < oldScale -- drop some digits 2472 // Can't predict the precision due to the effect of rounding. 2473 int drop = checkScale((long) oldScale - newScale); 2474 if (drop < LONG_TEN_POWERS_TABLE.length) 2475 return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, 2476 newScale); 2477 else 2478 return divideAndRound(this.intVal, bigTenToThe(drop), newScale, roundingMode, newScale); 2479 } 2480 } 2481 } 2482 2483 /** 2484 * Returns a {@code BigDecimal} whose scale is the specified 2485 * value, and whose value is numerically equal to this 2486 * {@code BigDecimal}'s. Throws an {@code ArithmeticException} 2487 * if this is not possible. 2488 * 2489 * <p>This call is typically used to increase the scale, in which 2490 * case it is guaranteed that there exists a {@code BigDecimal} 2491 * of the specified scale and the correct value. The call can 2492 * also be used to reduce the scale if the caller knows that the 2493 * {@code BigDecimal} has sufficiently many zeros at the end of 2494 * its fractional part (i.e., factors of ten in its integer value) 2495 * to allow for the rescaling without changing its value. 2496 * 2497 * <p>This method returns the same result as the two-argument 2498 * versions of {@code setScale}, but saves the caller the trouble 2499 * of specifying a rounding mode in cases where it is irrelevant. 2500 * 2501 * <p>Note that since {@code BigDecimal} objects are immutable, 2502 * calls of this method do <i>not</i> result in the original 2503 * object being modified, contrary to the usual convention of 2504 * having methods named <tt>set<i>X</i></tt> mutate field 2505 * <i>{@code X}</i>. Instead, {@code setScale} returns an 2506 * object with the proper scale; the returned object may or may 2507 * not be newly allocated. 2508 * 2509 * @param newScale scale of the {@code BigDecimal} value to be returned. 2510 * @return a {@code BigDecimal} whose scale is the specified value, and 2511 * whose unscaled value is determined by multiplying or dividing 2512 * this {@code BigDecimal}'s unscaled value by the appropriate 2513 * power of ten to maintain its overall value. 2514 * @throws ArithmeticException if the specified scaling operation would 2515 * require rounding. 2516 * @see #setScale(int, int) 2517 * @see #setScale(int, RoundingMode) 2518 */ 2519 public BigDecimal setScale(int newScale) { 2520 return setScale(newScale, ROUND_UNNECESSARY); 2521 } 2522 2523 // Decimal Point Motion Operations 2524 2525 /** 2526 * Returns a {@code BigDecimal} which is equivalent to this one 2527 * with the decimal point moved {@code n} places to the left. If 2528 * {@code n} is non-negative, the call merely adds {@code n} to 2529 * the scale. If {@code n} is negative, the call is equivalent 2530 * to {@code movePointRight(-n)}. The {@code BigDecimal} 2531 * returned by this call has value <tt>(this × 2532 * 10<sup>-n</sup>)</tt> and scale {@code max(this.scale()+n, 2533 * 0)}. 2534 * 2535 * @param n number of places to move the decimal point to the left. 2536 * @return a {@code BigDecimal} which is equivalent to this one with the 2537 * decimal point moved {@code n} places to the left. 2538 * @throws ArithmeticException if scale overflows. 2539 */ 2540 public BigDecimal movePointLeft(int n) { 2541 // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE 2542 int newScale = checkScale((long)scale + n); 2543 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2544 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2545 } 2546 2547 /** 2548 * Returns a {@code BigDecimal} which is equivalent to this one 2549 * with the decimal point moved {@code n} places to the right. 2550 * If {@code n} is non-negative, the call merely subtracts 2551 * {@code n} from the scale. If {@code n} is negative, the call 2552 * is equivalent to {@code movePointLeft(-n)}. The 2553 * {@code BigDecimal} returned by this call has value <tt>(this 2554 * × 10<sup>n</sup>)</tt> and scale {@code max(this.scale()-n, 2555 * 0)}. 2556 * 2557 * @param n number of places to move the decimal point to the right. 2558 * @return a {@code BigDecimal} which is equivalent to this one 2559 * with the decimal point moved {@code n} places to the right. 2560 * @throws ArithmeticException if scale overflows. 2561 */ 2562 public BigDecimal movePointRight(int n) { 2563 // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE 2564 int newScale = checkScale((long)scale - n); 2565 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2566 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2567 } 2568 2569 /** 2570 * Returns a BigDecimal whose numerical value is equal to 2571 * ({@code this} * 10<sup>n</sup>). The scale of 2572 * the result is {@code (this.scale() - n)}. 2573 * 2574 * @throws ArithmeticException if the scale would be 2575 * outside the range of a 32-bit integer. 2576 * 2577 * @since 1.5 2578 */ 2579 public BigDecimal scaleByPowerOfTen(int n) { 2580 return new BigDecimal(intVal, intCompact, 2581 checkScale((long)scale - n), precision); 2582 } 2583 2584 /** 2585 * Returns a {@code BigDecimal} which is numerically equal to 2586 * this one but with any trailing zeros removed from the 2587 * representation. For example, stripping the trailing zeros from 2588 * the {@code BigDecimal} value {@code 600.0}, which has 2589 * [{@code BigInteger}, {@code scale}] components equals to 2590 * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, 2591 * {@code scale}] components equals to [6, -2] 2592 * 2593 * @return a numerically equal {@code BigDecimal} with any 2594 * trailing zeros removed. 2595 * @since 1.5 2596 */ 2597 public BigDecimal stripTrailingZeros() { 2598 if(intCompact!=INFLATED) { 2599 return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE); 2600 } else { 2601 return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE); 2602 } 2603 } 2604 2605 // Comparison Operations 2606 2607 /** 2608 * Compares this {@code BigDecimal} with the specified 2609 * {@code BigDecimal}. Two {@code BigDecimal} objects that are 2610 * equal in value but have a different scale (like 2.0 and 2.00) 2611 * are considered equal by this method. This method is provided 2612 * in preference to individual methods for each of the six boolean 2613 * comparison operators ({@literal <}, ==, 2614 * {@literal >}, {@literal >=}, !=, {@literal <=}). The 2615 * suggested idiom for performing these comparisons is: 2616 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 2617 * <<i>op</i>> is one of the six comparison operators. 2618 * 2619 * @param val {@code BigDecimal} to which this {@code BigDecimal} is 2620 * to be compared. 2621 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically 2622 * less than, equal to, or greater than {@code val}. 2623 */ 2624 public int compareTo(BigDecimal val) { 2625 // Quick path for equal scale and non-inflated case. 2626 if (scale == val.scale) { 2627 long xs = intCompact; 2628 long ys = val.intCompact; 2629 if (xs != INFLATED && ys != INFLATED) 2630 return xs != ys ? ((xs > ys) ? 1 : -1) : 0; 2631 } 2632 int xsign = this.signum(); 2633 int ysign = val.signum(); 2634 if (xsign != ysign) 2635 return (xsign > ysign) ? 1 : -1; 2636 if (xsign == 0) 2637 return 0; 2638 int cmp = compareMagnitude(val); 2639 return (xsign > 0) ? cmp : -cmp; 2640 } 2641 2642 /** 2643 * Version of compareTo that ignores sign. 2644 */ 2645 private int compareMagnitude(BigDecimal val) { 2646 // Match scales, avoid unnecessary inflation 2647 long ys = val.intCompact; 2648 long xs = this.intCompact; 2649 if (xs == 0) 2650 return (ys == 0) ? 0 : -1; 2651 if (ys == 0) 2652 return 1; 2653 2654 int sdiff = this.scale - val.scale; 2655 if (sdiff != 0) { 2656 // Avoid matching scales if the (adjusted) exponents differ 2657 int xae = this.precision() - this.scale; // [-1] 2658 int yae = val.precision() - val.scale; // [-1] 2659 if (xae < yae) 2660 return -1; 2661 if (xae > yae) 2662 return 1; 2663 BigInteger rb = null; 2664 if (sdiff < 0) { 2665 if ( (xs == INFLATED || 2666 (xs = longMultiplyPowerTen(xs, -sdiff)) == INFLATED) && 2667 ys == INFLATED) { 2668 rb = bigMultiplyPowerTen(-sdiff); 2669 return rb.compareMagnitude(val.intVal); 2670 } 2671 } else { // sdiff > 0 2672 if ( (ys == INFLATED || 2673 (ys = longMultiplyPowerTen(ys, sdiff)) == INFLATED) && 2674 xs == INFLATED) { 2675 rb = val.bigMultiplyPowerTen(sdiff); 2676 return this.intVal.compareMagnitude(rb); 2677 } 2678 } 2679 } 2680 if (xs != INFLATED) 2681 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; 2682 else if (ys != INFLATED) 2683 return 1; 2684 else 2685 return this.intVal.compareMagnitude(val.intVal); 2686 } 2687 2688 /** 2689 * Compares this {@code BigDecimal} with the specified 2690 * {@code Object} for equality. Unlike {@link 2691 * #compareTo(BigDecimal) compareTo}, this method considers two 2692 * {@code BigDecimal} objects equal only if they are equal in 2693 * value and scale (thus 2.0 is not equal to 2.00 when compared by 2694 * this method). 2695 * 2696 * @param x {@code Object} to which this {@code BigDecimal} is 2697 * to be compared. 2698 * @return {@code true} if and only if the specified {@code Object} is a 2699 * {@code BigDecimal} whose value and scale are equal to this 2700 * {@code BigDecimal}'s. 2701 * @see #compareTo(java.math.BigDecimal) 2702 * @see #hashCode 2703 */ 2704 @Override 2705 public boolean equals(Object x) { 2706 if (!(x instanceof BigDecimal)) 2707 return false; 2708 BigDecimal xDec = (BigDecimal) x; 2709 if (x == this) 2710 return true; 2711 if (scale != xDec.scale) 2712 return false; 2713 long s = this.intCompact; 2714 long xs = xDec.intCompact; 2715 if (s != INFLATED) { 2716 if (xs == INFLATED) 2717 xs = compactValFor(xDec.intVal); 2718 return xs == s; 2719 } else if (xs != INFLATED) 2720 return xs == compactValFor(this.intVal); 2721 2722 return this.inflated().equals(xDec.inflated()); 2723 } 2724 2725 /** 2726 * Returns the minimum of this {@code BigDecimal} and 2727 * {@code val}. 2728 * 2729 * @param val value with which the minimum is to be computed. 2730 * @return the {@code BigDecimal} whose value is the lesser of this 2731 * {@code BigDecimal} and {@code val}. If they are equal, 2732 * as defined by the {@link #compareTo(BigDecimal) compareTo} 2733 * method, {@code this} is returned. 2734 * @see #compareTo(java.math.BigDecimal) 2735 */ 2736 public BigDecimal min(BigDecimal val) { 2737 return (compareTo(val) <= 0 ? this : val); 2738 } 2739 2740 /** 2741 * Returns the maximum of this {@code BigDecimal} and {@code val}. 2742 * 2743 * @param val value with which the maximum is to be computed. 2744 * @return the {@code BigDecimal} whose value is the greater of this 2745 * {@code BigDecimal} and {@code val}. If they are equal, 2746 * as defined by the {@link #compareTo(BigDecimal) compareTo} 2747 * method, {@code this} is returned. 2748 * @see #compareTo(java.math.BigDecimal) 2749 */ 2750 public BigDecimal max(BigDecimal val) { 2751 return (compareTo(val) >= 0 ? this : val); 2752 } 2753 2754 // Hash Function 2755 2756 /** 2757 * Returns the hash code for this {@code BigDecimal}. Note that 2758 * two {@code BigDecimal} objects that are numerically equal but 2759 * differ in scale (like 2.0 and 2.00) will generally <i>not</i> 2760 * have the same hash code. 2761 * 2762 * @return hash code for this {@code BigDecimal}. 2763 * @see #equals(Object) 2764 */ 2765 @Override 2766 public int hashCode() { 2767 if (intCompact != INFLATED) { 2768 long val2 = (intCompact < 0)? -intCompact : intCompact; 2769 int temp = (int)( ((int)(val2 >>> 32)) * 31 + 2770 (val2 & LONG_MASK)); 2771 return 31*((intCompact < 0) ?-temp:temp) + scale; 2772 } else 2773 return 31*intVal.hashCode() + scale; 2774 } 2775 2776 // Format Converters 2777 2778 /** 2779 * Returns the string representation of this {@code BigDecimal}, 2780 * using scientific notation if an exponent is needed. 2781 * 2782 * <p>A standard canonical string form of the {@code BigDecimal} 2783 * is created as though by the following steps: first, the 2784 * absolute value of the unscaled value of the {@code BigDecimal} 2785 * is converted to a string in base ten using the characters 2786 * {@code '0'} through {@code '9'} with no leading zeros (except 2787 * if its value is zero, in which case a single {@code '0'} 2788 * character is used). 2789 * 2790 * <p>Next, an <i>adjusted exponent</i> is calculated; this is the 2791 * negated scale, plus the number of characters in the converted 2792 * unscaled value, less one. That is, 2793 * {@code -scale+(ulength-1)}, where {@code ulength} is the 2794 * length of the absolute value of the unscaled value in decimal 2795 * digits (its <i>precision</i>). 2796 * 2797 * <p>If the scale is greater than or equal to zero and the 2798 * adjusted exponent is greater than or equal to {@code -6}, the 2799 * number will be converted to a character form without using 2800 * exponential notation. In this case, if the scale is zero then 2801 * no decimal point is added and if the scale is positive a 2802 * decimal point will be inserted with the scale specifying the 2803 * number of characters to the right of the decimal point. 2804 * {@code '0'} characters are added to the left of the converted 2805 * unscaled value as necessary. If no character precedes the 2806 * decimal point after this insertion then a conventional 2807 * {@code '0'} character is prefixed. 2808 * 2809 * <p>Otherwise (that is, if the scale is negative, or the 2810 * adjusted exponent is less than {@code -6}), the number will be 2811 * converted to a character form using exponential notation. In 2812 * this case, if the converted {@code BigInteger} has more than 2813 * one digit a decimal point is inserted after the first digit. 2814 * An exponent in character form is then suffixed to the converted 2815 * unscaled value (perhaps with inserted decimal point); this 2816 * comprises the letter {@code 'E'} followed immediately by the 2817 * adjusted exponent converted to a character form. The latter is 2818 * in base ten, using the characters {@code '0'} through 2819 * {@code '9'} with no leading zeros, and is always prefixed by a 2820 * sign character {@code '-'} (<tt>'\u002D'</tt>) if the 2821 * adjusted exponent is negative, {@code '+'} 2822 * (<tt>'\u002B'</tt>) otherwise). 2823 * 2824 * <p>Finally, the entire string is prefixed by a minus sign 2825 * character {@code '-'} (<tt>'\u002D'</tt>) if the unscaled 2826 * value is less than zero. No sign character is prefixed if the 2827 * unscaled value is zero or positive. 2828 * 2829 * <p><b>Examples:</b> 2830 * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] 2831 * on the left, the resulting string is shown on the right. 2832 * <pre> 2833 * [123,0] "123" 2834 * [-123,0] "-123" 2835 * [123,-1] "1.23E+3" 2836 * [123,-3] "1.23E+5" 2837 * [123,1] "12.3" 2838 * [123,5] "0.00123" 2839 * [123,10] "1.23E-8" 2840 * [-123,12] "-1.23E-10" 2841 * </pre> 2842 * 2843 * <b>Notes:</b> 2844 * <ol> 2845 * 2846 * <li>There is a one-to-one mapping between the distinguishable 2847 * {@code BigDecimal} values and the result of this conversion. 2848 * That is, every distinguishable {@code BigDecimal} value 2849 * (unscaled value and scale) has a unique string representation 2850 * as a result of using {@code toString}. If that string 2851 * representation is converted back to a {@code BigDecimal} using 2852 * the {@link #BigDecimal(String)} constructor, then the original 2853 * value will be recovered. 2854 * 2855 * <li>The string produced for a given number is always the same; 2856 * it is not affected by locale. This means that it can be used 2857 * as a canonical string representation for exchanging decimal 2858 * data, or as a key for a Hashtable, etc. Locale-sensitive 2859 * number formatting and parsing is handled by the {@link 2860 * java.text.NumberFormat} class and its subclasses. 2861 * 2862 * <li>The {@link #toEngineeringString} method may be used for 2863 * presenting numbers with exponents in engineering notation, and the 2864 * {@link #setScale(int,RoundingMode) setScale} method may be used for 2865 * rounding a {@code BigDecimal} so it has a known number of digits after 2866 * the decimal point. 2867 * 2868 * <li>The digit-to-character mapping provided by 2869 * {@code Character.forDigit} is used. 2870 * 2871 * </ol> 2872 * 2873 * @return string representation of this {@code BigDecimal}. 2874 * @see Character#forDigit 2875 * @see #BigDecimal(java.lang.String) 2876 */ 2877 @Override 2878 public String toString() { 2879 String sc = stringCache; 2880 if (sc == null) 2881 stringCache = sc = layoutChars(true); 2882 return sc; 2883 } 2884 2885 /** 2886 * Returns a string representation of this {@code BigDecimal}, 2887 * using engineering notation if an exponent is needed. 2888 * 2889 * <p>Returns a string that represents the {@code BigDecimal} as 2890 * described in the {@link #toString()} method, except that if 2891 * exponential notation is used, the power of ten is adjusted to 2892 * be a multiple of three (engineering notation) such that the 2893 * integer part of nonzero values will be in the range 1 through 2894 * 999. If exponential notation is used for zero values, a 2895 * decimal point and one or two fractional zero digits are used so 2896 * that the scale of the zero value is preserved. Note that 2897 * unlike the output of {@link #toString()}, the output of this 2898 * method is <em>not</em> guaranteed to recover the same [integer, 2899 * scale] pair of this {@code BigDecimal} if the output string is 2900 * converting back to a {@code BigDecimal} using the {@linkplain 2901 * #BigDecimal(String) string constructor}. The result of this method meets 2902 * the weaker constraint of always producing a numerically equal 2903 * result from applying the string constructor to the method's output. 2904 * 2905 * @return string representation of this {@code BigDecimal}, using 2906 * engineering notation if an exponent is needed. 2907 * @since 1.5 2908 */ 2909 public String toEngineeringString() { 2910 return layoutChars(false); 2911 } 2912 2913 /** 2914 * Returns a string representation of this {@code BigDecimal} 2915 * without an exponent field. For values with a positive scale, 2916 * the number of digits to the right of the decimal point is used 2917 * to indicate scale. For values with a zero or negative scale, 2918 * the resulting string is generated as if the value were 2919 * converted to a numerically equal value with zero scale and as 2920 * if all the trailing zeros of the zero scale value were present 2921 * in the result. 2922 * 2923 * The entire string is prefixed by a minus sign character '-' 2924 * (<tt>'\u002D'</tt>) if the unscaled value is less than 2925 * zero. No sign character is prefixed if the unscaled value is 2926 * zero or positive. 2927 * 2928 * Note that if the result of this method is passed to the 2929 * {@linkplain #BigDecimal(String) string constructor}, only the 2930 * numerical value of this {@code BigDecimal} will necessarily be 2931 * recovered; the representation of the new {@code BigDecimal} 2932 * may have a different scale. In particular, if this 2933 * {@code BigDecimal} has a negative scale, the string resulting 2934 * from this method will have a scale of zero when processed by 2935 * the string constructor. 2936 * 2937 * (This method behaves analogously to the {@code toString} 2938 * method in 1.4 and earlier releases.) 2939 * 2940 * @return a string representation of this {@code BigDecimal} 2941 * without an exponent field. 2942 * @since 1.5 2943 * @see #toString() 2944 * @see #toEngineeringString() 2945 */ 2946 public String toPlainString() { 2947 if(scale==0) { 2948 if(intCompact!=INFLATED) { 2949 return Long.toString(intCompact); 2950 } else { 2951 return intVal.toString(); 2952 } 2953 } 2954 if(this.scale<0) { // No decimal point 2955 if(signum()==0) { 2956 return "0"; 2957 } 2958 int tailingZeros = checkScaleNonZero((-(long)scale)); 2959 StringBuilder buf; 2960 if(intCompact!=INFLATED) { 2961 buf = new StringBuilder(20+tailingZeros); 2962 buf.append(intCompact); 2963 } else { 2964 String str = intVal.toString(); 2965 buf = new StringBuilder(str.length()+tailingZeros); 2966 buf.append(str); 2967 } 2968 for (int i = 0; i < tailingZeros; i++) 2969 buf.append('0'); 2970 return buf.toString(); 2971 } 2972 String str ; 2973 if(intCompact!=INFLATED) { 2974 str = Long.toString(Math.abs(intCompact)); 2975 } else { 2976 str = intVal.abs().toString(); 2977 } 2978 return getValueString(signum(), str, scale); 2979 } 2980 2981 /* Returns a digit.digit string */ 2982 private String getValueString(int signum, String intString, int scale) { 2983 /* Insert decimal point */ 2984 StringBuilder buf; 2985 int insertionPoint = intString.length() - scale; 2986 if (insertionPoint == 0) { /* Point goes right before intVal */ 2987 return (signum<0 ? "-0." : "0.") + intString; 2988 } else if (insertionPoint > 0) { /* Point goes inside intVal */ 2989 buf = new StringBuilder(intString); 2990 buf.insert(insertionPoint, '.'); 2991 if (signum < 0) 2992 buf.insert(0, '-'); 2993 } else { /* We must insert zeros between point and intVal */ 2994 buf = new StringBuilder(3-insertionPoint + intString.length()); 2995 buf.append(signum<0 ? "-0." : "0."); 2996 for (int i=0; i<-insertionPoint; i++) 2997 buf.append('0'); 2998 buf.append(intString); 2999 } 3000 return buf.toString(); 3001 } 3002 3003 /** 3004 * Converts this {@code BigDecimal} to a {@code BigInteger}. 3005 * This conversion is analogous to the 3006 * <i>narrowing primitive conversion</i> from {@code double} to 3007 * {@code long} as defined in section 5.1.3 of 3008 * <cite>The Java™ Language Specification</cite>: 3009 * any fractional part of this 3010 * {@code BigDecimal} will be discarded. Note that this 3011 * conversion can lose information about the precision of the 3012 * {@code BigDecimal} value. 3013 * <p> 3014 * To have an exception thrown if the conversion is inexact (in 3015 * other words if a nonzero fractional part is discarded), use the 3016 * {@link #toBigIntegerExact()} method. 3017 * 3018 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 3019 */ 3020 public BigInteger toBigInteger() { 3021 // force to an integer, quietly 3022 return this.setScale(0, ROUND_DOWN).inflated(); 3023 } 3024 3025 /** 3026 * Converts this {@code BigDecimal} to a {@code BigInteger}, 3027 * checking for lost information. An exception is thrown if this 3028 * {@code BigDecimal} has a nonzero fractional part. 3029 * 3030 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 3031 * @throws ArithmeticException if {@code this} has a nonzero 3032 * fractional part. 3033 * @since 1.5 3034 */ 3035 public BigInteger toBigIntegerExact() { 3036 // round to an integer, with Exception if decimal part non-0 3037 return this.setScale(0, ROUND_UNNECESSARY).inflated(); 3038 } 3039 3040 /** 3041 * Converts this {@code BigDecimal} to a {@code long}. 3042 * This conversion is analogous to the 3043 * <i>narrowing primitive conversion</i> from {@code double} to 3044 * {@code short} as defined in section 5.1.3 of 3045 * <cite>The Java™ Language Specification</cite>: 3046 * any fractional part of this 3047 * {@code BigDecimal} will be discarded, and if the resulting 3048 * "{@code BigInteger}" is too big to fit in a 3049 * {@code long}, only the low-order 64 bits are returned. 3050 * Note that this conversion can lose information about the 3051 * overall magnitude and precision of this {@code BigDecimal} value as well 3052 * as return a result with the opposite sign. 3053 * 3054 * @return this {@code BigDecimal} converted to a {@code long}. 3055 */ 3056 public long longValue(){ 3057 return (intCompact != INFLATED && scale == 0) ? 3058 intCompact: 3059 toBigInteger().longValue(); 3060 } 3061 3062 /** 3063 * Converts this {@code BigDecimal} to a {@code long}, checking 3064 * for lost information. If this {@code BigDecimal} has a 3065 * nonzero fractional part or is out of the possible range for a 3066 * {@code long} result then an {@code ArithmeticException} is 3067 * thrown. 3068 * 3069 * @return this {@code BigDecimal} converted to a {@code long}. 3070 * @throws ArithmeticException if {@code this} has a nonzero 3071 * fractional part, or will not fit in a {@code long}. 3072 * @since 1.5 3073 */ 3074 public long longValueExact() { 3075 if (intCompact != INFLATED && scale == 0) 3076 return intCompact; 3077 // If more than 19 digits in integer part it cannot possibly fit 3078 if ((precision() - scale) > 19) // [OK for negative scale too] 3079 throw new java.lang.ArithmeticException("Overflow"); 3080 // Fastpath zero and < 1.0 numbers (the latter can be very slow 3081 // to round if very small) 3082 if (this.signum() == 0) 3083 return 0; 3084 if ((this.precision() - this.scale) <= 0) 3085 throw new ArithmeticException("Rounding necessary"); 3086 // round to an integer, with Exception if decimal part non-0 3087 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); 3088 if (num.precision() >= 19) // need to check carefully 3089 LongOverflow.check(num); 3090 return num.inflated().longValue(); 3091 } 3092 3093 private static class LongOverflow { 3094 /** BigInteger equal to Long.MIN_VALUE. */ 3095 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE); 3096 3097 /** BigInteger equal to Long.MAX_VALUE. */ 3098 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE); 3099 3100 public static void check(BigDecimal num) { 3101 BigInteger intVal = num.inflated(); 3102 if (intVal.compareTo(LONGMIN) < 0 || 3103 intVal.compareTo(LONGMAX) > 0) 3104 throw new java.lang.ArithmeticException("Overflow"); 3105 } 3106 } 3107 3108 /** 3109 * Converts this {@code BigDecimal} to an {@code int}. 3110 * This conversion is analogous to the 3111 * <i>narrowing primitive conversion</i> from {@code double} to 3112 * {@code short} as defined in section 5.1.3 of 3113 * <cite>The Java™ Language Specification</cite>: 3114 * any fractional part of this 3115 * {@code BigDecimal} will be discarded, and if the resulting 3116 * "{@code BigInteger}" is too big to fit in an 3117 * {@code int}, only the low-order 32 bits are returned. 3118 * Note that this conversion can lose information about the 3119 * overall magnitude and precision of this {@code BigDecimal} 3120 * value as well as return a result with the opposite sign. 3121 * 3122 * @return this {@code BigDecimal} converted to an {@code int}. 3123 */ 3124 public int intValue() { 3125 return (intCompact != INFLATED && scale == 0) ? 3126 (int)intCompact : 3127 toBigInteger().intValue(); 3128 } 3129 3130 /** 3131 * Converts this {@code BigDecimal} to an {@code int}, checking 3132 * for lost information. If this {@code BigDecimal} has a 3133 * nonzero fractional part or is out of the possible range for an 3134 * {@code int} result then an {@code ArithmeticException} is 3135 * thrown. 3136 * 3137 * @return this {@code BigDecimal} converted to an {@code int}. 3138 * @throws ArithmeticException if {@code this} has a nonzero 3139 * fractional part, or will not fit in an {@code int}. 3140 * @since 1.5 3141 */ 3142 public int intValueExact() { 3143 long num; 3144 num = this.longValueExact(); // will check decimal part 3145 if ((int)num != num) 3146 throw new java.lang.ArithmeticException("Overflow"); 3147 return (int)num; 3148 } 3149 3150 /** 3151 * Converts this {@code BigDecimal} to a {@code short}, checking 3152 * for lost information. If this {@code BigDecimal} has a 3153 * nonzero fractional part or is out of the possible range for a 3154 * {@code short} result then an {@code ArithmeticException} is 3155 * thrown. 3156 * 3157 * @return this {@code BigDecimal} converted to a {@code short}. 3158 * @throws ArithmeticException if {@code this} has a nonzero 3159 * fractional part, or will not fit in a {@code short}. 3160 * @since 1.5 3161 */ 3162 public short shortValueExact() { 3163 long num; 3164 num = this.longValueExact(); // will check decimal part 3165 if ((short)num != num) 3166 throw new java.lang.ArithmeticException("Overflow"); 3167 return (short)num; 3168 } 3169 3170 /** 3171 * Converts this {@code BigDecimal} to a {@code byte}, checking 3172 * for lost information. If this {@code BigDecimal} has a 3173 * nonzero fractional part or is out of the possible range for a 3174 * {@code byte} result then an {@code ArithmeticException} is 3175 * thrown. 3176 * 3177 * @return this {@code BigDecimal} converted to a {@code byte}. 3178 * @throws ArithmeticException if {@code this} has a nonzero 3179 * fractional part, or will not fit in a {@code byte}. 3180 * @since 1.5 3181 */ 3182 public byte byteValueExact() { 3183 long num; 3184 num = this.longValueExact(); // will check decimal part 3185 if ((byte)num != num) 3186 throw new java.lang.ArithmeticException("Overflow"); 3187 return (byte)num; 3188 } 3189 3190 /** 3191 * Converts this {@code BigDecimal} to a {@code float}. 3192 * This conversion is similar to the 3193 * <i>narrowing primitive conversion</i> from {@code double} to 3194 * {@code float} as defined in section 5.1.3 of 3195 * <cite>The Java™ Language Specification</cite>: 3196 * if this {@code BigDecimal} has too great a 3197 * magnitude to represent as a {@code float}, it will be 3198 * converted to {@link Float#NEGATIVE_INFINITY} or {@link 3199 * Float#POSITIVE_INFINITY} as appropriate. Note that even when 3200 * the return value is finite, this conversion can lose 3201 * information about the precision of the {@code BigDecimal} 3202 * value. 3203 * 3204 * @return this {@code BigDecimal} converted to a {@code float}. 3205 */ 3206 public float floatValue(){ 3207 if(intCompact != INFLATED) { 3208 if (scale == 0) { 3209 return (float)intCompact; 3210 } else { 3211 /* 3212 * If both intCompact and the scale can be exactly 3213 * represented as float values, perform a single float 3214 * multiply or divide to compute the (properly 3215 * rounded) result. 3216 */ 3217 if (scale > 0 && scale < float10pow.length 3218 && intCompact > -1L<<22 && intCompact < 1L<<22) { 3219 return (float)intCompact / float10pow[scale]; 3220 } else if (scale < 0 && scale > -float10pow.length 3221 && intCompact > -1L<<22 && intCompact < 1L<<22) { 3222 return (float)intCompact * float10pow[-scale]; 3223 } 3224 } 3225 } 3226 // Somewhat inefficient, but guaranteed to work. 3227 return Float.parseFloat(this.toString()); 3228 } 3229 3230 /** 3231 * Converts this {@code BigDecimal} to a {@code double}. 3232 * This conversion is similar to the 3233 * <i>narrowing primitive conversion</i> from {@code double} to 3234 * {@code float} as defined in section 5.1.3 of 3235 * <cite>The Java™ Language Specification</cite>: 3236 * if this {@code BigDecimal} has too great a 3237 * magnitude represent as a {@code double}, it will be 3238 * converted to {@link Double#NEGATIVE_INFINITY} or {@link 3239 * Double#POSITIVE_INFINITY} as appropriate. Note that even when 3240 * the return value is finite, this conversion can lose 3241 * information about the precision of the {@code BigDecimal} 3242 * value. 3243 * 3244 * @return this {@code BigDecimal} converted to a {@code double}. 3245 */ 3246 public double doubleValue(){ 3247 if(intCompact != INFLATED) { 3248 if (scale == 0) { 3249 return (double)intCompact; 3250 } else { 3251 /* 3252 * If both intCompact and the scale can be exactly 3253 * represented as double values, perform a single 3254 * double multiply or divide to compute the (properly 3255 * rounded) result. 3256 */ 3257 if (scale > 0 && scale < double10pow.length 3258 && intCompact > -1L<<52 && intCompact < 1L<<52) { 3259 return (double)intCompact / double10pow[scale]; 3260 } else if (scale < 0 && scale > -double10pow.length 3261 && intCompact > -1L<<52 && intCompact < 1L<<52) { 3262 return (double)intCompact * double10pow[-scale]; 3263 } 3264 } 3265 } 3266 // Somewhat inefficient, but guaranteed to work. 3267 return Double.parseDouble(this.toString()); 3268 } 3269 3270 /** 3271 * Powers of 10 which can be represented exactly in {@code 3272 * double}. 3273 */ 3274 private static final double double10pow[] = { 3275 1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 3276 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11, 3277 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17, 3278 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22 3279 }; 3280 3281 /** 3282 * Powers of 10 which can be represented exactly in {@code 3283 * float}. 3284 */ 3285 private static final float float10pow[] = { 3286 1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f, 3287 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f 3288 }; 3289 3290 /** 3291 * Returns the size of an ulp, a unit in the last place, of this 3292 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} 3293 * value is the positive distance between this value and the 3294 * {@code BigDecimal} value next larger in magnitude with the 3295 * same number of digits. An ulp of a zero value is numerically 3296 * equal to 1 with the scale of {@code this}. The result is 3297 * stored with the same scale as {@code this} so the result 3298 * for zero and nonzero values is equal to {@code [1, 3299 * this.scale()]}. 3300 * 3301 * @return the size of an ulp of {@code this} 3302 * @since 1.5 3303 */ 3304 public BigDecimal ulp() { 3305 return BigDecimal.valueOf(1, this.scale(), 1); 3306 } 3307 3308 // Private class to build a string representation for BigDecimal object. 3309 // "StringBuilderHelper" is constructed as a thread local variable so it is 3310 // thread safe. The StringBuilder field acts as a buffer to hold the temporary 3311 // representation of BigDecimal. The cmpCharArray holds all the characters for 3312 // the compact representation of BigDecimal (except for '-' sign' if it is 3313 // negative) if its intCompact field is not INFLATED. It is shared by all 3314 // calls to toString() and its variants in that particular thread. 3315 static class StringBuilderHelper { 3316 final StringBuilder sb; // Placeholder for BigDecimal string 3317 final char[] cmpCharArray; // character array to place the intCompact 3318 3319 StringBuilderHelper() { 3320 sb = new StringBuilder(); 3321 // All non negative longs can be made to fit into 19 character array. 3322 cmpCharArray = new char[19]; 3323 } 3324 3325 // Accessors. 3326 StringBuilder getStringBuilder() { 3327 sb.setLength(0); 3328 return sb; 3329 } 3330 3331 char[] getCompactCharArray() { 3332 return cmpCharArray; 3333 } 3334 3335 /** 3336 * Places characters representing the intCompact in {@code long} into 3337 * cmpCharArray and returns the offset to the array where the 3338 * representation starts. 3339 * 3340 * @param intCompact the number to put into the cmpCharArray. 3341 * @return offset to the array where the representation starts. 3342 * Note: intCompact must be greater or equal to zero. 3343 */ 3344 int putIntCompact(long intCompact) { 3345 assert intCompact >= 0; 3346 3347 long q; 3348 int r; 3349 // since we start from the least significant digit, charPos points to 3350 // the last character in cmpCharArray. 3351 int charPos = cmpCharArray.length; 3352 3353 // Get 2 digits/iteration using longs until quotient fits into an int 3354 while (intCompact > Integer.MAX_VALUE) { 3355 q = intCompact / 100; 3356 r = (int)(intCompact - q * 100); 3357 intCompact = q; 3358 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3359 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3360 } 3361 3362 // Get 2 digits/iteration using ints when i2 >= 100 3363 int q2; 3364 int i2 = (int)intCompact; 3365 while (i2 >= 100) { 3366 q2 = i2 / 100; 3367 r = i2 - q2 * 100; 3368 i2 = q2; 3369 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3370 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3371 } 3372 3373 cmpCharArray[--charPos] = DIGIT_ONES[i2]; 3374 if (i2 >= 10) 3375 cmpCharArray[--charPos] = DIGIT_TENS[i2]; 3376 3377 return charPos; 3378 } 3379 3380 final static char[] DIGIT_TENS = { 3381 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 3382 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 3383 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 3384 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 3385 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 3386 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 3387 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 3388 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 3389 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 3390 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 3391 }; 3392 3393 final static char[] DIGIT_ONES = { 3394 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3395 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3396 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3397 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3398 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3399 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3400 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3401 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3402 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3403 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3404 }; 3405 } 3406 3407 /** 3408 * Lay out this {@code BigDecimal} into a {@code char[]} array. 3409 * The Java 1.2 equivalent to this was called {@code getValueString}. 3410 * 3411 * @param sci {@code true} for Scientific exponential notation; 3412 * {@code false} for Engineering 3413 * @return string with canonical string representation of this 3414 * {@code BigDecimal} 3415 */ 3416 private String layoutChars(boolean sci) { 3417 if (scale == 0) // zero scale is trivial 3418 return (intCompact != INFLATED) ? 3419 Long.toString(intCompact): 3420 intVal.toString(); 3421 if (scale == 2 && 3422 intCompact >= 0 && intCompact < Integer.MAX_VALUE) { 3423 // currency fast path 3424 int lowInt = (int)intCompact % 100; 3425 int highInt = (int)intCompact / 100; 3426 return (Integer.toString(highInt) + '.' + 3427 StringBuilderHelper.DIGIT_TENS[lowInt] + 3428 StringBuilderHelper.DIGIT_ONES[lowInt]) ; 3429 } 3430 3431 StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get(); 3432 char[] coeff; 3433 int offset; // offset is the starting index for coeff array 3434 // Get the significand as an absolute value 3435 if (intCompact != INFLATED) { 3436 offset = sbHelper.putIntCompact(Math.abs(intCompact)); 3437 coeff = sbHelper.getCompactCharArray(); 3438 } else { 3439 offset = 0; 3440 coeff = intVal.abs().toString().toCharArray(); 3441 } 3442 3443 // Construct a buffer, with sufficient capacity for all cases. 3444 // If E-notation is needed, length will be: +1 if negative, +1 3445 // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. 3446 // Otherwise it could have +1 if negative, plus leading "0.00000" 3447 StringBuilder buf = sbHelper.getStringBuilder(); 3448 if (signum() < 0) // prefix '-' if negative 3449 buf.append('-'); 3450 int coeffLen = coeff.length - offset; 3451 long adjusted = -(long)scale + (coeffLen -1); 3452 if ((scale >= 0) && (adjusted >= -6)) { // plain number 3453 int pad = scale - coeffLen; // count of padding zeros 3454 if (pad >= 0) { // 0.xxx form 3455 buf.append('0'); 3456 buf.append('.'); 3457 for (; pad>0; pad--) { 3458 buf.append('0'); 3459 } 3460 buf.append(coeff, offset, coeffLen); 3461 } else { // xx.xx form 3462 buf.append(coeff, offset, -pad); 3463 buf.append('.'); 3464 buf.append(coeff, -pad + offset, scale); 3465 } 3466 } else { // E-notation is needed 3467 if (sci) { // Scientific notation 3468 buf.append(coeff[offset]); // first character 3469 if (coeffLen > 1) { // more to come 3470 buf.append('.'); 3471 buf.append(coeff, offset + 1, coeffLen - 1); 3472 } 3473 } else { // Engineering notation 3474 int sig = (int)(adjusted % 3); 3475 if (sig < 0) 3476 sig += 3; // [adjusted was negative] 3477 adjusted -= sig; // now a multiple of 3 3478 sig++; 3479 if (signum() == 0) { 3480 switch (sig) { 3481 case 1: 3482 buf.append('0'); // exponent is a multiple of three 3483 break; 3484 case 2: 3485 buf.append("0.00"); 3486 adjusted += 3; 3487 break; 3488 case 3: 3489 buf.append("0.0"); 3490 adjusted += 3; 3491 break; 3492 default: 3493 throw new AssertionError("Unexpected sig value " + sig); 3494 } 3495 } else if (sig >= coeffLen) { // significand all in integer 3496 buf.append(coeff, offset, coeffLen); 3497 // may need some zeros, too 3498 for (int i = sig - coeffLen; i > 0; i--) 3499 buf.append('0'); 3500 } else { // xx.xxE form 3501 buf.append(coeff, offset, sig); 3502 buf.append('.'); 3503 buf.append(coeff, offset + sig, coeffLen - sig); 3504 } 3505 } 3506 if (adjusted != 0) { // [!sci could have made 0] 3507 buf.append('E'); 3508 if (adjusted > 0) // force sign for positive 3509 buf.append('+'); 3510 buf.append(adjusted); 3511 } 3512 } 3513 return buf.toString(); 3514 } 3515 3516 /** 3517 * Return 10 to the power n, as a {@code BigInteger}. 3518 * 3519 * @param n the power of ten to be returned (>=0) 3520 * @return a {@code BigInteger} with the value (10<sup>n</sup>) 3521 */ 3522 private static BigInteger bigTenToThe(int n) { 3523 if (n < 0) 3524 return BigInteger.ZERO; 3525 3526 if (n < BIG_TEN_POWERS_TABLE_MAX) { 3527 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3528 if (n < pows.length) 3529 return pows[n]; 3530 else 3531 return expandBigIntegerTenPowers(n); 3532 } 3533 // BigInteger.pow is slow, so make 10**n by constructing a 3534 // BigInteger from a character string (still not very fast) 3535 char tenpow[] = new char[n + 1]; 3536 tenpow[0] = '1'; 3537 for (int i = 1; i <= n; i++) 3538 tenpow[i] = '0'; 3539 return new BigInteger(tenpow,1, tenpow.length); 3540 } 3541 3542 /** 3543 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. 3544 * 3545 * @param n the power of ten to be returned (>=0) 3546 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and 3547 * in the meantime, the BIG_TEN_POWERS_TABLE array gets 3548 * expanded to the size greater than n. 3549 */ 3550 private static BigInteger expandBigIntegerTenPowers(int n) { 3551 synchronized(BigDecimal.class) { 3552 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3553 int curLen = pows.length; 3554 // The following comparison and the above synchronized statement is 3555 // to prevent multiple threads from expanding the same array. 3556 if (curLen <= n) { 3557 int newLen = curLen << 1; 3558 while (newLen <= n) 3559 newLen <<= 1; 3560 pows = Arrays.copyOf(pows, newLen); 3561 for (int i = curLen; i < newLen; i++) 3562 pows[i] = pows[i - 1].multiply(BigInteger.TEN); 3563 // Based on the following facts: 3564 // 1. pows is a private local varible; 3565 // 2. the following store is a volatile store. 3566 // the newly created array elements can be safely published. 3567 BIG_TEN_POWERS_TABLE = pows; 3568 } 3569 return pows[n]; 3570 } 3571 } 3572 3573 private static final long[] LONG_TEN_POWERS_TABLE = { 3574 1, // 0 / 10^0 3575 10, // 1 / 10^1 3576 100, // 2 / 10^2 3577 1000, // 3 / 10^3 3578 10000, // 4 / 10^4 3579 100000, // 5 / 10^5 3580 1000000, // 6 / 10^6 3581 10000000, // 7 / 10^7 3582 100000000, // 8 / 10^8 3583 1000000000, // 9 / 10^9 3584 10000000000L, // 10 / 10^10 3585 100000000000L, // 11 / 10^11 3586 1000000000000L, // 12 / 10^12 3587 10000000000000L, // 13 / 10^13 3588 100000000000000L, // 14 / 10^14 3589 1000000000000000L, // 15 / 10^15 3590 10000000000000000L, // 16 / 10^16 3591 100000000000000000L, // 17 / 10^17 3592 1000000000000000000L // 18 / 10^18 3593 }; 3594 3595 private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = { 3596 BigInteger.ONE, 3597 BigInteger.valueOf(10), 3598 BigInteger.valueOf(100), 3599 BigInteger.valueOf(1000), 3600 BigInteger.valueOf(10000), 3601 BigInteger.valueOf(100000), 3602 BigInteger.valueOf(1000000), 3603 BigInteger.valueOf(10000000), 3604 BigInteger.valueOf(100000000), 3605 BigInteger.valueOf(1000000000), 3606 BigInteger.valueOf(10000000000L), 3607 BigInteger.valueOf(100000000000L), 3608 BigInteger.valueOf(1000000000000L), 3609 BigInteger.valueOf(10000000000000L), 3610 BigInteger.valueOf(100000000000000L), 3611 BigInteger.valueOf(1000000000000000L), 3612 BigInteger.valueOf(10000000000000000L), 3613 BigInteger.valueOf(100000000000000000L), 3614 BigInteger.valueOf(1000000000000000000L) 3615 }; 3616 3617 private static final int BIG_TEN_POWERS_TABLE_INITLEN = 3618 BIG_TEN_POWERS_TABLE.length; 3619 private static final int BIG_TEN_POWERS_TABLE_MAX = 3620 16 * BIG_TEN_POWERS_TABLE_INITLEN; 3621 3622 private static final long THRESHOLDS_TABLE[] = { 3623 Long.MAX_VALUE, // 0 3624 Long.MAX_VALUE/10L, // 1 3625 Long.MAX_VALUE/100L, // 2 3626 Long.MAX_VALUE/1000L, // 3 3627 Long.MAX_VALUE/10000L, // 4 3628 Long.MAX_VALUE/100000L, // 5 3629 Long.MAX_VALUE/1000000L, // 6 3630 Long.MAX_VALUE/10000000L, // 7 3631 Long.MAX_VALUE/100000000L, // 8 3632 Long.MAX_VALUE/1000000000L, // 9 3633 Long.MAX_VALUE/10000000000L, // 10 3634 Long.MAX_VALUE/100000000000L, // 11 3635 Long.MAX_VALUE/1000000000000L, // 12 3636 Long.MAX_VALUE/10000000000000L, // 13 3637 Long.MAX_VALUE/100000000000000L, // 14 3638 Long.MAX_VALUE/1000000000000000L, // 15 3639 Long.MAX_VALUE/10000000000000000L, // 16 3640 Long.MAX_VALUE/100000000000000000L, // 17 3641 Long.MAX_VALUE/1000000000000000000L // 18 3642 }; 3643 3644 /** 3645 * Compute val * 10 ^ n; return this product if it is 3646 * representable as a long, INFLATED otherwise. 3647 */ 3648 private static long longMultiplyPowerTen(long val, int n) { 3649 if (val == 0 || n <= 0) 3650 return val; 3651 long[] tab = LONG_TEN_POWERS_TABLE; 3652 long[] bounds = THRESHOLDS_TABLE; 3653 if (n < tab.length && n < bounds.length) { 3654 long tenpower = tab[n]; 3655 if (val == 1) 3656 return tenpower; 3657 if (Math.abs(val) <= bounds[n]) 3658 return val * tenpower; 3659 } 3660 return INFLATED; 3661 } 3662 3663 /** 3664 * Compute this * 10 ^ n. 3665 * Needed mainly to allow special casing to trap zero value 3666 */ 3667 private BigInteger bigMultiplyPowerTen(int n) { 3668 if (n <= 0) 3669 return this.inflated(); 3670 3671 if (intCompact != INFLATED) 3672 return bigTenToThe(n).multiply(intCompact); 3673 else 3674 return intVal.multiply(bigTenToThe(n)); 3675 } 3676 3677 /** 3678 * Returns appropriate BigInteger from intVal field if intVal is 3679 * null, i.e. the compact representation is in use. 3680 */ 3681 private BigInteger inflated() { 3682 if (intVal == null) { 3683 return BigInteger.valueOf(intCompact); 3684 } 3685 return intVal; 3686 } 3687 3688 /** 3689 * Match the scales of two {@code BigDecimal}s to align their 3690 * least significant digits. 3691 * 3692 * <p>If the scales of val[0] and val[1] differ, rescale 3693 * (non-destructively) the lower-scaled {@code BigDecimal} so 3694 * they match. That is, the lower-scaled reference will be 3695 * replaced by a reference to a new object with the same scale as 3696 * the other {@code BigDecimal}. 3697 * 3698 * @param val array of two elements referring to the two 3699 * {@code BigDecimal}s to be aligned. 3700 */ 3701 private static void matchScale(BigDecimal[] val) { 3702 if (val[0].scale == val[1].scale) { 3703 return; 3704 } else if (val[0].scale < val[1].scale) { 3705 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY); 3706 } else if (val[1].scale < val[0].scale) { 3707 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY); 3708 } 3709 } 3710 3711 private static final sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe(); 3712 private static final long intCompactOffset; 3713 private static final long intValOffset; 3714 static { 3715 try { 3716 intCompactOffset = unsafe.objectFieldOffset 3717 (BigDecimal.class.getDeclaredField("intCompact")); 3718 intValOffset = unsafe.objectFieldOffset 3719 (BigDecimal.class.getDeclaredField("intVal")); 3720 } catch (Exception ex) { 3721 throw new Error(ex); 3722 } 3723 } 3724 3725 private void setIntCompactVolatile(long val) { 3726 unsafe.putLongVolatile(this, intCompactOffset, val); 3727 } 3728 3729 private void setIntValVolatile(BigInteger val) { 3730 unsafe.putObjectVolatile(this, intValOffset, val); 3731 } 3732 3733 /** 3734 * Reconstitute the {@code BigDecimal} instance from a stream (that is, 3735 * deserialize it). 3736 * 3737 * @param s the stream being read. 3738 */ 3739 private void readObject(java.io.ObjectInputStream s) 3740 throws java.io.IOException, ClassNotFoundException { 3741 // Read in all fields 3742 s.defaultReadObject(); 3743 // validate possibly bad fields 3744 if (intVal == null) { 3745 String message = "BigDecimal: null intVal in stream"; 3746 throw new java.io.StreamCorruptedException(message); 3747 // [all values of scale are now allowed] 3748 } 3749 setIntCompactVolatile(compactValFor(intVal)); 3750 } 3751 3752 /** 3753 * Serialize this {@code BigDecimal} to the stream in question 3754 * 3755 * @param s the stream to serialize to. 3756 */ 3757 private void writeObject(java.io.ObjectOutputStream s) 3758 throws java.io.IOException { 3759 // Must inflate to maintain compatible serial form. 3760 if (this.intVal == null) 3761 this.setIntValVolatile(BigInteger.valueOf(this.intCompact)); 3762 s.defaultWriteObject(); 3763 } 3764 3765 /** 3766 * Returns the length of the absolute value of a {@code long}, in decimal 3767 * digits. 3768 * 3769 * @param x 3770 * the {@code long} 3771 * @return the length of the unscaled value, in deciaml digits. 3772 */ 3773 static int longDigitLength(long x) { 3774 /* 3775 * As described in "Bit Twiddling Hacks" by Sean Anderson, 3776 * (http://graphics.stanford.edu/~seander/bithacks.html) integer log 10 3777 * of x is within 1 of (1233/4096)* (1 + integer log 2 of x). The 3778 * fraction 1233/4096 approximates log10(2). So we first do a version of 3779 * log2 (a variant of Long class with pre-checks and opposite 3780 * directionality) and then scale and check against powers table. This 3781 * is a little simpler in present context than the version in Hacker's 3782 * Delight sec 11-4. Adding one to bit length allows comparing downward 3783 * from the LONG_TEN_POWERS_TABLE that we need anyway. 3784 */ 3785 assert x != BigDecimal.INFLATED; 3786 if (x < 0) 3787 x = -x; 3788 if (x < 10) // must screen for 0, might as well 10 3789 return 1; 3790 int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12; 3791 long[] tab = LONG_TEN_POWERS_TABLE; 3792 // if r >= length, must have max possible digits for long 3793 return (r >= tab.length || x < tab[r]) ? r : r + 1; 3794 } 3795 3796 /** 3797 * Returns the length of the absolute value of a BigInteger, in 3798 * decimal digits. 3799 * 3800 * @param b the BigInteger 3801 * @return the length of the unscaled value, in decimal digits 3802 */ 3803 private static int bigDigitLength(BigInteger b) { 3804 /* 3805 * Same idea as the long version, but we need a better 3806 * approximation of log10(2). Using 646456993/2^31 3807 * is accurate up to max possible reported bitLength. 3808 */ 3809 if (b.signum == 0) 3810 return 1; 3811 int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31); 3812 return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1; 3813 } 3814 3815 /** 3816 * Check a scale for Underflow or Overflow. If this BigDecimal is 3817 * nonzero, throw an exception if the scale is outof range. If this 3818 * is zero, saturate the scale to the extreme value of the right 3819 * sign if the scale is out of range. 3820 * 3821 * @param val The new scale. 3822 * @throws ArithmeticException (overflow or underflow) if the new 3823 * scale is out of range. 3824 * @return validated scale as an int. 3825 */ 3826 private int checkScale(long val) { 3827 int asInt = (int)val; 3828 if (asInt != val) { 3829 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 3830 BigInteger b; 3831 if (intCompact != 0 && 3832 ((b = intVal) == null || b.signum() != 0)) 3833 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 3834 } 3835 return asInt; 3836 } 3837 3838 /** 3839 * Returns the compact value for given {@code BigInteger}, or 3840 * INFLATED if too big. Relies on internal representation of 3841 * {@code BigInteger}. 3842 */ 3843 private static long compactValFor(BigInteger b) { 3844 int[] m = b.mag; 3845 int len = m.length; 3846 if (len == 0) 3847 return 0; 3848 int d = m[0]; 3849 if (len > 2 || (len == 2 && d < 0)) 3850 return INFLATED; 3851 3852 long u = (len == 2)? 3853 (((long) m[1] & LONG_MASK) + (((long)d) << 32)) : 3854 (((long)d) & LONG_MASK); 3855 return (b.signum < 0)? -u : u; 3856 } 3857 3858 private static int longCompareMagnitude(long x, long y) { 3859 if (x < 0) 3860 x = -x; 3861 if (y < 0) 3862 y = -y; 3863 return (x < y) ? -1 : ((x == y) ? 0 : 1); 3864 } 3865 3866 private static int saturateLong(long s) { 3867 int i = (int)s; 3868 return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); 3869 } 3870 3871 /* 3872 * Internal printing routine 3873 */ 3874 private static void print(String name, BigDecimal bd) { 3875 System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n", 3876 name, 3877 bd.intCompact, 3878 bd.intVal, 3879 bd.scale, 3880 bd.precision); 3881 } 3882 3883 /** 3884 * Check internal invariants of this BigDecimal. These invariants 3885 * include: 3886 * 3887 * <ul> 3888 * 3889 * <li>The object must be initialized; either intCompact must not be 3890 * INFLATED or intVal is non-null. Both of these conditions may 3891 * be true. 3892 * 3893 * <li>If both intCompact and intVal and set, their values must be 3894 * consistent. 3895 * 3896 * <li>If precision is nonzero, it must have the right value. 3897 * </ul> 3898 * 3899 * Note: Since this is an audit method, we are not supposed to change the 3900 * state of this BigDecimal object. 3901 */ 3902 private BigDecimal audit() { 3903 if (intCompact == INFLATED) { 3904 if (intVal == null) { 3905 print("audit", this); 3906 throw new AssertionError("null intVal"); 3907 } 3908 // Check precision 3909 if (precision > 0 && precision != bigDigitLength(intVal)) { 3910 print("audit", this); 3911 throw new AssertionError("precision mismatch"); 3912 } 3913 } else { 3914 if (intVal != null) { 3915 long val = intVal.longValue(); 3916 if (val != intCompact) { 3917 print("audit", this); 3918 throw new AssertionError("Inconsistent state, intCompact=" + 3919 intCompact + "\t intVal=" + val); 3920 } 3921 } 3922 // Check precision 3923 if (precision > 0 && precision != longDigitLength(intCompact)) { 3924 print("audit", this); 3925 throw new AssertionError("precision mismatch"); 3926 } 3927 } 3928 return this; 3929 } 3930 3931 /* the same as checkScale where value!=0 */ 3932 private static int checkScaleNonZero(long val) { 3933 int asInt = (int)val; 3934 if (asInt != val) { 3935 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 3936 } 3937 return asInt; 3938 } 3939 3940 private static int checkScale(long intCompact, long val) { 3941 int asInt = (int)val; 3942 if (asInt != val) { 3943 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 3944 if (intCompact != 0) 3945 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 3946 } 3947 return asInt; 3948 } 3949 3950 private static int checkScale(BigInteger intVal, long val) { 3951 int asInt = (int)val; 3952 if (asInt != val) { 3953 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 3954 if (intVal.signum() != 0) 3955 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 3956 } 3957 return asInt; 3958 } 3959 3960 /** 3961 * Returns a {@code BigDecimal} rounded according to the MathContext 3962 * settings; 3963 * If rounding is needed a new {@code BigDecimal} is created and returned. 3964 * 3965 * @param val the value to be rounded 3966 * @param mc the context to use. 3967 * @return a {@code BigDecimal} rounded according to the MathContext 3968 * settings. May return {@code value}, if no rounding needed. 3969 * @throws ArithmeticException if the rounding mode is 3970 * {@code RoundingMode.UNNECESSARY} and the 3971 * result is inexact. 3972 */ 3973 private static BigDecimal doRound(BigDecimal val, MathContext mc) { 3974 int mcp = mc.precision; 3975 boolean wasDivided = false; 3976 if (mcp > 0) { 3977 BigInteger intVal = val.intVal; 3978 long compactVal = val.intCompact; 3979 int scale = val.scale; 3980 int prec = val.precision(); 3981 int mode = mc.roundingMode.oldMode; 3982 int drop; 3983 if (compactVal == INFLATED) { 3984 drop = prec - mcp; 3985 while (drop > 0) { 3986 scale = checkScaleNonZero((long) scale - drop); 3987 intVal = divideAndRoundByTenPow(intVal, drop, mode); 3988 wasDivided = true; 3989 compactVal = compactValFor(intVal); 3990 if (compactVal != INFLATED) { 3991 prec = longDigitLength(compactVal); 3992 break; 3993 } 3994 prec = bigDigitLength(intVal); 3995 drop = prec - mcp; 3996 } 3997 } 3998 if (compactVal != INFLATED) { 3999 drop = prec - mcp; // drop can't be more than 18 4000 while (drop > 0) { 4001 scale = checkScaleNonZero((long) scale - drop); 4002 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4003 wasDivided = true; 4004 prec = longDigitLength(compactVal); 4005 drop = prec - mcp; 4006 intVal = null; 4007 } 4008 } 4009 return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val; 4010 } 4011 return val; 4012 } 4013 4014 /* 4015 * Returns a {@code BigDecimal} created from {@code long} value with 4016 * given scale rounded according to the MathContext settings 4017 */ 4018 private static BigDecimal doRound(long compactVal, int scale, MathContext mc) { 4019 int mcp = mc.precision; 4020 if (mcp > 0 && mcp<19) { 4021 int prec = longDigitLength(compactVal); 4022 int drop = prec - mcp; // drop can't be more than 18 4023 while (drop > 0) { 4024 scale = checkScaleNonZero((long) scale - drop); 4025 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4026 prec = longDigitLength(compactVal); 4027 drop = prec - mcp; 4028 } 4029 return valueOf(compactVal, scale, prec); 4030 } 4031 return valueOf(compactVal, scale); 4032 } 4033 4034 /* 4035 * Returns a {@code BigDecimal} created from {@code BigInteger} value with 4036 * given scale rounded according to the MathContext settings 4037 */ 4038 private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) { 4039 int mcp = mc.precision; 4040 int prec = 0; 4041 if (mcp > 0) { 4042 long compactVal = compactValFor(intVal); 4043 int mode = mc.roundingMode.oldMode; 4044 int drop; 4045 if (compactVal == INFLATED) { 4046 prec = bigDigitLength(intVal); 4047 drop = prec - mcp; 4048 while (drop > 0) { 4049 scale = checkScaleNonZero((long) scale - drop); 4050 intVal = divideAndRoundByTenPow(intVal, drop, mode); 4051 compactVal = compactValFor(intVal); 4052 if (compactVal != INFLATED) { 4053 break; 4054 } 4055 prec = bigDigitLength(intVal); 4056 drop = prec - mcp; 4057 } 4058 } 4059 if (compactVal != INFLATED) { 4060 prec = longDigitLength(compactVal); 4061 drop = prec - mcp; // drop can't be more than 18 4062 while (drop > 0) { 4063 scale = checkScaleNonZero((long) scale - drop); 4064 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4065 prec = longDigitLength(compactVal); 4066 drop = prec - mcp; 4067 } 4068 return valueOf(compactVal,scale,prec); 4069 } 4070 } 4071 return new BigDecimal(intVal,INFLATED,scale,prec); 4072 } 4073 4074 /* 4075 * Divides {@code BigInteger} value by ten power. 4076 */ 4077 private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) { 4078 if (tenPow < LONG_TEN_POWERS_TABLE.length) 4079 intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode); 4080 else 4081 intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode); 4082 return intVal; 4083 } 4084 4085 /** 4086 * Internally used for division operation for division {@code long} by 4087 * {@code long}. 4088 * The returned {@code BigDecimal} object is the quotient whose scale is set 4089 * to the passed in scale. If the remainder is not zero, it will be rounded 4090 * based on the passed in roundingMode. Also, if the remainder is zero and 4091 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4092 * trailing zeros of the result is stripped to match the preferredScale. 4093 */ 4094 private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode, 4095 int preferredScale) { 4096 4097 int qsign; // quotient sign 4098 long q = ldividend / ldivisor; // store quotient in long 4099 if (roundingMode == ROUND_DOWN && scale == preferredScale) 4100 return valueOf(q, scale); 4101 long r = ldividend % ldivisor; // store remainder in long 4102 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; 4103 if (r != 0) { 4104 boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r); 4105 return valueOf((increment ? q + qsign : q), scale); 4106 } else { 4107 if (preferredScale != scale) 4108 return createAndStripZerosToMatchScale(q, scale, preferredScale); 4109 else 4110 return valueOf(q, scale); 4111 } 4112 } 4113 4114 /** 4115 * Divides {@code long} by {@code long} and do rounding based on the 4116 * passed in roundingMode. 4117 */ 4118 private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) { 4119 int qsign; // quotient sign 4120 long q = ldividend / ldivisor; // store quotient in long 4121 if (roundingMode == ROUND_DOWN) 4122 return q; 4123 long r = ldividend % ldivisor; // store remainder in long 4124 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; 4125 if (r != 0) { 4126 boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r); 4127 return increment ? q + qsign : q; 4128 } else { 4129 return q; 4130 } 4131 } 4132 4133 /** 4134 * Tests if quotient has to be incremented according the roundingMode 4135 */ 4136 private static boolean needIncrement(long ldivisor, int roundingMode, 4137 int qsign, long q, long r) { 4138 boolean increment = false; 4139 int cmpFracHalf; 4140 /* Round as appropriate */ 4141 if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited 4142 throw new ArithmeticException("Rounding necessary"); 4143 } else if (roundingMode == ROUND_UP) { // Away from zero 4144 increment = true; 4145 } else if (roundingMode == ROUND_DOWN) { // Towards zero 4146 increment = false; 4147 } else if (roundingMode == ROUND_CEILING) { // Towards +infinity 4148 increment = (qsign > 0); 4149 } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity 4150 increment = (qsign < 0); 4151 } else { 4152 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { 4153 cmpFracHalf = 1; // 2 * r can't fit into long 4154 } else { 4155 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); 4156 } 4157 if (cmpFracHalf < 0) 4158 increment = false; // We're closer to higher digit 4159 else if (cmpFracHalf > 0) // We're closer to lower digit 4160 increment = true; 4161 else if (roundingMode == ROUND_HALF_UP) 4162 increment = true; 4163 else if (roundingMode == ROUND_HALF_DOWN) 4164 increment = false; 4165 else 4166 // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd 4167 increment = (q & 1L) != 0L ; 4168 } 4169 return increment; 4170 } 4171 4172 /** 4173 * Divides {@code BigInteger} value by {@code long} value and 4174 * do rounding based on the passed in roundingMode. 4175 */ 4176 private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) { 4177 boolean isRemainderZero; // record remainder is zero or not 4178 int qsign; // quotient sign 4179 long r = 0; // store quotient & remainder in long 4180 MutableBigInteger mq = null; // store quotient 4181 // Descend into mutables for faster remainder checks 4182 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4183 mq = new MutableBigInteger(); 4184 r = mdividend.divide(ldivisor, mq); 4185 isRemainderZero = (r == 0); 4186 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; 4187 if (!isRemainderZero) { 4188 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) { 4189 mq.add(MutableBigInteger.ONE); 4190 } 4191 } 4192 return mq.toBigInteger(qsign); 4193 } 4194 4195 /** 4196 * Internally used for division operation for division {@code BigInteger} 4197 * by {@code long}. 4198 * The returned {@code BigDecimal} object is the quotient whose scale is set 4199 * to the passed in scale. If the remainder is not zero, it will be rounded 4200 * based on the passed in roundingMode. Also, if the remainder is zero and 4201 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4202 * trailing zeros of the result is stripped to match the preferredScale. 4203 */ 4204 private static BigDecimal divideAndRound(BigInteger bdividend, 4205 long ldivisor, int scale, int roundingMode, int preferredScale) { 4206 boolean isRemainderZero; // record remainder is zero or not 4207 int qsign; // quotient sign 4208 long r = 0; // store quotient & remainder in long 4209 MutableBigInteger mq = null; // store quotient 4210 // Descend into mutables for faster remainder checks 4211 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4212 mq = new MutableBigInteger(); 4213 r = mdividend.divide(ldivisor, mq); 4214 isRemainderZero = (r == 0); 4215 qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; 4216 if (!isRemainderZero) { 4217 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) { 4218 mq.add(MutableBigInteger.ONE); 4219 } 4220 return mq.toBigDecimal(qsign, scale); 4221 } else { 4222 if (preferredScale != scale) { 4223 long compactVal = mq.toCompactValue(qsign); 4224 if(compactVal!=INFLATED) { 4225 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); 4226 } 4227 BigInteger intVal = mq.toBigInteger(qsign); 4228 return createAndStripZerosToMatchScale(intVal,scale, preferredScale); 4229 } else { 4230 return mq.toBigDecimal(qsign, scale); 4231 } 4232 } 4233 } 4234 4235 /** 4236 * Tests if quotient has to be incremented according the roundingMode 4237 */ 4238 private static boolean needIncrement(long ldivisor, int roundingMode, 4239 int qsign, MutableBigInteger mq, long r) { 4240 boolean increment = false; 4241 /* Round as appropriate */ 4242 if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited 4243 throw new ArithmeticException("Rounding necessary"); 4244 } else if (roundingMode == ROUND_UP) { // Away from zero 4245 increment = true; 4246 } else if (roundingMode == ROUND_DOWN) { // Towards zero 4247 increment = false; 4248 } else if (roundingMode == ROUND_CEILING) { // Towards +infinity 4249 increment = (qsign > 0); 4250 } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity 4251 increment = (qsign < 0); 4252 } else { 4253 int cmpFracHalf; 4254 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { 4255 cmpFracHalf = 1; // 2 * r can't fit into long 4256 } else { 4257 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); 4258 } 4259 if (cmpFracHalf < 0) 4260 increment = false; // We're closer to higher digit 4261 else if (cmpFracHalf > 0) // We're closer to lower digit 4262 increment = true; 4263 else if (roundingMode == ROUND_HALF_UP) 4264 increment = true; 4265 else if (roundingMode == ROUND_HALF_DOWN) 4266 increment = false; 4267 else 4268 // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd 4269 increment = mq.isOdd(); 4270 } 4271 return increment; 4272 } 4273 4274 /** 4275 * Divides {@code BigInteger} value by {@code BigInteger} value and 4276 * do rounding based on the passed in roundingMode. 4277 */ 4278 private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) { 4279 boolean isRemainderZero; // record remainder is zero or not 4280 int qsign; // quotient sign 4281 // Descend into mutables for faster remainder checks 4282 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4283 MutableBigInteger mq = new MutableBigInteger(); 4284 MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); 4285 MutableBigInteger mr = mdividend.divide(mdivisor, mq); 4286 isRemainderZero = mr.isZero(); 4287 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; 4288 if (!isRemainderZero) { 4289 if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { 4290 mq.add(MutableBigInteger.ONE); 4291 } 4292 } 4293 return mq.toBigInteger(qsign); 4294 } 4295 4296 /** 4297 * Internally used for division operation for division {@code BigInteger} 4298 * by {@code BigInteger}. 4299 * The returned {@code BigDecimal} object is the quotient whose scale is set 4300 * to the passed in scale. If the remainder is not zero, it will be rounded 4301 * based on the passed in roundingMode. Also, if the remainder is zero and 4302 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4303 * trailing zeros of the result is stripped to match the preferredScale. 4304 */ 4305 private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode, 4306 int preferredScale) { 4307 boolean isRemainderZero; // record remainder is zero or not 4308 int qsign; // quotient sign 4309 // Descend into mutables for faster remainder checks 4310 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4311 MutableBigInteger mq = new MutableBigInteger(); 4312 MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); 4313 MutableBigInteger mr = mdividend.divide(mdivisor, mq); 4314 isRemainderZero = mr.isZero(); 4315 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; 4316 if (!isRemainderZero) { 4317 if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { 4318 mq.add(MutableBigInteger.ONE); 4319 } 4320 return mq.toBigDecimal(qsign, scale); 4321 } else { 4322 if (preferredScale != scale) { 4323 long compactVal = mq.toCompactValue(qsign); 4324 if (compactVal != INFLATED) { 4325 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); 4326 } 4327 BigInteger intVal = mq.toBigInteger(qsign); 4328 return createAndStripZerosToMatchScale(intVal, scale, preferredScale); 4329 } else { 4330 return mq.toBigDecimal(qsign, scale); 4331 } 4332 } 4333 } 4334 4335 /** 4336 * Tests if quotient has to be incremented according the roundingMode 4337 */ 4338 private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode, int qsign, MutableBigInteger mq, 4339 MutableBigInteger mr) { 4340 boolean increment = false; 4341 /* Round as appropriate */ 4342 if (roundingMode == ROUND_UNNECESSARY) { // Rounding prohibited 4343 throw new ArithmeticException("Rounding necessary"); 4344 } else if (roundingMode == ROUND_UP) { // Away from zero 4345 increment = true; 4346 } else if (roundingMode == ROUND_DOWN) { // Towards zero 4347 increment = false; 4348 } else if (roundingMode == ROUND_CEILING) { // Towards +infinity 4349 increment = (qsign > 0); 4350 } else if (roundingMode == ROUND_FLOOR) { // Towards -infinity 4351 increment = (qsign < 0); 4352 } else { 4353 int cmpFracHalf = mr.compareHalf(mdivisor); 4354 if (cmpFracHalf < 0) 4355 increment = false; // We're closer to higher digit 4356 else if (cmpFracHalf > 0) // We're closer to lower digit 4357 increment = true; 4358 else if (roundingMode == ROUND_HALF_UP) 4359 increment = true; 4360 else if (roundingMode == ROUND_HALF_DOWN) 4361 increment = false; 4362 else 4363 // roundingMode == ROUND_HALF_EVEN, true iff quotient is odd 4364 increment = mq.isOdd(); 4365 } 4366 return increment; 4367 } 4368 4369 /** 4370 * Remove insignificant trailing zeros from this 4371 * {@code BigInteger} value until the preferred scale is reached or no 4372 * more zeros can be removed. If the preferred scale is less than 4373 * Integer.MIN_VALUE, all the trailing zeros will be removed. 4374 * 4375 * @return new {@code BigDecimal} with a scale possibly reduced 4376 * to be closed to the preferred scale. 4377 */ 4378 private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) { 4379 BigInteger qr[]; // quotient-remainder pair 4380 while (intVal.compareMagnitude(BigInteger.TEN) >= 0 4381 && scale > preferredScale) { 4382 if (intVal.testBit(0)) 4383 break; // odd number cannot end in 0 4384 qr = intVal.divideAndRemainder(BigInteger.TEN); 4385 if (qr[1].signum() != 0) 4386 break; // non-0 remainder 4387 intVal = qr[0]; 4388 scale = checkScale(intVal,(long) scale - 1); // could Overflow 4389 } 4390 return valueOf(intVal, scale, 0); 4391 } 4392 4393 /** 4394 * Remove insignificant trailing zeros from this 4395 * {@code long} value until the preferred scale is reached or no 4396 * more zeros can be removed. If the preferred scale is less than 4397 * Integer.MIN_VALUE, all the trailing zeros will be removed. 4398 * 4399 * @return new {@code BigDecimal} with a scale possibly reduced 4400 * to be closed to the preferred scale. 4401 */ 4402 private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) { 4403 while (Math.abs(compactVal) >= 10L && scale > preferredScale) { 4404 if ((compactVal & 1L) != 0L) 4405 break; // odd number cannot end in 0 4406 long r = compactVal % 10L; 4407 if (r != 0L) 4408 break; // non-0 remainder 4409 compactVal /= 10; 4410 scale = checkScale(compactVal, (long) scale - 1); // could Overflow 4411 } 4412 return valueOf(compactVal, scale); 4413 } 4414 4415 private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) { 4416 if(intCompact!=INFLATED) { 4417 return createAndStripZerosToMatchScale(intCompact, scale, preferredScale); 4418 } else { 4419 return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal, 4420 scale, preferredScale); 4421 } 4422 } 4423 4424 /* 4425 * returns INFLATED if oveflow 4426 */ 4427 private static long add(long xs, long ys){ 4428 long sum = xs + ys; 4429 // See "Hacker's Delight" section 2-12 for explanation of 4430 // the overflow test. 4431 if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed 4432 return sum; 4433 } 4434 return INFLATED; 4435 } 4436 4437 private static BigDecimal add(long xs, long ys, int scale){ 4438 long sum = add(xs, ys); 4439 if (sum!=INFLATED) 4440 return BigDecimal.valueOf(sum, scale); 4441 return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale); 4442 } 4443 4444 private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) { 4445 long sdiff = (long) scale1 - scale2; 4446 if (sdiff == 0) { 4447 return add(xs, ys, scale1); 4448 } else if (sdiff < 0) { 4449 int raise = checkScale(xs,-sdiff); 4450 long scaledX = longMultiplyPowerTen(xs, raise); 4451 if (scaledX != INFLATED) { 4452 return add(scaledX, ys, scale2); 4453 } else { 4454 BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys); 4455 return ((xs^ys)>=0) ? // same sign test 4456 new BigDecimal(bigsum, INFLATED, scale2, 0) 4457 : valueOf(bigsum, scale2, 0); 4458 } 4459 } else { 4460 int raise = checkScale(ys,sdiff); 4461 long scaledY = longMultiplyPowerTen(ys, raise); 4462 if (scaledY != INFLATED) { 4463 return add(xs, scaledY, scale1); 4464 } else { 4465 BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs); 4466 return ((xs^ys)>=0) ? 4467 new BigDecimal(bigsum, INFLATED, scale1, 0) 4468 : valueOf(bigsum, scale1, 0); 4469 } 4470 } 4471 } 4472 4473 private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) { 4474 int rscale = scale1; 4475 long sdiff = (long)rscale - scale2; 4476 boolean sameSigns = (Long.signum(xs) == snd.signum); 4477 BigInteger sum; 4478 if (sdiff < 0) { 4479 int raise = checkScale(xs,-sdiff); 4480 rscale = scale2; 4481 long scaledX = longMultiplyPowerTen(xs, raise); 4482 if (scaledX == INFLATED) { 4483 sum = snd.add(bigMultiplyPowerTen(xs,raise)); 4484 } else { 4485 sum = snd.add(scaledX); 4486 } 4487 } else { //if (sdiff > 0) { 4488 int raise = checkScale(snd,sdiff); 4489 snd = bigMultiplyPowerTen(snd,raise); 4490 sum = snd.add(xs); 4491 } 4492 return (sameSigns) ? 4493 new BigDecimal(sum, INFLATED, rscale, 0) : 4494 valueOf(sum, rscale, 0); 4495 } 4496 4497 private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) { 4498 int rscale = scale1; 4499 long sdiff = (long)rscale - scale2; 4500 if (sdiff != 0) { 4501 if (sdiff < 0) { 4502 int raise = checkScale(fst,-sdiff); 4503 rscale = scale2; 4504 fst = bigMultiplyPowerTen(fst,raise); 4505 } else { 4506 int raise = checkScale(snd,sdiff); 4507 snd = bigMultiplyPowerTen(snd,raise); 4508 } 4509 } 4510 BigInteger sum = fst.add(snd); 4511 return (fst.signum == snd.signum) ? 4512 new BigDecimal(sum, INFLATED, rscale, 0) : 4513 valueOf(sum, rscale, 0); 4514 } 4515 4516 private static BigInteger bigMultiplyPowerTen(long value, int n) { 4517 if (n <= 0) 4518 return BigInteger.valueOf(value); 4519 return bigTenToThe(n).multiply(value); 4520 } 4521 4522 private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) { 4523 if (n <= 0) 4524 return value; 4525 if(n<LONG_TEN_POWERS_TABLE.length) { 4526 return value.multiply(LONG_TEN_POWERS_TABLE[n]); 4527 } 4528 return value.multiply(bigTenToThe(n)); 4529 } 4530 4531 /** 4532 * Returns a {@code BigDecimal} whose value is {@code (xs / 4533 * ys)}, with rounding according to the context settings. 4534 * 4535 * Fast path - used only when (xscale <= yscale && yscale < 18 4536 * && mc.presision<18) { 4537 */ 4538 private static BigDecimal divideSmallFastPath(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) { 4539 int mcp = mc.precision; 4540 int roundingMode = mc.roundingMode.oldMode; 4541 4542 // assert xscale <= yscale && yscale<18 && mcp<18 4543 int xraise = yscale - xscale; // xraise >=0 4544 long scaledX = (xraise==0) ? xs : 4545 longMultiplyPowerTen(xs, xraise); // can't overflow here! 4546 BigDecimal quotient; 4547 4548 int cmp = longCompareMagnitude(scaledX, ys); 4549 if(cmp > 0) { // satisfy constraint (b) 4550 yscale -= 1; // [that is, divisor *= 10] 4551 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4552 if (checkScaleNonZero((long) mcp + yscale) > xscale) { 4553 // assert newScale >= xscale 4554 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4555 long scaledXs; 4556 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) { 4557 quotient = null; 4558 if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) { 4559 quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4560 } 4561 if(quotient==null) { 4562 BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1); 4563 quotient = divideAndRound(rb, ys, 4564 scl, roundingMode, checkScaleNonZero(preferredScale)); 4565 } 4566 } else { 4567 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4568 } 4569 } else { 4570 int newScale = checkScaleNonZero((long) xscale - mcp); 4571 // assert newScale >= yscale 4572 if (newScale == yscale) { // easy case 4573 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 4574 } else { 4575 int raise = checkScaleNonZero((long) newScale - yscale); 4576 long scaledYs; 4577 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 4578 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4579 quotient = divideAndRound(BigInteger.valueOf(xs), 4580 rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4581 } else { 4582 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 4583 } 4584 } 4585 } 4586 } else { 4587 // abs(scaledX) <= abs(ys) 4588 // result is "scaledX * 10^msp / ys" 4589 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4590 if(cmp==0) { 4591 // abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign 4592 quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale)); 4593 } else { 4594 // abs(scaledX) < abs(ys) 4595 long scaledXs; 4596 if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) { 4597 quotient = null; 4598 if(mcp<LONG_TEN_POWERS_TABLE.length) { 4599 quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4600 } 4601 if(quotient==null) { 4602 BigInteger rb = bigMultiplyPowerTen(scaledX,mcp); 4603 quotient = divideAndRound(rb, ys, 4604 scl, roundingMode, checkScaleNonZero(preferredScale)); 4605 } 4606 } else { 4607 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4608 } 4609 } 4610 } 4611 // doRound, here, only affects 1000000000 case. 4612 return doRound(quotient,mc); 4613 } 4614 4615 /** 4616 * Returns a {@code BigDecimal} whose value is {@code (xs / 4617 * ys)}, with rounding according to the context settings. 4618 */ 4619 private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) { 4620 int mcp = mc.precision; 4621 if(xscale <= yscale && yscale < 18 && mcp<18) { 4622 return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc); 4623 } 4624 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 4625 yscale -= 1; // [that is, divisor *= 10] 4626 } 4627 int roundingMode = mc.roundingMode.oldMode; 4628 // In order to find out whether the divide generates the exact result, 4629 // we avoid calling the above divide method. 'quotient' holds the 4630 // return BigDecimal object whose scale will be set to 'scl'. 4631 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4632 BigDecimal quotient; 4633 if (checkScaleNonZero((long) mcp + yscale) > xscale) { 4634 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4635 long scaledXs; 4636 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) { 4637 BigInteger rb = bigMultiplyPowerTen(xs,raise); 4638 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4639 } else { 4640 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4641 } 4642 } else { 4643 int newScale = checkScaleNonZero((long) xscale - mcp); 4644 // assert newScale >= yscale 4645 if (newScale == yscale) { // easy case 4646 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 4647 } else { 4648 int raise = checkScaleNonZero((long) newScale - yscale); 4649 long scaledYs; 4650 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 4651 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4652 quotient = divideAndRound(BigInteger.valueOf(xs), 4653 rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4654 } else { 4655 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 4656 } 4657 } 4658 } 4659 // doRound, here, only affects 1000000000 case. 4660 return doRound(quotient,mc); 4661 } 4662 4663 /** 4664 * Returns a {@code BigDecimal} whose value is {@code (xs / 4665 * ys)}, with rounding according to the context settings. 4666 */ 4667 private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) { 4668 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4669 if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b) 4670 yscale -= 1; // [that is, divisor *= 10] 4671 } 4672 int mcp = mc.precision; 4673 int roundingMode = mc.roundingMode.oldMode; 4674 4675 // In order to find out whether the divide generates the exact result, 4676 // we avoid calling the above divide method. 'quotient' holds the 4677 // return BigDecimal object whose scale will be set to 'scl'. 4678 BigDecimal quotient; 4679 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4680 if (checkScaleNonZero((long) mcp + yscale) > xscale) { 4681 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4682 BigInteger rb = bigMultiplyPowerTen(xs,raise); 4683 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4684 } else { 4685 int newScale = checkScaleNonZero((long) xscale - mcp); 4686 // assert newScale >= yscale 4687 if (newScale == yscale) { // easy case 4688 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 4689 } else { 4690 int raise = checkScaleNonZero((long) newScale - yscale); 4691 long scaledYs; 4692 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 4693 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4694 quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4695 } else { 4696 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 4697 } 4698 } 4699 } 4700 // doRound, here, only affects 1000000000 case. 4701 return doRound(quotient, mc); 4702 } 4703 4704 /** 4705 * Returns a {@code BigDecimal} whose value is {@code (xs / 4706 * ys)}, with rounding according to the context settings. 4707 */ 4708 private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) { 4709 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4710 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 4711 yscale -= 1; // [that is, divisor *= 10] 4712 } 4713 int mcp = mc.precision; 4714 int roundingMode = mc.roundingMode.oldMode; 4715 4716 // In order to find out whether the divide generates the exact result, 4717 // we avoid calling the above divide method. 'quotient' holds the 4718 // return BigDecimal object whose scale will be set to 'scl'. 4719 BigDecimal quotient; 4720 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4721 if (checkScaleNonZero((long) mcp + yscale) > xscale) { 4722 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4723 BigInteger rb = bigMultiplyPowerTen(xs,raise); 4724 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4725 } else { 4726 int newScale = checkScaleNonZero((long) xscale - mcp); 4727 int raise = checkScaleNonZero((long) newScale - yscale); 4728 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4729 quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4730 } 4731 // doRound, here, only affects 1000000000 case. 4732 return doRound(quotient, mc); 4733 } 4734 4735 /** 4736 * Returns a {@code BigDecimal} whose value is {@code (xs / 4737 * ys)}, with rounding according to the context settings. 4738 */ 4739 private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) { 4740 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4741 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 4742 yscale -= 1; // [that is, divisor *= 10] 4743 } 4744 int mcp = mc.precision; 4745 int roundingMode = mc.roundingMode.oldMode; 4746 4747 // In order to find out whether the divide generates the exact result, 4748 // we avoid calling the above divide method. 'quotient' holds the 4749 // return BigDecimal object whose scale will be set to 'scl'. 4750 BigDecimal quotient; 4751 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4752 if (checkScaleNonZero((long) mcp + yscale) > xscale) { 4753 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4754 BigInteger rb = bigMultiplyPowerTen(xs,raise); 4755 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4756 } else { 4757 int newScale = checkScaleNonZero((long) xscale - mcp); 4758 int raise = checkScaleNonZero((long) newScale - yscale); 4759 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4760 quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4761 } 4762 // doRound, here, only affects 1000000000 case. 4763 return doRound(quotient, mc); 4764 } 4765 4766 /* 4767 * performs divideAndRound for (dividend0*dividend1, divisor) 4768 * returns null if quotient can't fit into long value; 4769 */ 4770 private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode, 4771 int preferredScale) { 4772 int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor); 4773 dividend0 = Math.abs(dividend0); 4774 dividend1 = Math.abs(dividend1); 4775 divisor = Math.abs(divisor); 4776 // multiply dividend0 * dividend1 4777 long d0_hi = dividend0 >>> 32; 4778 long d0_lo = dividend0 & LONG_MASK; 4779 long d1_hi = dividend1 >>> 32; 4780 long d1_lo = dividend1 & LONG_MASK; 4781 long product = d0_lo * d1_lo; 4782 long d0 = product & LONG_MASK; 4783 long d1 = product >>> 32; 4784 product = d0_hi * d1_lo + d1; 4785 d1 = product & LONG_MASK; 4786 long d2 = product >>> 32; 4787 product = d0_lo * d1_hi + d1; 4788 d1 = product & LONG_MASK; 4789 d2 += product >>> 32; 4790 long d3 = d2>>>32; 4791 d2 &= LONG_MASK; 4792 product = d0_hi*d1_hi + d2; 4793 d2 = product & LONG_MASK; 4794 d3 = ((product>>>32) + d3) & LONG_MASK; 4795 final long dividendHi = make64(d3,d2); 4796 final long dividendLo = make64(d1,d0); 4797 // divide 4798 return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale); 4799 } 4800 4801 private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits). 4802 4803 /* 4804 * divideAndRound 128-bit value by long divisor. 4805 * returns null if quotient can't fit into long value; 4806 * Specialized version of Knuth's division 4807 */ 4808 private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign, 4809 int scale, int roundingMode, int preferredScale) { 4810 if (dividendHi >= divisor) { 4811 return null; 4812 } 4813 final int shift = Long.numberOfLeadingZeros(divisor); 4814 divisor <<= shift; 4815 4816 final long v1 = divisor >>> 32; 4817 final long v0 = divisor & LONG_MASK; 4818 4819 long q1, q0; 4820 long r_tmp; 4821 4822 long tmp = dividendLo << shift; 4823 long u1 = tmp >>> 32; 4824 long u0 = tmp & LONG_MASK; 4825 4826 tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift); 4827 long u2 = tmp & LONG_MASK; 4828 tmp = divWord(tmp,v1); 4829 q1 = tmp & LONG_MASK; 4830 r_tmp = tmp >>> 32; 4831 while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) { 4832 q1--; 4833 r_tmp += v1; 4834 if (r_tmp >= DIV_NUM_BASE) 4835 break; 4836 } 4837 tmp = mulsub(u2,u1,v1,v0,q1); 4838 u1 = tmp & LONG_MASK; 4839 tmp = divWord(tmp,v1); 4840 q0 = tmp & LONG_MASK; 4841 r_tmp = tmp >>> 32; 4842 while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) { 4843 q0--; 4844 r_tmp += v1; 4845 if (r_tmp >= DIV_NUM_BASE) 4846 break; 4847 } 4848 if((int)q1 < 0) { 4849 // result (which is positive and unsigned here) 4850 // can't fit into long due to sign bit is used for value 4851 MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0}); 4852 if (roundingMode == ROUND_DOWN && scale == preferredScale) { 4853 return mq.toBigDecimal(sign, scale); 4854 } 4855 long r = mulsub(u1, u0, v1, v0, q0) >>> shift; 4856 if (r != 0) { 4857 if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){ 4858 mq.add(MutableBigInteger.ONE); 4859 } 4860 return mq.toBigDecimal(sign, scale); 4861 } else { 4862 if (preferredScale != scale) { 4863 BigInteger intVal = mq.toBigInteger(sign); 4864 return createAndStripZerosToMatchScale(intVal,scale, preferredScale); 4865 } else { 4866 return mq.toBigDecimal(sign, scale); 4867 } 4868 } 4869 } 4870 long q = make64(q1,q0); 4871 q*=sign; 4872 if (roundingMode == ROUND_DOWN && scale == preferredScale) 4873 return valueOf(q, scale); 4874 long r = mulsub(u1, u0, v1, v0, q0) >>> shift; 4875 if (r != 0) { 4876 boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r); 4877 return valueOf((increment ? q + sign : q), scale); 4878 } else { 4879 if (preferredScale != scale) { 4880 return createAndStripZerosToMatchScale(q, scale, preferredScale); 4881 } else { 4882 return valueOf(q, scale); 4883 } 4884 } 4885 } 4886 4887 /* 4888 * calculate divideAndRound for ldividend*10^raise / divisor 4889 * when abs(dividend)==abs(divisor); 4890 */ 4891 private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) { 4892 if (scale > preferredScale) { 4893 int diff = scale - preferredScale; 4894 if(diff < raise) { 4895 return scaledTenPow(raise - diff, qsign, preferredScale); 4896 } else { 4897 return valueOf(qsign,scale-raise); 4898 } 4899 } else { 4900 return scaledTenPow(raise, qsign, scale); 4901 } 4902 } 4903 4904 static BigDecimal scaledTenPow(int n, int sign, int scale) { 4905 if (n < LONG_TEN_POWERS_TABLE.length) 4906 return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale); 4907 else { 4908 BigInteger unscaledVal = bigTenToThe(n); 4909 if(sign==-1) { 4910 unscaledVal = unscaledVal.negate(); 4911 } 4912 return new BigDecimal(unscaledVal, INFLATED, scale, n+1); 4913 } 4914 } 4915 4916 private static long divWord(long n, long dLong) { 4917 long r; 4918 long q; 4919 if (dLong == 1) { 4920 q = (int)n; 4921 return (q & LONG_MASK); 4922 } 4923 // Approximate the quotient and remainder 4924 q = (n >>> 1) / (dLong >>> 1); 4925 r = n - q*dLong; 4926 4927 // Correct the approximation 4928 while (r < 0) { 4929 r += dLong; 4930 q--; 4931 } 4932 while (r >= dLong) { 4933 r -= dLong; 4934 q++; 4935 } 4936 // n - q*dlong == r && 0 <= r <dLong, hence we're done. 4937 return (r << 32) | (q & LONG_MASK); 4938 } 4939 4940 private static long make64(long hi, long lo) { 4941 return hi<<32 | lo; 4942 } 4943 4944 private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) { 4945 long tmp = u0 - q0*v0; 4946 return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK); 4947 } 4948 4949 private static boolean unsignedLongCompare(long one, long two) { 4950 return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE); 4951 } 4952 4953 private static boolean unsignedLongCompareEq(long one, long two) { 4954 return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE); 4955 } 4956 4957 4958 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4959 private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) { 4960 // assert xs!=0 && ys!=0 4961 int sdiff = xscale - yscale; 4962 if (sdiff != 0) { 4963 if (sdiff < 0) { 4964 xs = longMultiplyPowerTen(xs, -sdiff); 4965 } else { // sdiff > 0 4966 ys = longMultiplyPowerTen(ys, sdiff); 4967 } 4968 } 4969 if (xs != INFLATED) 4970 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; 4971 else 4972 return 1; 4973 } 4974 4975 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4976 private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) { 4977 // assert "ys can't be represented as long" 4978 if (xs == 0) 4979 return -1; 4980 int sdiff = xscale - yscale; 4981 if (sdiff < 0) { 4982 if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) { 4983 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys); 4984 } 4985 } 4986 return -1; 4987 } 4988 4989 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 4990 private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) { 4991 int sdiff = xscale - yscale; 4992 if (sdiff < 0) { 4993 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys); 4994 } else { // sdiff >= 0 4995 return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff)); 4996 } 4997 } 4998 4999 private static long multiply(long x, long y){ 5000 long product = x * y; 5001 long ax = Math.abs(x); 5002 long ay = Math.abs(y); 5003 if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){ 5004 return product; 5005 } 5006 return INFLATED; 5007 } 5008 5009 private static BigDecimal multiply(long x, long y, int scale) { 5010 long product = multiply(x, y); 5011 if(product!=INFLATED) { 5012 return valueOf(product,scale); 5013 } 5014 return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0); 5015 } 5016 5017 private static BigDecimal multiply(long x, BigInteger y, int scale) { 5018 if(x==0) { 5019 return zeroValueOf(scale); 5020 } 5021 return new BigDecimal(y.multiply(x),INFLATED,scale,0); 5022 } 5023 5024 private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) { 5025 return new BigDecimal(x.multiply(y),INFLATED,scale,0); 5026 } 5027 5028 /** 5029 * Multiplies two long values and rounds according {@code MathContext} 5030 */ 5031 private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) { 5032 long product = multiply(x, y); 5033 if(product!=INFLATED) { 5034 return doRound(product, scale, mc); 5035 } 5036 // attempt to do it in 128 bits 5037 int rsign = 1; 5038 if(x < 0) { 5039 x = -x; 5040 rsign = -1; 5041 } 5042 if(y < 0) { 5043 y = -y; 5044 rsign *= -1; 5045 } 5046 // multiply dividend0 * dividend1 5047 long m0_hi = x >>> 32; 5048 long m0_lo = x & LONG_MASK; 5049 long m1_hi = y >>> 32; 5050 long m1_lo = y & LONG_MASK; 5051 product = m0_lo * m1_lo; 5052 long m0 = product & LONG_MASK; 5053 long m1 = product >>> 32; 5054 product = m0_hi * m1_lo + m1; 5055 m1 = product & LONG_MASK; 5056 long m2 = product >>> 32; 5057 product = m0_lo * m1_hi + m1; 5058 m1 = product & LONG_MASK; 5059 m2 += product >>> 32; 5060 long m3 = m2>>>32; 5061 m2 &= LONG_MASK; 5062 product = m0_hi*m1_hi + m2; 5063 m2 = product & LONG_MASK; 5064 m3 = ((product>>>32) + m3) & LONG_MASK; 5065 final long mHi = make64(m3,m2); 5066 final long mLo = make64(m1,m0); 5067 BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc); 5068 if(res!=null) { 5069 return res; 5070 } 5071 res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0); 5072 return doRound(res,mc); 5073 } 5074 5075 private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) { 5076 if(x==0) { 5077 return zeroValueOf(scale); 5078 } 5079 return doRound(y.multiply(x), scale, mc); 5080 } 5081 5082 private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) { 5083 return doRound(x.multiply(y), scale, mc); 5084 } 5085 5086 /** 5087 * rounds 128-bit value according {@code MathContext} 5088 * returns null if result can't be repsented as compact BigDecimal. 5089 */ 5090 private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) { 5091 int mcp = mc.precision; 5092 int drop; 5093 BigDecimal res = null; 5094 if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) { 5095 scale = checkScaleNonZero((long)scale - drop); 5096 res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale); 5097 } 5098 if(res!=null) { 5099 return doRound(res,mc); 5100 } 5101 return null; 5102 } 5103 5104 private static final long[][] LONGLONG_TEN_POWERS_TABLE = { 5105 { 0L, 0x8AC7230489E80000L }, //10^19 5106 { 0x5L, 0x6bc75e2d63100000L }, //10^20 5107 { 0x36L, 0x35c9adc5dea00000L }, //10^21 5108 { 0x21eL, 0x19e0c9bab2400000L }, //10^22 5109 { 0x152dL, 0x02c7e14af6800000L }, //10^23 5110 { 0xd3c2L, 0x1bcecceda1000000L }, //10^24 5111 { 0x84595L, 0x161401484a000000L }, //10^25 5112 { 0x52b7d2L, 0xdcc80cd2e4000000L }, //10^26 5113 { 0x33b2e3cL, 0x9fd0803ce8000000L }, //10^27 5114 { 0x204fce5eL, 0x3e25026110000000L }, //10^28 5115 { 0x1431e0faeL, 0x6d7217caa0000000L }, //10^29 5116 { 0xc9f2c9cd0L, 0x4674edea40000000L }, //10^30 5117 { 0x7e37be2022L, 0xc0914b2680000000L }, //10^31 5118 { 0x4ee2d6d415bL, 0x85acef8100000000L }, //10^32 5119 { 0x314dc6448d93L, 0x38c15b0a00000000L }, //10^33 5120 { 0x1ed09bead87c0L, 0x378d8e6400000000L }, //10^34 5121 { 0x13426172c74d82L, 0x2b878fe800000000L }, //10^35 5122 { 0xc097ce7bc90715L, 0xb34b9f1000000000L }, //10^36 5123 { 0x785ee10d5da46d9L, 0x00f436a000000000L }, //10^37 5124 { 0x4b3b4ca85a86c47aL, 0x098a224000000000L }, //10^38 5125 }; 5126 5127 /* 5128 * returns precision of 128-bit value 5129 */ 5130 private static int precision(long hi, long lo){ 5131 if(hi==0) { 5132 if(lo>=0) { 5133 return longDigitLength(lo); 5134 } 5135 return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19; 5136 // 0x8AC7230489E80000L = unsigned 2^19 5137 } 5138 int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12; 5139 int idx = r-19; 5140 return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo, 5141 LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1; 5142 } 5143 5144 /* 5145 * returns true if 128 bit number <hi0,lo0> is less then <hi1,lo1> 5146 * hi0 & hi1 should be non-negative 5147 */ 5148 private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) { 5149 if(hi0!=hi1) { 5150 return hi0<hi1; 5151 } 5152 return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE); 5153 } 5154 5155 private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) { 5156 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5157 int newScale = scale + divisorScale; 5158 int raise = newScale - dividendScale; 5159 if(raise<LONG_TEN_POWERS_TABLE.length) { 5160 long xs = dividend; 5161 if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) { 5162 return divideAndRound(xs, divisor, scale, roundingMode, scale); 5163 } 5164 BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale); 5165 if(q!=null) { 5166 return q; 5167 } 5168 } 5169 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5170 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5171 } else { 5172 int newScale = checkScale(divisor,(long)dividendScale - scale); 5173 int raise = newScale - divisorScale; 5174 if(raise<LONG_TEN_POWERS_TABLE.length) { 5175 long ys = divisor; 5176 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) { 5177 return divideAndRound(dividend, ys, scale, roundingMode, scale); 5178 } 5179 } 5180 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5181 return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale); 5182 } 5183 } 5184 5185 private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) { 5186 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5187 int newScale = scale + divisorScale; 5188 int raise = newScale - dividendScale; 5189 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5190 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5191 } else { 5192 int newScale = checkScale(divisor,(long)dividendScale - scale); 5193 int raise = newScale - divisorScale; 5194 if(raise<LONG_TEN_POWERS_TABLE.length) { 5195 long ys = divisor; 5196 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) { 5197 return divideAndRound(dividend, ys, scale, roundingMode, scale); 5198 } 5199 } 5200 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5201 return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale); 5202 } 5203 } 5204 5205 private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) { 5206 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5207 int newScale = scale + divisorScale; 5208 int raise = newScale - dividendScale; 5209 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5210 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5211 } else { 5212 int newScale = checkScale(divisor,(long)dividendScale - scale); 5213 int raise = newScale - divisorScale; 5214 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5215 return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale); 5216 } 5217 } 5218 5219 private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) { 5220 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5221 int newScale = scale + divisorScale; 5222 int raise = newScale - dividendScale; 5223 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5224 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5225 } else { 5226 int newScale = checkScale(divisor,(long)dividendScale - scale); 5227 int raise = newScale - divisorScale; 5228 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5229 return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale); 5230 } 5231 } 5232 5233 }