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