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