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