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