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 <i>inconsistent 208 * with equals</i>. 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 * <i>in</i> 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 <i>exactly</i> 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 * @since 9 2044 */ 2045 public BigDecimal sqrt(MathContext mc) { 2046 int signum = signum(); 2047 if (signum == 1) { 2048 /* 2049 * The following code draws on the algorithm presented in 2050 * "Properly Rounded Variable Precision Square Root," Hull and 2051 * Abrham, ACM Transactions on Mathematical Software, Vol 11, 2052 * No. 3, September 1985, Pages 229-237. 2053 * 2054 * The BigDecimal computational model differs from the one 2055 * presented in the paper in several ways: first BigDecimal 2056 * numbers aren't necessarily normalized, second many more 2057 * rounding modes are supported, including UNNECESSARY, and 2058 * exact results can be requested. 2059 * 2060 * The main steps of the algorithm below are as follows, 2061 * first argument reduce the value to the numerical range 2062 * [1, 10) using the following relations: 2063 * 2064 * x = y * 10 ^ exp 2065 * sqrt(x) = sqrt(y) * 10^(exp / 2) if exp is even 2066 * sqrt(x) = sqrt(y/10) * 10 ^((exp+1)/2) is exp is odd 2067 * 2068 * Then use Newton's iteration on the reduced value to compute 2069 * the numerical digits of the desired result. 2070 * 2071 * Finally, scale back to the desired exponent range and 2072 * perform any adjustment to get the preferred scale in the 2073 * representation. 2074 */ 2075 2076 // The code below favors relative simplicity over checking 2077 // for special cases that could run faster. 2078 2079 int preferredScale = this.scale()/2; 2080 BigDecimal zeroWithFinalPreferredScale = valueOf(0L, preferredScale); 2081 2082 // First phase of numerical normalization, strip trailing 2083 // zeros and check for even powers of 10. 2084 BigDecimal stripped = this.stripTrailingZeros(); 2085 int strippedScale = stripped.scale(); 2086 2087 // Numerically sqrt(10^2N) = 10^N 2088 if (stripped.isPowerOfTen() && 2089 strippedScale % 2 == 0) { 2090 BigDecimal result = valueOf(1L, strippedScale/2); 2091 if (result.scale() != preferredScale) { 2092 // Adjust to requested precision and preferred 2093 // scale as appropriate. 2094 result = result.add(zeroWithFinalPreferredScale, mc); 2095 } 2096 return result; 2097 } 2098 2099 // After stripTrailingZeros, the representation is normalized as 2100 // 2101 // unscaledValue * 10^(-scale) 2102 // 2103 // where unscaledValue is an integer with the mimimum 2104 // precision for the cohort of the numerical value. To 2105 // allow binary floating-point hardware to be used to get 2106 // approximately a 15 digit approximation to the square 2107 // root, it is helpful to instead normalize this so that 2108 // the significand portion is to right of the decimal 2109 // point by roughly (scale() - precision() +1). 2110 2111 // Now the precision / scale adjustment 2112 int scaleAdjust = 0; 2113 int scale = stripped.scale() - stripped.precision() + 1; 2114 if (scale % 2 == 0) { 2115 scaleAdjust = scale; 2116 } else { 2117 scaleAdjust = scale - 1; 2118 } 2119 2120 BigDecimal working = stripped.scaleByPowerOfTen(scaleAdjust); 2121 2122 assert // Verify 0.1 <= working < 10 2123 ONE_TENTH.compareTo(working) <= 0 && working.compareTo(TEN) < 0; 2124 2125 // Use good ole' Math.sqrt to get the initial guess for 2126 // the Newton iteration, good to at least 15 decimal 2127 // digits. This approach does incur the cost of a 2128 // 2129 // BigDecimal -> double -> BigDecimal 2130 // 2131 // conversion cycle, but it avoids the need for several 2132 // Newton iterations in BigDecimal arithmetic to get the 2133 // working answer to 15 digits of precision. If many fewer 2134 // than 15 digits were needed, it might be faster to do 2135 // the loop entirely in BigDecimal arithmetic. 2136 // 2137 // (A double value might have as much many as 17 decimal 2138 // digits of precision; it depends on the relative density 2139 // of binary and decimal numbers at different regions of 2140 // the number line.) 2141 // 2142 // (It would be possible to check for certain special 2143 // cases to avoid doing any Newton iterations. For 2144 // example, if the BigDecimal -> double conversion was 2145 // known to be exact and the rounding mode had a 2146 // low-enough precision, the post-Newton rounding logic 2147 // could be applied directly.) 2148 2149 BigDecimal guess = new BigDecimal(Math.sqrt(working.doubleValue())); 2150 int guessPrecision = 15; 2151 int originalPrecision = mc.getPrecision(); 2152 int targetPrecision; 2153 2154 // If an exact value is requested, it must only need about 2155 // half of the input digits to represent since multiplying 2156 // an N digit number by itself yield a 2N-1 digit or 2N 2157 // digit result. 2158 if (originalPrecision == 0) { 2159 targetPrecision = stripped.precision()/2 + 1; 2160 } else { 2161 targetPrecision = originalPrecision; 2162 } 2163 2164 // When setting the precision to use inside the Newton 2165 // iteration loop, take care to avoid the case where the 2166 // precision of the input exceeds the requested precision 2167 // and rounding the input value too soon. 2168 BigDecimal approx = guess; 2169 int workingPrecision = working.precision(); 2170 do { 2171 int tmpPrecision = Math.max(Math.max(guessPrecision, targetPrecision + 2), 2172 workingPrecision); 2173 MathContext mcTmp = new MathContext(tmpPrecision, RoundingMode.HALF_EVEN); 2174 // approx = 0.5 * (approx + fraction / approx) 2175 approx = ONE_HALF.multiply(approx.add(working.divide(approx, mcTmp), mcTmp)); 2176 guessPrecision *= 2; 2177 } while (guessPrecision < targetPrecision + 2); 2178 2179 BigDecimal result; 2180 RoundingMode targetRm = mc.getRoundingMode(); 2181 if (targetRm == RoundingMode.UNNECESSARY || originalPrecision == 0) { 2182 RoundingMode tmpRm = 2183 (targetRm == RoundingMode.UNNECESSARY) ? RoundingMode.DOWN : targetRm; 2184 MathContext mcTmp = new MathContext(targetPrecision, tmpRm); 2185 result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mcTmp); 2186 2187 // If result*result != this numerically, the square 2188 // root isn't exact 2189 if (this.subtract(result.multiply(result)).compareTo(ZERO) != 0) { 2190 throw new ArithmeticException("Computed square root not exact."); 2191 } 2192 } else { 2193 result = approx.scaleByPowerOfTen(-scaleAdjust/2).round(mc); 2194 } 2195 2196 if (result.scale() != preferredScale) { 2197 // The preferred scale of an add is 2198 // max(addend.scale(), augend.scale()). Therefore, if 2199 // the scale of the result is first minimized using 2200 // stripTrailingZeros(), adding a zero of the 2201 // preferred scale rounding the correct precision will 2202 // perform the proper scale vs precision tradeoffs. 2203 result = result.stripTrailingZeros(). 2204 add(zeroWithFinalPreferredScale, 2205 new MathContext(originalPrecision, RoundingMode.UNNECESSARY)); 2206 } 2207 assert squareRootResultAssertions(result, mc); 2208 return result; 2209 } else { 2210 switch (signum) { 2211 case -1: 2212 throw new ArithmeticException("Attempted square root " + 2213 "of negative BigDecimal"); 2214 case 0: 2215 return valueOf(0L, scale()/2); 2216 2217 default: 2218 throw new AssertionError("Bad value from signum"); 2219 } 2220 } 2221 } 2222 2223 private boolean isPowerOfTen() { 2224 return BigInteger.ONE.equals(this.unscaledValue()); 2225 } 2226 2227 /** 2228 * For nonzero values, check numerical correctness properties of 2229 * the computed result for the chosen rounding mode. 2230 * 2231 * For the directed roundings, for DOWN and FLOOR, result^2 must 2232 * be {@code <=} the input and (result+ulp)^2 must be {@code >} the 2233 * input. Conversely, for UP and CEIL, result^2 must be {@code >=} the 2234 * input and (result-ulp)^2 must be {@code <} the input. 2235 */ 2236 private boolean squareRootResultAssertions(BigDecimal result, MathContext mc) { 2237 if (result.signum() == 0) { 2238 return squareRootZeroResultAssertions(result, mc); 2239 } else { 2240 RoundingMode rm = mc.getRoundingMode(); 2241 BigDecimal ulp = result.ulp(); 2242 BigDecimal neighborUp = result.add(ulp); 2243 // Make neighbor down accurate even for powers of ten 2244 if (this.isPowerOfTen()) { 2245 ulp = ulp.divide(TEN); 2246 } 2247 BigDecimal neighborDown = result.subtract(ulp); 2248 2249 // Both the starting value and result should be nonzero and positive. 2250 if (result.signum() != 1 || 2251 this.signum() != 1) { 2252 return false; 2253 } 2254 2255 switch (rm) { 2256 case DOWN: 2257 case FLOOR: 2258 return 2259 result.multiply(result).compareTo(this) <= 0 && 2260 neighborUp.multiply(neighborUp).compareTo(this) > 0; 2261 2262 case UP: 2263 case CEILING: 2264 return 2265 result.multiply(result).compareTo(this) >= 0 && 2266 neighborDown.multiply(neighborDown).compareTo(this) < 0; 2267 2268 case HALF_DOWN: 2269 case HALF_EVEN: 2270 case HALF_UP: 2271 BigDecimal err = result.multiply(result).subtract(this).abs(); 2272 BigDecimal errUp = neighborUp.multiply(neighborUp).subtract(this); 2273 BigDecimal errDown = this.subtract(neighborDown.multiply(neighborDown)); 2274 // All error values should be positive so don't need to 2275 // compare absolute values. 2276 2277 int err_comp_errUp = err.compareTo(errUp); 2278 int err_comp_errDown = err.compareTo(errDown); 2279 2280 return 2281 errUp.signum() == 1 && 2282 errDown.signum() == 1 && 2283 2284 err_comp_errUp <= 0 && 2285 err_comp_errDown <= 0 && 2286 2287 ((err_comp_errUp == 0 ) ? err_comp_errDown < 0 : true) && 2288 ((err_comp_errDown == 0 ) ? err_comp_errUp < 0 : true); 2289 // && could check for digit conditions for ties too 2290 2291 default: // Definition of UNNECESSARY already verified. 2292 return true; 2293 } 2294 } 2295 } 2296 2297 private boolean squareRootZeroResultAssertions(BigDecimal result, MathContext mc) { 2298 return this.compareTo(ZERO) == 0; 2299 } 2300 2301 /** 2302 * Returns a {@code BigDecimal} whose value is 2303 * <code>(this<sup>n</sup>)</code>, The power is computed exactly, to 2304 * unlimited precision. 2305 * 2306 * <p>The parameter {@code n} must be in the range 0 through 2307 * 999999999, inclusive. {@code ZERO.pow(0)} returns {@link 2308 * #ONE}. 2309 * 2310 * Note that future releases may expand the allowable exponent 2311 * range of this method. 2312 * 2313 * @param n power to raise this {@code BigDecimal} to. 2314 * @return <code>this<sup>n</sup></code> 2315 * @throws ArithmeticException if {@code n} is out of range. 2316 * @since 1.5 2317 */ 2318 public BigDecimal pow(int n) { 2319 if (n < 0 || n > 999999999) 2320 throw new ArithmeticException("Invalid operation"); 2321 // No need to calculate pow(n) if result will over/underflow. 2322 // Don't attempt to support "supernormal" numbers. 2323 int newScale = checkScale((long)scale * n); 2324 return new BigDecimal(this.inflated().pow(n), newScale); 2325 } 2326 2327 2328 /** 2329 * Returns a {@code BigDecimal} whose value is 2330 * <code>(this<sup>n</sup>)</code>. The current implementation uses 2331 * the core algorithm defined in ANSI standard X3.274-1996 with 2332 * rounding according to the context settings. In general, the 2333 * returned numerical value is within two ulps of the exact 2334 * numerical value for the chosen precision. Note that future 2335 * releases may use a different algorithm with a decreased 2336 * allowable error bound and increased allowable exponent range. 2337 * 2338 * <p>The X3.274-1996 algorithm is: 2339 * 2340 * <ul> 2341 * <li> An {@code ArithmeticException} exception is thrown if 2342 * <ul> 2343 * <li>{@code abs(n) > 999999999} 2344 * <li>{@code mc.precision == 0} and {@code n < 0} 2345 * <li>{@code mc.precision > 0} and {@code n} has more than 2346 * {@code mc.precision} decimal digits 2347 * </ul> 2348 * 2349 * <li> if {@code n} is zero, {@link #ONE} is returned even if 2350 * {@code this} is zero, otherwise 2351 * <ul> 2352 * <li> if {@code n} is positive, the result is calculated via 2353 * the repeated squaring technique into a single accumulator. 2354 * The individual multiplications with the accumulator use the 2355 * same math context settings as in {@code mc} except for a 2356 * precision increased to {@code mc.precision + elength + 1} 2357 * where {@code elength} is the number of decimal digits in 2358 * {@code n}. 2359 * 2360 * <li> if {@code n} is negative, the result is calculated as if 2361 * {@code n} were positive; this value is then divided into one 2362 * using the working precision specified above. 2363 * 2364 * <li> The final value from either the positive or negative case 2365 * is then rounded to the destination precision. 2366 * </ul> 2367 * </ul> 2368 * 2369 * @param n power to raise this {@code BigDecimal} to. 2370 * @param mc the context to use. 2371 * @return <code>this<sup>n</sup></code> using the ANSI standard X3.274-1996 2372 * algorithm 2373 * @throws ArithmeticException if the result is inexact but the 2374 * rounding mode is {@code UNNECESSARY}, or {@code n} is out 2375 * of range. 2376 * @since 1.5 2377 */ 2378 public BigDecimal pow(int n, MathContext mc) { 2379 if (mc.precision == 0) 2380 return pow(n); 2381 if (n < -999999999 || n > 999999999) 2382 throw new ArithmeticException("Invalid operation"); 2383 if (n == 0) 2384 return ONE; // x**0 == 1 in X3.274 2385 BigDecimal lhs = this; 2386 MathContext workmc = mc; // working settings 2387 int mag = Math.abs(n); // magnitude of n 2388 if (mc.precision > 0) { 2389 int elength = longDigitLength(mag); // length of n in digits 2390 if (elength > mc.precision) // X3.274 rule 2391 throw new ArithmeticException("Invalid operation"); 2392 workmc = new MathContext(mc.precision + elength + 1, 2393 mc.roundingMode); 2394 } 2395 // ready to carry out power calculation... 2396 BigDecimal acc = ONE; // accumulator 2397 boolean seenbit = false; // set once we've seen a 1-bit 2398 for (int i=1;;i++) { // for each bit [top bit ignored] 2399 mag += mag; // shift left 1 bit 2400 if (mag < 0) { // top bit is set 2401 seenbit = true; // OK, we're off 2402 acc = acc.multiply(lhs, workmc); // acc=acc*x 2403 } 2404 if (i == 31) 2405 break; // that was the last bit 2406 if (seenbit) 2407 acc=acc.multiply(acc, workmc); // acc=acc*acc [square] 2408 // else (!seenbit) no point in squaring ONE 2409 } 2410 // if negative n, calculate the reciprocal using working precision 2411 if (n < 0) // [hence mc.precision>0] 2412 acc=ONE.divide(acc, workmc); 2413 // round to final precision and strip zeros 2414 return doRound(acc, mc); 2415 } 2416 2417 /** 2418 * Returns a {@code BigDecimal} whose value is the absolute value 2419 * of this {@code BigDecimal}, and whose scale is 2420 * {@code this.scale()}. 2421 * 2422 * @return {@code abs(this)} 2423 */ 2424 public BigDecimal abs() { 2425 return (signum() < 0 ? negate() : this); 2426 } 2427 2428 /** 2429 * Returns a {@code BigDecimal} whose value is the absolute value 2430 * of this {@code BigDecimal}, with rounding according to the 2431 * context settings. 2432 * 2433 * @param mc the context to use. 2434 * @return {@code abs(this)}, rounded as necessary. 2435 * @throws ArithmeticException if the result is inexact but the 2436 * rounding mode is {@code UNNECESSARY}. 2437 * @since 1.5 2438 */ 2439 public BigDecimal abs(MathContext mc) { 2440 return (signum() < 0 ? negate(mc) : plus(mc)); 2441 } 2442 2443 /** 2444 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2445 * and whose scale is {@code this.scale()}. 2446 * 2447 * @return {@code -this}. 2448 */ 2449 public BigDecimal negate() { 2450 if (intCompact == INFLATED) { 2451 return new BigDecimal(intVal.negate(), INFLATED, scale, precision); 2452 } else { 2453 return valueOf(-intCompact, scale, precision); 2454 } 2455 } 2456 2457 /** 2458 * Returns a {@code BigDecimal} whose value is {@code (-this)}, 2459 * with rounding according to the context settings. 2460 * 2461 * @param mc the context to use. 2462 * @return {@code -this}, rounded as necessary. 2463 * @throws ArithmeticException if the result is inexact but the 2464 * rounding mode is {@code UNNECESSARY}. 2465 * @since 1.5 2466 */ 2467 public BigDecimal negate(MathContext mc) { 2468 return negate().plus(mc); 2469 } 2470 2471 /** 2472 * Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose 2473 * scale is {@code this.scale()}. 2474 * 2475 * <p>This method, which simply returns this {@code BigDecimal} 2476 * is included for symmetry with the unary minus method {@link 2477 * #negate()}. 2478 * 2479 * @return {@code this}. 2480 * @see #negate() 2481 * @since 1.5 2482 */ 2483 public BigDecimal plus() { 2484 return this; 2485 } 2486 2487 /** 2488 * Returns a {@code BigDecimal} whose value is {@code (+this)}, 2489 * with rounding according to the context settings. 2490 * 2491 * <p>The effect of this method is identical to that of the {@link 2492 * #round(MathContext)} method. 2493 * 2494 * @param mc the context to use. 2495 * @return {@code this}, rounded as necessary. A zero result will 2496 * have a scale of 0. 2497 * @throws ArithmeticException if the result is inexact but the 2498 * rounding mode is {@code UNNECESSARY}. 2499 * @see #round(MathContext) 2500 * @since 1.5 2501 */ 2502 public BigDecimal plus(MathContext mc) { 2503 if (mc.precision == 0) // no rounding please 2504 return this; 2505 return doRound(this, mc); 2506 } 2507 2508 /** 2509 * Returns the signum function of this {@code BigDecimal}. 2510 * 2511 * @return -1, 0, or 1 as the value of this {@code BigDecimal} 2512 * is negative, zero, or positive. 2513 */ 2514 public int signum() { 2515 return (intCompact != INFLATED)? 2516 Long.signum(intCompact): 2517 intVal.signum(); 2518 } 2519 2520 /** 2521 * Returns the <i>scale</i> of this {@code BigDecimal}. If zero 2522 * or positive, the scale is the number of digits to the right of 2523 * the decimal point. If negative, the unscaled value of the 2524 * number is multiplied by ten to the power of the negation of the 2525 * scale. For example, a scale of {@code -3} means the unscaled 2526 * value is multiplied by 1000. 2527 * 2528 * @return the scale of this {@code BigDecimal}. 2529 */ 2530 public int scale() { 2531 return scale; 2532 } 2533 2534 /** 2535 * Returns the <i>precision</i> of this {@code BigDecimal}. (The 2536 * precision is the number of digits in the unscaled value.) 2537 * 2538 * <p>The precision of a zero value is 1. 2539 * 2540 * @return the precision of this {@code BigDecimal}. 2541 * @since 1.5 2542 */ 2543 public int precision() { 2544 int result = precision; 2545 if (result == 0) { 2546 long s = intCompact; 2547 if (s != INFLATED) 2548 result = longDigitLength(s); 2549 else 2550 result = bigDigitLength(intVal); 2551 precision = result; 2552 } 2553 return result; 2554 } 2555 2556 2557 /** 2558 * Returns a {@code BigInteger} whose value is the <i>unscaled 2559 * value</i> of this {@code BigDecimal}. (Computes <code>(this * 2560 * 10<sup>this.scale()</sup>)</code>.) 2561 * 2562 * @return the unscaled value of this {@code BigDecimal}. 2563 * @since 1.2 2564 */ 2565 public BigInteger unscaledValue() { 2566 return this.inflated(); 2567 } 2568 2569 // Rounding Modes 2570 2571 /** 2572 * Rounding mode to round away from zero. Always increments the 2573 * digit prior to a nonzero discarded fraction. Note that this rounding 2574 * mode never decreases the magnitude of the calculated value. 2575 * 2576 * @deprecated Use {@link RoundingMode#UP} instead. 2577 */ 2578 @Deprecated(since="9") 2579 public static final int ROUND_UP = 0; 2580 2581 /** 2582 * Rounding mode to round towards zero. Never increments the digit 2583 * prior to a discarded fraction (i.e., truncates). Note that this 2584 * rounding mode never increases the magnitude of the calculated value. 2585 * 2586 * @deprecated Use {@link RoundingMode#DOWN} instead. 2587 */ 2588 @Deprecated(since="9") 2589 public static final int ROUND_DOWN = 1; 2590 2591 /** 2592 * Rounding mode to round towards positive infinity. If the 2593 * {@code BigDecimal} is positive, behaves as for 2594 * {@code ROUND_UP}; if negative, behaves as for 2595 * {@code ROUND_DOWN}. Note that this rounding mode never 2596 * decreases the calculated value. 2597 * 2598 * @deprecated Use {@link RoundingMode#CEILING} instead. 2599 */ 2600 @Deprecated(since="9") 2601 public static final int ROUND_CEILING = 2; 2602 2603 /** 2604 * Rounding mode to round towards negative infinity. If the 2605 * {@code BigDecimal} is positive, behave as for 2606 * {@code ROUND_DOWN}; if negative, behave as for 2607 * {@code ROUND_UP}. Note that this rounding mode never 2608 * increases the calculated value. 2609 * 2610 * @deprecated Use {@link RoundingMode#FLOOR} instead. 2611 */ 2612 @Deprecated(since="9") 2613 public static final int ROUND_FLOOR = 3; 2614 2615 /** 2616 * Rounding mode to round towards {@literal "nearest neighbor"} 2617 * unless both neighbors are equidistant, in which case round up. 2618 * Behaves as for {@code ROUND_UP} if the discarded fraction is 2619 * ≥ 0.5; otherwise, behaves as for {@code ROUND_DOWN}. Note 2620 * that this is the rounding mode that most of us were taught in 2621 * grade school. 2622 * 2623 * @deprecated Use {@link RoundingMode#HALF_UP} instead. 2624 */ 2625 @Deprecated(since="9") 2626 public static final int ROUND_HALF_UP = 4; 2627 2628 /** 2629 * Rounding mode to round towards {@literal "nearest neighbor"} 2630 * unless both neighbors are equidistant, in which case round 2631 * down. Behaves as for {@code ROUND_UP} if the discarded 2632 * fraction is {@literal >} 0.5; otherwise, behaves as for 2633 * {@code ROUND_DOWN}. 2634 * 2635 * @deprecated Use {@link RoundingMode#HALF_DOWN} instead. 2636 */ 2637 @Deprecated(since="9") 2638 public static final int ROUND_HALF_DOWN = 5; 2639 2640 /** 2641 * Rounding mode to round towards the {@literal "nearest neighbor"} 2642 * unless both neighbors are equidistant, in which case, round 2643 * towards the even neighbor. Behaves as for 2644 * {@code ROUND_HALF_UP} if the digit to the left of the 2645 * discarded fraction is odd; behaves as for 2646 * {@code ROUND_HALF_DOWN} if it's even. Note that this is the 2647 * rounding mode that minimizes cumulative error when applied 2648 * repeatedly over a sequence of calculations. 2649 * 2650 * @deprecated Use {@link RoundingMode#HALF_EVEN} instead. 2651 */ 2652 @Deprecated(since="9") 2653 public static final int ROUND_HALF_EVEN = 6; 2654 2655 /** 2656 * Rounding mode to assert that the requested operation has an exact 2657 * result, hence no rounding is necessary. If this rounding mode is 2658 * specified on an operation that yields an inexact result, an 2659 * {@code ArithmeticException} is thrown. 2660 * 2661 * @deprecated Use {@link RoundingMode#UNNECESSARY} instead. 2662 */ 2663 @Deprecated(since="9") 2664 public static final int ROUND_UNNECESSARY = 7; 2665 2666 2667 // Scaling/Rounding Operations 2668 2669 /** 2670 * Returns a {@code BigDecimal} rounded according to the 2671 * {@code MathContext} settings. If the precision setting is 0 then 2672 * no rounding takes place. 2673 * 2674 * <p>The effect of this method is identical to that of the 2675 * {@link #plus(MathContext)} method. 2676 * 2677 * @param mc the context to use. 2678 * @return a {@code BigDecimal} rounded according to the 2679 * {@code MathContext} settings. 2680 * @throws ArithmeticException if the rounding mode is 2681 * {@code UNNECESSARY} and the 2682 * {@code BigDecimal} operation would require rounding. 2683 * @see #plus(MathContext) 2684 * @since 1.5 2685 */ 2686 public BigDecimal round(MathContext mc) { 2687 return plus(mc); 2688 } 2689 2690 /** 2691 * Returns a {@code BigDecimal} whose scale is the specified 2692 * value, and whose unscaled value is determined by multiplying or 2693 * dividing this {@code BigDecimal}'s unscaled value by the 2694 * appropriate power of ten to maintain its overall value. If the 2695 * scale is reduced by the operation, the unscaled value must be 2696 * divided (rather than multiplied), and the value may be changed; 2697 * in this case, the specified rounding mode is applied to the 2698 * division. 2699 * 2700 * @apiNote Since BigDecimal objects are immutable, calls of 2701 * this method do <em>not</em> result in the original object being 2702 * modified, contrary to the usual convention of having methods 2703 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>. 2704 * Instead, {@code setScale} returns an object with the proper 2705 * scale; the returned object may or may not be newly allocated. 2706 * 2707 * @param newScale scale of the {@code BigDecimal} value to be returned. 2708 * @param roundingMode The rounding mode to apply. 2709 * @return a {@code BigDecimal} whose scale is the specified value, 2710 * and whose unscaled value is determined by multiplying or 2711 * dividing this {@code BigDecimal}'s unscaled value by the 2712 * appropriate power of ten to maintain its overall value. 2713 * @throws ArithmeticException if {@code roundingMode==UNNECESSARY} 2714 * and the specified scaling operation would require 2715 * rounding. 2716 * @see RoundingMode 2717 * @since 1.5 2718 */ 2719 public BigDecimal setScale(int newScale, RoundingMode roundingMode) { 2720 return setScale(newScale, roundingMode.oldMode); 2721 } 2722 2723 /** 2724 * Returns a {@code BigDecimal} whose scale is the specified 2725 * value, and whose unscaled value is determined by multiplying or 2726 * dividing this {@code BigDecimal}'s unscaled value by the 2727 * appropriate power of ten to maintain its overall value. If the 2728 * scale is reduced by the operation, the unscaled value must be 2729 * divided (rather than multiplied), and the value may be changed; 2730 * in this case, the specified rounding mode is applied to the 2731 * division. 2732 * 2733 * @apiNote Since BigDecimal objects are immutable, calls of 2734 * this method do <em>not</em> result in the original object being 2735 * modified, contrary to the usual convention of having methods 2736 * named <code>set<i>X</i></code> mutate field <i>{@code X}</i>. 2737 * Instead, {@code setScale} returns an object with the proper 2738 * scale; the returned object may or may not be newly allocated. 2739 * 2740 * @deprecated The method {@link #setScale(int, RoundingMode)} should 2741 * be used in preference to this legacy method. 2742 * 2743 * @param newScale scale of the {@code BigDecimal} value to be returned. 2744 * @param roundingMode The rounding mode to apply. 2745 * @return a {@code BigDecimal} whose scale is the specified value, 2746 * and whose unscaled value is determined by multiplying or 2747 * dividing this {@code BigDecimal}'s unscaled value by the 2748 * appropriate power of ten to maintain its overall value. 2749 * @throws ArithmeticException if {@code roundingMode==ROUND_UNNECESSARY} 2750 * and the specified scaling operation would require 2751 * rounding. 2752 * @throws IllegalArgumentException if {@code roundingMode} does not 2753 * represent a valid rounding mode. 2754 * @see #ROUND_UP 2755 * @see #ROUND_DOWN 2756 * @see #ROUND_CEILING 2757 * @see #ROUND_FLOOR 2758 * @see #ROUND_HALF_UP 2759 * @see #ROUND_HALF_DOWN 2760 * @see #ROUND_HALF_EVEN 2761 * @see #ROUND_UNNECESSARY 2762 */ 2763 @Deprecated(since="9") 2764 public BigDecimal setScale(int newScale, int roundingMode) { 2765 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 2766 throw new IllegalArgumentException("Invalid rounding mode"); 2767 2768 int oldScale = this.scale; 2769 if (newScale == oldScale) // easy case 2770 return this; 2771 if (this.signum() == 0) // zero can have any scale 2772 return zeroValueOf(newScale); 2773 if(this.intCompact!=INFLATED) { 2774 long rs = this.intCompact; 2775 if (newScale > oldScale) { 2776 int raise = checkScale((long) newScale - oldScale); 2777 if ((rs = longMultiplyPowerTen(rs, raise)) != INFLATED) { 2778 return valueOf(rs,newScale); 2779 } 2780 BigInteger rb = bigMultiplyPowerTen(raise); 2781 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0); 2782 } else { 2783 // newScale < oldScale -- drop some digits 2784 // Can't predict the precision due to the effect of rounding. 2785 int drop = checkScale((long) oldScale - newScale); 2786 if (drop < LONG_TEN_POWERS_TABLE.length) { 2787 return divideAndRound(rs, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, newScale); 2788 } else { 2789 return divideAndRound(this.inflated(), bigTenToThe(drop), newScale, roundingMode, newScale); 2790 } 2791 } 2792 } else { 2793 if (newScale > oldScale) { 2794 int raise = checkScale((long) newScale - oldScale); 2795 BigInteger rb = bigMultiplyPowerTen(this.intVal,raise); 2796 return new BigDecimal(rb, INFLATED, newScale, (precision > 0) ? precision + raise : 0); 2797 } else { 2798 // newScale < oldScale -- drop some digits 2799 // Can't predict the precision due to the effect of rounding. 2800 int drop = checkScale((long) oldScale - newScale); 2801 if (drop < LONG_TEN_POWERS_TABLE.length) 2802 return divideAndRound(this.intVal, LONG_TEN_POWERS_TABLE[drop], newScale, roundingMode, 2803 newScale); 2804 else 2805 return divideAndRound(this.intVal, bigTenToThe(drop), newScale, roundingMode, newScale); 2806 } 2807 } 2808 } 2809 2810 /** 2811 * Returns a {@code BigDecimal} whose scale is the specified 2812 * value, and whose value is numerically equal to this 2813 * {@code BigDecimal}'s. Throws an {@code ArithmeticException} 2814 * if this is not possible. 2815 * 2816 * <p>This call is typically used to increase the scale, in which 2817 * case it is guaranteed that there exists a {@code BigDecimal} 2818 * of the specified scale and the correct value. The call can 2819 * also be used to reduce the scale if the caller knows that the 2820 * {@code BigDecimal} has sufficiently many zeros at the end of 2821 * its fractional part (i.e., factors of ten in its integer value) 2822 * to allow for the rescaling without changing its value. 2823 * 2824 * <p>This method returns the same result as the two-argument 2825 * versions of {@code setScale}, but saves the caller the trouble 2826 * of specifying a rounding mode in cases where it is irrelevant. 2827 * 2828 * @apiNote Since {@code BigDecimal} objects are immutable, 2829 * calls of this method do <em>not</em> result in the original 2830 * object being modified, contrary to the usual convention of 2831 * having methods named <code>set<i>X</i></code> mutate field 2832 * <i>{@code X}</i>. Instead, {@code setScale} returns an 2833 * object with the proper scale; the returned object may or may 2834 * not be newly allocated. 2835 * 2836 * @param newScale scale of the {@code BigDecimal} value to be returned. 2837 * @return a {@code BigDecimal} whose scale is the specified value, and 2838 * whose unscaled value is determined by multiplying or dividing 2839 * this {@code BigDecimal}'s unscaled value by the appropriate 2840 * power of ten to maintain its overall value. 2841 * @throws ArithmeticException if the specified scaling operation would 2842 * require rounding. 2843 * @see #setScale(int, int) 2844 * @see #setScale(int, RoundingMode) 2845 */ 2846 public BigDecimal setScale(int newScale) { 2847 return setScale(newScale, ROUND_UNNECESSARY); 2848 } 2849 2850 // Decimal Point Motion Operations 2851 2852 /** 2853 * Returns a {@code BigDecimal} which is equivalent to this one 2854 * with the decimal point moved {@code n} places to the left. If 2855 * {@code n} is non-negative, the call merely adds {@code n} to 2856 * the scale. If {@code n} is negative, the call is equivalent 2857 * to {@code movePointRight(-n)}. The {@code BigDecimal} 2858 * returned by this call has value <code>(this × 2859 * 10<sup>-n</sup>)</code> and scale {@code max(this.scale()+n, 2860 * 0)}. 2861 * 2862 * @param n number of places to move the decimal point to the left. 2863 * @return a {@code BigDecimal} which is equivalent to this one with the 2864 * decimal point moved {@code n} places to the left. 2865 * @throws ArithmeticException if scale overflows. 2866 */ 2867 public BigDecimal movePointLeft(int n) { 2868 // Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE 2869 int newScale = checkScale((long)scale + n); 2870 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2871 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2872 } 2873 2874 /** 2875 * Returns a {@code BigDecimal} which is equivalent to this one 2876 * with the decimal point moved {@code n} places to the right. 2877 * If {@code n} is non-negative, the call merely subtracts 2878 * {@code n} from the scale. If {@code n} is negative, the call 2879 * is equivalent to {@code movePointLeft(-n)}. The 2880 * {@code BigDecimal} returned by this call has value <code>(this 2881 * × 10<sup>n</sup>)</code> and scale {@code max(this.scale()-n, 2882 * 0)}. 2883 * 2884 * @param n number of places to move the decimal point to the right. 2885 * @return a {@code BigDecimal} which is equivalent to this one 2886 * with the decimal point moved {@code n} places to the right. 2887 * @throws ArithmeticException if scale overflows. 2888 */ 2889 public BigDecimal movePointRight(int n) { 2890 // Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE 2891 int newScale = checkScale((long)scale - n); 2892 BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0); 2893 return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num; 2894 } 2895 2896 /** 2897 * Returns a BigDecimal whose numerical value is equal to 2898 * ({@code this} * 10<sup>n</sup>). The scale of 2899 * the result is {@code (this.scale() - n)}. 2900 * 2901 * @param n the exponent power of ten to scale by 2902 * @return a BigDecimal whose numerical value is equal to 2903 * ({@code this} * 10<sup>n</sup>) 2904 * @throws ArithmeticException if the scale would be 2905 * outside the range of a 32-bit integer. 2906 * 2907 * @since 1.5 2908 */ 2909 public BigDecimal scaleByPowerOfTen(int n) { 2910 return new BigDecimal(intVal, intCompact, 2911 checkScale((long)scale - n), precision); 2912 } 2913 2914 /** 2915 * Returns a {@code BigDecimal} which is numerically equal to 2916 * this one but with any trailing zeros removed from the 2917 * representation. For example, stripping the trailing zeros from 2918 * the {@code BigDecimal} value {@code 600.0}, which has 2919 * [{@code BigInteger}, {@code scale}] components equals to 2920 * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, 2921 * {@code scale}] components equals to [6, -2]. If 2922 * this BigDecimal is numerically equal to zero, then 2923 * {@code BigDecimal.ZERO} is returned. 2924 * 2925 * @return a numerically equal {@code BigDecimal} with any 2926 * trailing zeros removed. 2927 * @since 1.5 2928 */ 2929 public BigDecimal stripTrailingZeros() { 2930 if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) { 2931 return BigDecimal.ZERO; 2932 } else if (intCompact != INFLATED) { 2933 return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE); 2934 } else { 2935 return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE); 2936 } 2937 } 2938 2939 // Comparison Operations 2940 2941 /** 2942 * Compares this {@code BigDecimal} with the specified 2943 * {@code BigDecimal}. Two {@code BigDecimal} objects that are 2944 * equal in value but have a different scale (like 2.0 and 2.00) 2945 * are considered equal by this method. This method is provided 2946 * in preference to individual methods for each of the six boolean 2947 * comparison operators ({@literal <}, ==, 2948 * {@literal >}, {@literal >=}, !=, {@literal <=}). The 2949 * suggested idiom for performing these comparisons is: 2950 * {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where 2951 * <<i>op</i>> is one of the six comparison operators. 2952 * 2953 * @param val {@code BigDecimal} to which this {@code BigDecimal} is 2954 * to be compared. 2955 * @return -1, 0, or 1 as this {@code BigDecimal} is numerically 2956 * less than, equal to, or greater than {@code val}. 2957 */ 2958 @Override 2959 public int compareTo(BigDecimal val) { 2960 // Quick path for equal scale and non-inflated case. 2961 if (scale == val.scale) { 2962 long xs = intCompact; 2963 long ys = val.intCompact; 2964 if (xs != INFLATED && ys != INFLATED) 2965 return xs != ys ? ((xs > ys) ? 1 : -1) : 0; 2966 } 2967 int xsign = this.signum(); 2968 int ysign = val.signum(); 2969 if (xsign != ysign) 2970 return (xsign > ysign) ? 1 : -1; 2971 if (xsign == 0) 2972 return 0; 2973 int cmp = compareMagnitude(val); 2974 return (xsign > 0) ? cmp : -cmp; 2975 } 2976 2977 /** 2978 * Version of compareTo that ignores sign. 2979 */ 2980 private int compareMagnitude(BigDecimal val) { 2981 // Match scales, avoid unnecessary inflation 2982 long ys = val.intCompact; 2983 long xs = this.intCompact; 2984 if (xs == 0) 2985 return (ys == 0) ? 0 : -1; 2986 if (ys == 0) 2987 return 1; 2988 2989 long sdiff = (long)this.scale - val.scale; 2990 if (sdiff != 0) { 2991 // Avoid matching scales if the (adjusted) exponents differ 2992 long xae = (long)this.precision() - this.scale; // [-1] 2993 long yae = (long)val.precision() - val.scale; // [-1] 2994 if (xae < yae) 2995 return -1; 2996 if (xae > yae) 2997 return 1; 2998 if (sdiff < 0) { 2999 // The cases sdiff <= Integer.MIN_VALUE intentionally fall through. 3000 if ( sdiff > Integer.MIN_VALUE && 3001 (xs == INFLATED || 3002 (xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) && 3003 ys == INFLATED) { 3004 BigInteger rb = bigMultiplyPowerTen((int)-sdiff); 3005 return rb.compareMagnitude(val.intVal); 3006 } 3007 } else { // sdiff > 0 3008 // The cases sdiff > Integer.MAX_VALUE intentionally fall through. 3009 if ( sdiff <= Integer.MAX_VALUE && 3010 (ys == INFLATED || 3011 (ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) && 3012 xs == INFLATED) { 3013 BigInteger rb = val.bigMultiplyPowerTen((int)sdiff); 3014 return this.intVal.compareMagnitude(rb); 3015 } 3016 } 3017 } 3018 if (xs != INFLATED) 3019 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; 3020 else if (ys != INFLATED) 3021 return 1; 3022 else 3023 return this.intVal.compareMagnitude(val.intVal); 3024 } 3025 3026 /** 3027 * Compares this {@code BigDecimal} with the specified 3028 * {@code Object} for equality. Unlike {@link 3029 * #compareTo(BigDecimal) compareTo}, this method considers two 3030 * {@code BigDecimal} objects equal only if they are equal in 3031 * value and scale (thus 2.0 is not equal to 2.00 when compared by 3032 * this method). 3033 * 3034 * @param x {@code Object} to which this {@code BigDecimal} is 3035 * to be compared. 3036 * @return {@code true} if and only if the specified {@code Object} is a 3037 * {@code BigDecimal} whose value and scale are equal to this 3038 * {@code BigDecimal}'s. 3039 * @see #compareTo(java.math.BigDecimal) 3040 * @see #hashCode 3041 */ 3042 @Override 3043 public boolean equals(Object x) { 3044 if (!(x instanceof BigDecimal)) 3045 return false; 3046 BigDecimal xDec = (BigDecimal) x; 3047 if (x == this) 3048 return true; 3049 if (scale != xDec.scale) 3050 return false; 3051 long s = this.intCompact; 3052 long xs = xDec.intCompact; 3053 if (s != INFLATED) { 3054 if (xs == INFLATED) 3055 xs = compactValFor(xDec.intVal); 3056 return xs == s; 3057 } else if (xs != INFLATED) 3058 return xs == compactValFor(this.intVal); 3059 3060 return this.inflated().equals(xDec.inflated()); 3061 } 3062 3063 /** 3064 * Returns the minimum of this {@code BigDecimal} and 3065 * {@code val}. 3066 * 3067 * @param val value with which the minimum is to be computed. 3068 * @return the {@code BigDecimal} whose value is the lesser of this 3069 * {@code BigDecimal} and {@code val}. If they are equal, 3070 * as defined by the {@link #compareTo(BigDecimal) compareTo} 3071 * method, {@code this} is returned. 3072 * @see #compareTo(java.math.BigDecimal) 3073 */ 3074 public BigDecimal min(BigDecimal val) { 3075 return (compareTo(val) <= 0 ? this : val); 3076 } 3077 3078 /** 3079 * Returns the maximum of this {@code BigDecimal} and {@code val}. 3080 * 3081 * @param val value with which the maximum is to be computed. 3082 * @return the {@code BigDecimal} whose value is the greater of this 3083 * {@code BigDecimal} and {@code val}. If they are equal, 3084 * as defined by the {@link #compareTo(BigDecimal) compareTo} 3085 * method, {@code this} is returned. 3086 * @see #compareTo(java.math.BigDecimal) 3087 */ 3088 public BigDecimal max(BigDecimal val) { 3089 return (compareTo(val) >= 0 ? this : val); 3090 } 3091 3092 // Hash Function 3093 3094 /** 3095 * Returns the hash code for this {@code BigDecimal}. Note that 3096 * two {@code BigDecimal} objects that are numerically equal but 3097 * differ in scale (like 2.0 and 2.00) will generally <em>not</em> 3098 * have the same hash code. 3099 * 3100 * @return hash code for this {@code BigDecimal}. 3101 * @see #equals(Object) 3102 */ 3103 @Override 3104 public int hashCode() { 3105 if (intCompact != INFLATED) { 3106 long val2 = (intCompact < 0)? -intCompact : intCompact; 3107 int temp = (int)( ((int)(val2 >>> 32)) * 31 + 3108 (val2 & LONG_MASK)); 3109 return 31*((intCompact < 0) ?-temp:temp) + scale; 3110 } else 3111 return 31*intVal.hashCode() + scale; 3112 } 3113 3114 // Format Converters 3115 3116 /** 3117 * Returns the string representation of this {@code BigDecimal}, 3118 * using scientific notation if an exponent is needed. 3119 * 3120 * <p>A standard canonical string form of the {@code BigDecimal} 3121 * is created as though by the following steps: first, the 3122 * absolute value of the unscaled value of the {@code BigDecimal} 3123 * is converted to a string in base ten using the characters 3124 * {@code '0'} through {@code '9'} with no leading zeros (except 3125 * if its value is zero, in which case a single {@code '0'} 3126 * character is used). 3127 * 3128 * <p>Next, an <i>adjusted exponent</i> is calculated; this is the 3129 * negated scale, plus the number of characters in the converted 3130 * unscaled value, less one. That is, 3131 * {@code -scale+(ulength-1)}, where {@code ulength} is the 3132 * length of the absolute value of the unscaled value in decimal 3133 * digits (its <i>precision</i>). 3134 * 3135 * <p>If the scale is greater than or equal to zero and the 3136 * adjusted exponent is greater than or equal to {@code -6}, the 3137 * number will be converted to a character form without using 3138 * exponential notation. In this case, if the scale is zero then 3139 * no decimal point is added and if the scale is positive a 3140 * decimal point will be inserted with the scale specifying the 3141 * number of characters to the right of the decimal point. 3142 * {@code '0'} characters are added to the left of the converted 3143 * unscaled value as necessary. If no character precedes the 3144 * decimal point after this insertion then a conventional 3145 * {@code '0'} character is prefixed. 3146 * 3147 * <p>Otherwise (that is, if the scale is negative, or the 3148 * adjusted exponent is less than {@code -6}), the number will be 3149 * converted to a character form using exponential notation. In 3150 * this case, if the converted {@code BigInteger} has more than 3151 * one digit a decimal point is inserted after the first digit. 3152 * An exponent in character form is then suffixed to the converted 3153 * unscaled value (perhaps with inserted decimal point); this 3154 * comprises the letter {@code 'E'} followed immediately by the 3155 * adjusted exponent converted to a character form. The latter is 3156 * in base ten, using the characters {@code '0'} through 3157 * {@code '9'} with no leading zeros, and is always prefixed by a 3158 * sign character {@code '-'} (<code>'\u002D'</code>) if the 3159 * adjusted exponent is negative, {@code '+'} 3160 * (<code>'\u002B'</code>) otherwise). 3161 * 3162 * <p>Finally, the entire string is prefixed by a minus sign 3163 * character {@code '-'} (<code>'\u002D'</code>) if the unscaled 3164 * value is less than zero. No sign character is prefixed if the 3165 * unscaled value is zero or positive. 3166 * 3167 * <p><b>Examples:</b> 3168 * <p>For each representation [<i>unscaled value</i>, <i>scale</i>] 3169 * on the left, the resulting string is shown on the right. 3170 * <pre> 3171 * [123,0] "123" 3172 * [-123,0] "-123" 3173 * [123,-1] "1.23E+3" 3174 * [123,-3] "1.23E+5" 3175 * [123,1] "12.3" 3176 * [123,5] "0.00123" 3177 * [123,10] "1.23E-8" 3178 * [-123,12] "-1.23E-10" 3179 * </pre> 3180 * 3181 * <b>Notes:</b> 3182 * <ol> 3183 * 3184 * <li>There is a one-to-one mapping between the distinguishable 3185 * {@code BigDecimal} values and the result of this conversion. 3186 * That is, every distinguishable {@code BigDecimal} value 3187 * (unscaled value and scale) has a unique string representation 3188 * as a result of using {@code toString}. If that string 3189 * representation is converted back to a {@code BigDecimal} using 3190 * the {@link #BigDecimal(String)} constructor, then the original 3191 * value will be recovered. 3192 * 3193 * <li>The string produced for a given number is always the same; 3194 * it is not affected by locale. This means that it can be used 3195 * as a canonical string representation for exchanging decimal 3196 * data, or as a key for a Hashtable, etc. Locale-sensitive 3197 * number formatting and parsing is handled by the {@link 3198 * java.text.NumberFormat} class and its subclasses. 3199 * 3200 * <li>The {@link #toEngineeringString} method may be used for 3201 * presenting numbers with exponents in engineering notation, and the 3202 * {@link #setScale(int,RoundingMode) setScale} method may be used for 3203 * rounding a {@code BigDecimal} so it has a known number of digits after 3204 * the decimal point. 3205 * 3206 * <li>The digit-to-character mapping provided by 3207 * {@code Character.forDigit} is used. 3208 * 3209 * </ol> 3210 * 3211 * @return string representation of this {@code BigDecimal}. 3212 * @see Character#forDigit 3213 * @see #BigDecimal(java.lang.String) 3214 */ 3215 @Override 3216 public String toString() { 3217 String sc = stringCache; 3218 if (sc == null) { 3219 stringCache = sc = layoutChars(true); 3220 } 3221 return sc; 3222 } 3223 3224 /** 3225 * Returns a string representation of this {@code BigDecimal}, 3226 * using engineering notation if an exponent is needed. 3227 * 3228 * <p>Returns a string that represents the {@code BigDecimal} as 3229 * described in the {@link #toString()} method, except that if 3230 * exponential notation is used, the power of ten is adjusted to 3231 * be a multiple of three (engineering notation) such that the 3232 * integer part of nonzero values will be in the range 1 through 3233 * 999. If exponential notation is used for zero values, a 3234 * decimal point and one or two fractional zero digits are used so 3235 * that the scale of the zero value is preserved. Note that 3236 * unlike the output of {@link #toString()}, the output of this 3237 * method is <em>not</em> guaranteed to recover the same [integer, 3238 * scale] pair of this {@code BigDecimal} if the output string is 3239 * converting back to a {@code BigDecimal} using the {@linkplain 3240 * #BigDecimal(String) string constructor}. The result of this method meets 3241 * the weaker constraint of always producing a numerically equal 3242 * result from applying the string constructor to the method's output. 3243 * 3244 * @return string representation of this {@code BigDecimal}, using 3245 * engineering notation if an exponent is needed. 3246 * @since 1.5 3247 */ 3248 public String toEngineeringString() { 3249 return layoutChars(false); 3250 } 3251 3252 /** 3253 * Returns a string representation of this {@code BigDecimal} 3254 * without an exponent field. For values with a positive scale, 3255 * the number of digits to the right of the decimal point is used 3256 * to indicate scale. For values with a zero or negative scale, 3257 * the resulting string is generated as if the value were 3258 * converted to a numerically equal value with zero scale and as 3259 * if all the trailing zeros of the zero scale value were present 3260 * in the result. 3261 * 3262 * The entire string is prefixed by a minus sign character '-' 3263 * (<code>'\u002D'</code>) if the unscaled value is less than 3264 * zero. No sign character is prefixed if the unscaled value is 3265 * zero or positive. 3266 * 3267 * Note that if the result of this method is passed to the 3268 * {@linkplain #BigDecimal(String) string constructor}, only the 3269 * numerical value of this {@code BigDecimal} will necessarily be 3270 * recovered; the representation of the new {@code BigDecimal} 3271 * may have a different scale. In particular, if this 3272 * {@code BigDecimal} has a negative scale, the string resulting 3273 * from this method will have a scale of zero when processed by 3274 * the string constructor. 3275 * 3276 * (This method behaves analogously to the {@code toString} 3277 * method in 1.4 and earlier releases.) 3278 * 3279 * @return a string representation of this {@code BigDecimal} 3280 * without an exponent field. 3281 * @since 1.5 3282 * @see #toString() 3283 * @see #toEngineeringString() 3284 */ 3285 public String toPlainString() { 3286 if(scale==0) { 3287 if(intCompact!=INFLATED) { 3288 return Long.toString(intCompact); 3289 } else { 3290 return intVal.toString(); 3291 } 3292 } 3293 if(this.scale<0) { // No decimal point 3294 if(signum()==0) { 3295 return "0"; 3296 } 3297 int trailingZeros = checkScaleNonZero((-(long)scale)); 3298 StringBuilder buf; 3299 if(intCompact!=INFLATED) { 3300 buf = new StringBuilder(20+trailingZeros); 3301 buf.append(intCompact); 3302 } else { 3303 String str = intVal.toString(); 3304 buf = new StringBuilder(str.length()+trailingZeros); 3305 buf.append(str); 3306 } 3307 for (int i = 0; i < trailingZeros; i++) { 3308 buf.append('0'); 3309 } 3310 return buf.toString(); 3311 } 3312 String str ; 3313 if(intCompact!=INFLATED) { 3314 str = Long.toString(Math.abs(intCompact)); 3315 } else { 3316 str = intVal.abs().toString(); 3317 } 3318 return getValueString(signum(), str, scale); 3319 } 3320 3321 /* Returns a digit.digit string */ 3322 private String getValueString(int signum, String intString, int scale) { 3323 /* Insert decimal point */ 3324 StringBuilder buf; 3325 int insertionPoint = intString.length() - scale; 3326 if (insertionPoint == 0) { /* Point goes right before intVal */ 3327 return (signum<0 ? "-0." : "0.") + intString; 3328 } else if (insertionPoint > 0) { /* Point goes inside intVal */ 3329 buf = new StringBuilder(intString); 3330 buf.insert(insertionPoint, '.'); 3331 if (signum < 0) 3332 buf.insert(0, '-'); 3333 } else { /* We must insert zeros between point and intVal */ 3334 buf = new StringBuilder(3-insertionPoint + intString.length()); 3335 buf.append(signum<0 ? "-0." : "0."); 3336 for (int i=0; i<-insertionPoint; i++) { 3337 buf.append('0'); 3338 } 3339 buf.append(intString); 3340 } 3341 return buf.toString(); 3342 } 3343 3344 /** 3345 * Converts this {@code BigDecimal} to a {@code BigInteger}. 3346 * This conversion is analogous to the 3347 * <i>narrowing primitive conversion</i> from {@code double} to 3348 * {@code long} as defined in 3349 * <cite>The Java™ Language Specification</cite>: 3350 * any fractional part of this 3351 * {@code BigDecimal} will be discarded. Note that this 3352 * conversion can lose information about the precision of the 3353 * {@code BigDecimal} value. 3354 * <p> 3355 * To have an exception thrown if the conversion is inexact (in 3356 * other words if a nonzero fractional part is discarded), use the 3357 * {@link #toBigIntegerExact()} method. 3358 * 3359 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 3360 * @jls 5.1.3 Narrowing Primitive Conversion 3361 */ 3362 public BigInteger toBigInteger() { 3363 // force to an integer, quietly 3364 return this.setScale(0, ROUND_DOWN).inflated(); 3365 } 3366 3367 /** 3368 * Converts this {@code BigDecimal} to a {@code BigInteger}, 3369 * checking for lost information. An exception is thrown if this 3370 * {@code BigDecimal} has a nonzero fractional part. 3371 * 3372 * @return this {@code BigDecimal} converted to a {@code BigInteger}. 3373 * @throws ArithmeticException if {@code this} has a nonzero 3374 * fractional part. 3375 * @since 1.5 3376 */ 3377 public BigInteger toBigIntegerExact() { 3378 // round to an integer, with Exception if decimal part non-0 3379 return this.setScale(0, ROUND_UNNECESSARY).inflated(); 3380 } 3381 3382 /** 3383 * Converts this {@code BigDecimal} to a {@code long}. 3384 * This conversion is analogous to the 3385 * <i>narrowing primitive conversion</i> from {@code double} to 3386 * {@code short} as defined in 3387 * <cite>The Java™ Language Specification</cite>: 3388 * any fractional part of this 3389 * {@code BigDecimal} will be discarded, and if the resulting 3390 * "{@code BigInteger}" is too big to fit in a 3391 * {@code long}, only the low-order 64 bits are returned. 3392 * Note that this conversion can lose information about the 3393 * overall magnitude and precision of this {@code BigDecimal} value as well 3394 * as return a result with the opposite sign. 3395 * 3396 * @return this {@code BigDecimal} converted to a {@code long}. 3397 * @jls 5.1.3 Narrowing Primitive Conversion 3398 */ 3399 @Override 3400 public long longValue(){ 3401 return (intCompact != INFLATED && scale == 0) ? 3402 intCompact: 3403 toBigInteger().longValue(); 3404 } 3405 3406 /** 3407 * Converts this {@code BigDecimal} to a {@code long}, checking 3408 * for lost information. If this {@code BigDecimal} has a 3409 * nonzero fractional part or is out of the possible range for a 3410 * {@code long} result then an {@code ArithmeticException} is 3411 * thrown. 3412 * 3413 * @return this {@code BigDecimal} converted to a {@code long}. 3414 * @throws ArithmeticException if {@code this} has a nonzero 3415 * fractional part, or will not fit in a {@code long}. 3416 * @since 1.5 3417 */ 3418 public long longValueExact() { 3419 if (intCompact != INFLATED && scale == 0) 3420 return intCompact; 3421 // If more than 19 digits in integer part it cannot possibly fit 3422 if ((precision() - scale) > 19) // [OK for negative scale too] 3423 throw new java.lang.ArithmeticException("Overflow"); 3424 // Fastpath zero and < 1.0 numbers (the latter can be very slow 3425 // to round if very small) 3426 if (this.signum() == 0) 3427 return 0; 3428 if ((this.precision() - this.scale) <= 0) 3429 throw new ArithmeticException("Rounding necessary"); 3430 // round to an integer, with Exception if decimal part non-0 3431 BigDecimal num = this.setScale(0, ROUND_UNNECESSARY); 3432 if (num.precision() >= 19) // need to check carefully 3433 LongOverflow.check(num); 3434 return num.inflated().longValue(); 3435 } 3436 3437 private static class LongOverflow { 3438 /** BigInteger equal to Long.MIN_VALUE. */ 3439 private static final BigInteger LONGMIN = BigInteger.valueOf(Long.MIN_VALUE); 3440 3441 /** BigInteger equal to Long.MAX_VALUE. */ 3442 private static final BigInteger LONGMAX = BigInteger.valueOf(Long.MAX_VALUE); 3443 3444 public static void check(BigDecimal num) { 3445 BigInteger intVal = num.inflated(); 3446 if (intVal.compareTo(LONGMIN) < 0 || 3447 intVal.compareTo(LONGMAX) > 0) 3448 throw new java.lang.ArithmeticException("Overflow"); 3449 } 3450 } 3451 3452 /** 3453 * Converts this {@code BigDecimal} to an {@code int}. 3454 * This conversion is analogous to the 3455 * <i>narrowing primitive conversion</i> from {@code double} to 3456 * {@code short} as defined in 3457 * <cite>The Java™ Language Specification</cite>: 3458 * any fractional part of this 3459 * {@code BigDecimal} will be discarded, and if the resulting 3460 * "{@code BigInteger}" is too big to fit in an 3461 * {@code int}, only the low-order 32 bits are returned. 3462 * Note that this conversion can lose information about the 3463 * overall magnitude and precision of this {@code BigDecimal} 3464 * value as well as return a result with the opposite sign. 3465 * 3466 * @return this {@code BigDecimal} converted to an {@code int}. 3467 * @jls 5.1.3 Narrowing Primitive Conversion 3468 */ 3469 @Override 3470 public int intValue() { 3471 return (intCompact != INFLATED && scale == 0) ? 3472 (int)intCompact : 3473 toBigInteger().intValue(); 3474 } 3475 3476 /** 3477 * Converts this {@code BigDecimal} to an {@code int}, checking 3478 * for lost information. If this {@code BigDecimal} has a 3479 * nonzero fractional part or is out of the possible range for an 3480 * {@code int} result then an {@code ArithmeticException} is 3481 * thrown. 3482 * 3483 * @return this {@code BigDecimal} converted to an {@code int}. 3484 * @throws ArithmeticException if {@code this} has a nonzero 3485 * fractional part, or will not fit in an {@code int}. 3486 * @since 1.5 3487 */ 3488 public int intValueExact() { 3489 long num; 3490 num = this.longValueExact(); // will check decimal part 3491 if ((int)num != num) 3492 throw new java.lang.ArithmeticException("Overflow"); 3493 return (int)num; 3494 } 3495 3496 /** 3497 * Converts this {@code BigDecimal} to a {@code short}, checking 3498 * for lost information. If this {@code BigDecimal} has a 3499 * nonzero fractional part or is out of the possible range for a 3500 * {@code short} result then an {@code ArithmeticException} is 3501 * thrown. 3502 * 3503 * @return this {@code BigDecimal} converted to a {@code short}. 3504 * @throws ArithmeticException if {@code this} has a nonzero 3505 * fractional part, or will not fit in a {@code short}. 3506 * @since 1.5 3507 */ 3508 public short shortValueExact() { 3509 long num; 3510 num = this.longValueExact(); // will check decimal part 3511 if ((short)num != num) 3512 throw new java.lang.ArithmeticException("Overflow"); 3513 return (short)num; 3514 } 3515 3516 /** 3517 * Converts this {@code BigDecimal} to a {@code byte}, checking 3518 * for lost information. If this {@code BigDecimal} has a 3519 * nonzero fractional part or is out of the possible range for a 3520 * {@code byte} result then an {@code ArithmeticException} is 3521 * thrown. 3522 * 3523 * @return this {@code BigDecimal} converted to a {@code byte}. 3524 * @throws ArithmeticException if {@code this} has a nonzero 3525 * fractional part, or will not fit in a {@code byte}. 3526 * @since 1.5 3527 */ 3528 public byte byteValueExact() { 3529 long num; 3530 num = this.longValueExact(); // will check decimal part 3531 if ((byte)num != num) 3532 throw new java.lang.ArithmeticException("Overflow"); 3533 return (byte)num; 3534 } 3535 3536 /** 3537 * Converts this {@code BigDecimal} to a {@code float}. 3538 * This conversion is similar to the 3539 * <i>narrowing primitive conversion</i> from {@code double} to 3540 * {@code float} as defined in 3541 * <cite>The Java™ Language Specification</cite>: 3542 * if this {@code BigDecimal} has too great a 3543 * magnitude to represent as a {@code float}, it will be 3544 * converted to {@link Float#NEGATIVE_INFINITY} or {@link 3545 * Float#POSITIVE_INFINITY} as appropriate. Note that even when 3546 * the return value is finite, this conversion can lose 3547 * information about the precision of the {@code BigDecimal} 3548 * value. 3549 * 3550 * @return this {@code BigDecimal} converted to a {@code float}. 3551 * @jls 5.1.3 Narrowing Primitive Conversion 3552 */ 3553 @Override 3554 public float floatValue(){ 3555 if(intCompact != INFLATED) { 3556 if (scale == 0) { 3557 return (float)intCompact; 3558 } else { 3559 /* 3560 * If both intCompact and the scale can be exactly 3561 * represented as float values, perform a single float 3562 * multiply or divide to compute the (properly 3563 * rounded) result. 3564 */ 3565 if (Math.abs(intCompact) < 1L<<22 ) { 3566 // Don't have too guard against 3567 // Math.abs(MIN_VALUE) because of outer check 3568 // against INFLATED. 3569 if (scale > 0 && scale < FLOAT_10_POW.length) { 3570 return (float)intCompact / FLOAT_10_POW[scale]; 3571 } else if (scale < 0 && scale > -FLOAT_10_POW.length) { 3572 return (float)intCompact * FLOAT_10_POW[-scale]; 3573 } 3574 } 3575 } 3576 } 3577 // Somewhat inefficient, but guaranteed to work. 3578 return Float.parseFloat(this.toString()); 3579 } 3580 3581 /** 3582 * Converts this {@code BigDecimal} to a {@code double}. 3583 * This conversion is similar to the 3584 * <i>narrowing primitive conversion</i> from {@code double} to 3585 * {@code float} as defined 3586 * <cite>The Java™ Language Specification</cite>: 3587 * if this {@code BigDecimal} has too great a 3588 * magnitude represent as a {@code double}, it will be 3589 * converted to {@link Double#NEGATIVE_INFINITY} or {@link 3590 * Double#POSITIVE_INFINITY} as appropriate. Note that even when 3591 * the return value is finite, this conversion can lose 3592 * information about the precision of the {@code BigDecimal} 3593 * value. 3594 * 3595 * @return this {@code BigDecimal} converted to a {@code double}. 3596 * @jls 5.1.3 Narrowing Primitive Conversion 3597 */ 3598 @Override 3599 public double doubleValue(){ 3600 if(intCompact != INFLATED) { 3601 if (scale == 0) { 3602 return (double)intCompact; 3603 } else { 3604 /* 3605 * If both intCompact and the scale can be exactly 3606 * represented as double values, perform a single 3607 * double multiply or divide to compute the (properly 3608 * rounded) result. 3609 */ 3610 if (Math.abs(intCompact) < 1L<<52 ) { 3611 // Don't have too guard against 3612 // Math.abs(MIN_VALUE) because of outer check 3613 // against INFLATED. 3614 if (scale > 0 && scale < DOUBLE_10_POW.length) { 3615 return (double)intCompact / DOUBLE_10_POW[scale]; 3616 } else if (scale < 0 && scale > -DOUBLE_10_POW.length) { 3617 return (double)intCompact * DOUBLE_10_POW[-scale]; 3618 } 3619 } 3620 } 3621 } 3622 // Somewhat inefficient, but guaranteed to work. 3623 return Double.parseDouble(this.toString()); 3624 } 3625 3626 /** 3627 * Powers of 10 which can be represented exactly in {@code 3628 * double}. 3629 */ 3630 private static final double DOUBLE_10_POW[] = { 3631 1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 3632 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11, 3633 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17, 3634 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22 3635 }; 3636 3637 /** 3638 * Powers of 10 which can be represented exactly in {@code 3639 * float}. 3640 */ 3641 private static final float FLOAT_10_POW[] = { 3642 1.0e0f, 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f, 3643 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f 3644 }; 3645 3646 /** 3647 * Returns the size of an ulp, a unit in the last place, of this 3648 * {@code BigDecimal}. An ulp of a nonzero {@code BigDecimal} 3649 * value is the positive distance between this value and the 3650 * {@code BigDecimal} value next larger in magnitude with the 3651 * same number of digits. An ulp of a zero value is numerically 3652 * equal to 1 with the scale of {@code this}. The result is 3653 * stored with the same scale as {@code this} so the result 3654 * for zero and nonzero values is equal to {@code [1, 3655 * this.scale()]}. 3656 * 3657 * @return the size of an ulp of {@code this} 3658 * @since 1.5 3659 */ 3660 public BigDecimal ulp() { 3661 return BigDecimal.valueOf(1, this.scale(), 1); 3662 } 3663 3664 // Private class to build a string representation for BigDecimal object. 3665 // "StringBuilderHelper" is constructed as a thread local variable so it is 3666 // thread safe. The StringBuilder field acts as a buffer to hold the temporary 3667 // representation of BigDecimal. The cmpCharArray holds all the characters for 3668 // the compact representation of BigDecimal (except for '-' sign' if it is 3669 // negative) if its intCompact field is not INFLATED. It is shared by all 3670 // calls to toString() and its variants in that particular thread. 3671 static class StringBuilderHelper { 3672 final StringBuilder sb; // Placeholder for BigDecimal string 3673 final char[] cmpCharArray; // character array to place the intCompact 3674 3675 StringBuilderHelper() { 3676 sb = new StringBuilder(); 3677 // All non negative longs can be made to fit into 19 character array. 3678 cmpCharArray = new char[19]; 3679 } 3680 3681 // Accessors. 3682 StringBuilder getStringBuilder() { 3683 sb.setLength(0); 3684 return sb; 3685 } 3686 3687 char[] getCompactCharArray() { 3688 return cmpCharArray; 3689 } 3690 3691 /** 3692 * Places characters representing the intCompact in {@code long} into 3693 * cmpCharArray and returns the offset to the array where the 3694 * representation starts. 3695 * 3696 * @param intCompact the number to put into the cmpCharArray. 3697 * @return offset to the array where the representation starts. 3698 * Note: intCompact must be greater or equal to zero. 3699 */ 3700 int putIntCompact(long intCompact) { 3701 assert intCompact >= 0; 3702 3703 long q; 3704 int r; 3705 // since we start from the least significant digit, charPos points to 3706 // the last character in cmpCharArray. 3707 int charPos = cmpCharArray.length; 3708 3709 // Get 2 digits/iteration using longs until quotient fits into an int 3710 while (intCompact > Integer.MAX_VALUE) { 3711 q = intCompact / 100; 3712 r = (int)(intCompact - q * 100); 3713 intCompact = q; 3714 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3715 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3716 } 3717 3718 // Get 2 digits/iteration using ints when i2 >= 100 3719 int q2; 3720 int i2 = (int)intCompact; 3721 while (i2 >= 100) { 3722 q2 = i2 / 100; 3723 r = i2 - q2 * 100; 3724 i2 = q2; 3725 cmpCharArray[--charPos] = DIGIT_ONES[r]; 3726 cmpCharArray[--charPos] = DIGIT_TENS[r]; 3727 } 3728 3729 cmpCharArray[--charPos] = DIGIT_ONES[i2]; 3730 if (i2 >= 10) 3731 cmpCharArray[--charPos] = DIGIT_TENS[i2]; 3732 3733 return charPos; 3734 } 3735 3736 static final char[] DIGIT_TENS = { 3737 '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 3738 '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', 3739 '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', 3740 '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', 3741 '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', 3742 '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', 3743 '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', 3744 '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', 3745 '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', 3746 '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', 3747 }; 3748 3749 static final char[] DIGIT_ONES = { 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 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3758 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3759 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3760 }; 3761 } 3762 3763 /** 3764 * Lay out this {@code BigDecimal} into a {@code char[]} array. 3765 * The Java 1.2 equivalent to this was called {@code getValueString}. 3766 * 3767 * @param sci {@code true} for Scientific exponential notation; 3768 * {@code false} for Engineering 3769 * @return string with canonical string representation of this 3770 * {@code BigDecimal} 3771 */ 3772 private String layoutChars(boolean sci) { 3773 if (scale == 0) // zero scale is trivial 3774 return (intCompact != INFLATED) ? 3775 Long.toString(intCompact): 3776 intVal.toString(); 3777 if (scale == 2 && 3778 intCompact >= 0 && intCompact < Integer.MAX_VALUE) { 3779 // currency fast path 3780 int lowInt = (int)intCompact % 100; 3781 int highInt = (int)intCompact / 100; 3782 return (Integer.toString(highInt) + '.' + 3783 StringBuilderHelper.DIGIT_TENS[lowInt] + 3784 StringBuilderHelper.DIGIT_ONES[lowInt]) ; 3785 } 3786 3787 StringBuilderHelper sbHelper = threadLocalStringBuilderHelper.get(); 3788 char[] coeff; 3789 int offset; // offset is the starting index for coeff array 3790 // Get the significand as an absolute value 3791 if (intCompact != INFLATED) { 3792 offset = sbHelper.putIntCompact(Math.abs(intCompact)); 3793 coeff = sbHelper.getCompactCharArray(); 3794 } else { 3795 offset = 0; 3796 coeff = intVal.abs().toString().toCharArray(); 3797 } 3798 3799 // Construct a buffer, with sufficient capacity for all cases. 3800 // If E-notation is needed, length will be: +1 if negative, +1 3801 // if '.' needed, +2 for "E+", + up to 10 for adjusted exponent. 3802 // Otherwise it could have +1 if negative, plus leading "0.00000" 3803 StringBuilder buf = sbHelper.getStringBuilder(); 3804 if (signum() < 0) // prefix '-' if negative 3805 buf.append('-'); 3806 int coeffLen = coeff.length - offset; 3807 long adjusted = -(long)scale + (coeffLen -1); 3808 if ((scale >= 0) && (adjusted >= -6)) { // plain number 3809 int pad = scale - coeffLen; // count of padding zeros 3810 if (pad >= 0) { // 0.xxx form 3811 buf.append('0'); 3812 buf.append('.'); 3813 for (; pad>0; pad--) { 3814 buf.append('0'); 3815 } 3816 buf.append(coeff, offset, coeffLen); 3817 } else { // xx.xx form 3818 buf.append(coeff, offset, -pad); 3819 buf.append('.'); 3820 buf.append(coeff, -pad + offset, scale); 3821 } 3822 } else { // E-notation is needed 3823 if (sci) { // Scientific notation 3824 buf.append(coeff[offset]); // first character 3825 if (coeffLen > 1) { // more to come 3826 buf.append('.'); 3827 buf.append(coeff, offset + 1, coeffLen - 1); 3828 } 3829 } else { // Engineering notation 3830 int sig = (int)(adjusted % 3); 3831 if (sig < 0) 3832 sig += 3; // [adjusted was negative] 3833 adjusted -= sig; // now a multiple of 3 3834 sig++; 3835 if (signum() == 0) { 3836 switch (sig) { 3837 case 1: 3838 buf.append('0'); // exponent is a multiple of three 3839 break; 3840 case 2: 3841 buf.append("0.00"); 3842 adjusted += 3; 3843 break; 3844 case 3: 3845 buf.append("0.0"); 3846 adjusted += 3; 3847 break; 3848 default: 3849 throw new AssertionError("Unexpected sig value " + sig); 3850 } 3851 } else if (sig >= coeffLen) { // significand all in integer 3852 buf.append(coeff, offset, coeffLen); 3853 // may need some zeros, too 3854 for (int i = sig - coeffLen; i > 0; i--) { 3855 buf.append('0'); 3856 } 3857 } else { // xx.xxE form 3858 buf.append(coeff, offset, sig); 3859 buf.append('.'); 3860 buf.append(coeff, offset + sig, coeffLen - sig); 3861 } 3862 } 3863 if (adjusted != 0) { // [!sci could have made 0] 3864 buf.append('E'); 3865 if (adjusted > 0) // force sign for positive 3866 buf.append('+'); 3867 buf.append(adjusted); 3868 } 3869 } 3870 return buf.toString(); 3871 } 3872 3873 /** 3874 * Return 10 to the power n, as a {@code BigInteger}. 3875 * 3876 * @param n the power of ten to be returned (>=0) 3877 * @return a {@code BigInteger} with the value (10<sup>n</sup>) 3878 */ 3879 private static BigInteger bigTenToThe(int n) { 3880 if (n < 0) 3881 return BigInteger.ZERO; 3882 3883 if (n < BIG_TEN_POWERS_TABLE_MAX) { 3884 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3885 if (n < pows.length) 3886 return pows[n]; 3887 else 3888 return expandBigIntegerTenPowers(n); 3889 } 3890 3891 return BigInteger.TEN.pow(n); 3892 } 3893 3894 /** 3895 * Expand the BIG_TEN_POWERS_TABLE array to contain at least 10**n. 3896 * 3897 * @param n the power of ten to be returned (>=0) 3898 * @return a {@code BigDecimal} with the value (10<sup>n</sup>) and 3899 * in the meantime, the BIG_TEN_POWERS_TABLE array gets 3900 * expanded to the size greater than n. 3901 */ 3902 private static BigInteger expandBigIntegerTenPowers(int n) { 3903 synchronized(BigDecimal.class) { 3904 BigInteger[] pows = BIG_TEN_POWERS_TABLE; 3905 int curLen = pows.length; 3906 // The following comparison and the above synchronized statement is 3907 // to prevent multiple threads from expanding the same array. 3908 if (curLen <= n) { 3909 int newLen = curLen << 1; 3910 while (newLen <= n) { 3911 newLen <<= 1; 3912 } 3913 pows = Arrays.copyOf(pows, newLen); 3914 for (int i = curLen; i < newLen; i++) { 3915 pows[i] = pows[i - 1].multiply(BigInteger.TEN); 3916 } 3917 // Based on the following facts: 3918 // 1. pows is a private local varible; 3919 // 2. the following store is a volatile store. 3920 // the newly created array elements can be safely published. 3921 BIG_TEN_POWERS_TABLE = pows; 3922 } 3923 return pows[n]; 3924 } 3925 } 3926 3927 private static final long[] LONG_TEN_POWERS_TABLE = { 3928 1, // 0 / 10^0 3929 10, // 1 / 10^1 3930 100, // 2 / 10^2 3931 1000, // 3 / 10^3 3932 10000, // 4 / 10^4 3933 100000, // 5 / 10^5 3934 1000000, // 6 / 10^6 3935 10000000, // 7 / 10^7 3936 100000000, // 8 / 10^8 3937 1000000000, // 9 / 10^9 3938 10000000000L, // 10 / 10^10 3939 100000000000L, // 11 / 10^11 3940 1000000000000L, // 12 / 10^12 3941 10000000000000L, // 13 / 10^13 3942 100000000000000L, // 14 / 10^14 3943 1000000000000000L, // 15 / 10^15 3944 10000000000000000L, // 16 / 10^16 3945 100000000000000000L, // 17 / 10^17 3946 1000000000000000000L // 18 / 10^18 3947 }; 3948 3949 private static volatile BigInteger BIG_TEN_POWERS_TABLE[] = { 3950 BigInteger.ONE, 3951 BigInteger.valueOf(10), 3952 BigInteger.valueOf(100), 3953 BigInteger.valueOf(1000), 3954 BigInteger.valueOf(10000), 3955 BigInteger.valueOf(100000), 3956 BigInteger.valueOf(1000000), 3957 BigInteger.valueOf(10000000), 3958 BigInteger.valueOf(100000000), 3959 BigInteger.valueOf(1000000000), 3960 BigInteger.valueOf(10000000000L), 3961 BigInteger.valueOf(100000000000L), 3962 BigInteger.valueOf(1000000000000L), 3963 BigInteger.valueOf(10000000000000L), 3964 BigInteger.valueOf(100000000000000L), 3965 BigInteger.valueOf(1000000000000000L), 3966 BigInteger.valueOf(10000000000000000L), 3967 BigInteger.valueOf(100000000000000000L), 3968 BigInteger.valueOf(1000000000000000000L) 3969 }; 3970 3971 private static final int BIG_TEN_POWERS_TABLE_INITLEN = 3972 BIG_TEN_POWERS_TABLE.length; 3973 private static final int BIG_TEN_POWERS_TABLE_MAX = 3974 16 * BIG_TEN_POWERS_TABLE_INITLEN; 3975 3976 private static final long THRESHOLDS_TABLE[] = { 3977 Long.MAX_VALUE, // 0 3978 Long.MAX_VALUE/10L, // 1 3979 Long.MAX_VALUE/100L, // 2 3980 Long.MAX_VALUE/1000L, // 3 3981 Long.MAX_VALUE/10000L, // 4 3982 Long.MAX_VALUE/100000L, // 5 3983 Long.MAX_VALUE/1000000L, // 6 3984 Long.MAX_VALUE/10000000L, // 7 3985 Long.MAX_VALUE/100000000L, // 8 3986 Long.MAX_VALUE/1000000000L, // 9 3987 Long.MAX_VALUE/10000000000L, // 10 3988 Long.MAX_VALUE/100000000000L, // 11 3989 Long.MAX_VALUE/1000000000000L, // 12 3990 Long.MAX_VALUE/10000000000000L, // 13 3991 Long.MAX_VALUE/100000000000000L, // 14 3992 Long.MAX_VALUE/1000000000000000L, // 15 3993 Long.MAX_VALUE/10000000000000000L, // 16 3994 Long.MAX_VALUE/100000000000000000L, // 17 3995 Long.MAX_VALUE/1000000000000000000L // 18 3996 }; 3997 3998 /** 3999 * Compute val * 10 ^ n; return this product if it is 4000 * representable as a long, INFLATED otherwise. 4001 */ 4002 private static long longMultiplyPowerTen(long val, int n) { 4003 if (val == 0 || n <= 0) 4004 return val; 4005 long[] tab = LONG_TEN_POWERS_TABLE; 4006 long[] bounds = THRESHOLDS_TABLE; 4007 if (n < tab.length && n < bounds.length) { 4008 long tenpower = tab[n]; 4009 if (val == 1) 4010 return tenpower; 4011 if (Math.abs(val) <= bounds[n]) 4012 return val * tenpower; 4013 } 4014 return INFLATED; 4015 } 4016 4017 /** 4018 * Compute this * 10 ^ n. 4019 * Needed mainly to allow special casing to trap zero value 4020 */ 4021 private BigInteger bigMultiplyPowerTen(int n) { 4022 if (n <= 0) 4023 return this.inflated(); 4024 4025 if (intCompact != INFLATED) 4026 return bigTenToThe(n).multiply(intCompact); 4027 else 4028 return intVal.multiply(bigTenToThe(n)); 4029 } 4030 4031 /** 4032 * Returns appropriate BigInteger from intVal field if intVal is 4033 * null, i.e. the compact representation is in use. 4034 */ 4035 private BigInteger inflated() { 4036 if (intVal == null) { 4037 return BigInteger.valueOf(intCompact); 4038 } 4039 return intVal; 4040 } 4041 4042 /** 4043 * Match the scales of two {@code BigDecimal}s to align their 4044 * least significant digits. 4045 * 4046 * <p>If the scales of val[0] and val[1] differ, rescale 4047 * (non-destructively) the lower-scaled {@code BigDecimal} so 4048 * they match. That is, the lower-scaled reference will be 4049 * replaced by a reference to a new object with the same scale as 4050 * the other {@code BigDecimal}. 4051 * 4052 * @param val array of two elements referring to the two 4053 * {@code BigDecimal}s to be aligned. 4054 */ 4055 private static void matchScale(BigDecimal[] val) { 4056 if (val[0].scale < val[1].scale) { 4057 val[0] = val[0].setScale(val[1].scale, ROUND_UNNECESSARY); 4058 } else if (val[1].scale < val[0].scale) { 4059 val[1] = val[1].setScale(val[0].scale, ROUND_UNNECESSARY); 4060 } 4061 } 4062 4063 private static class UnsafeHolder { 4064 private static final jdk.internal.misc.Unsafe unsafe; 4065 private static final long intCompactOffset; 4066 private static final long intValOffset; 4067 static { 4068 try { 4069 unsafe = jdk.internal.misc.Unsafe.getUnsafe(); 4070 intCompactOffset = unsafe.objectFieldOffset 4071 (BigDecimal.class.getDeclaredField("intCompact")); 4072 intValOffset = unsafe.objectFieldOffset 4073 (BigDecimal.class.getDeclaredField("intVal")); 4074 } catch (Exception ex) { 4075 throw new ExceptionInInitializerError(ex); 4076 } 4077 } 4078 static void setIntCompact(BigDecimal bd, long val) { 4079 unsafe.putLong(bd, intCompactOffset, val); 4080 } 4081 4082 static void setIntValVolatile(BigDecimal bd, BigInteger val) { 4083 unsafe.putObjectVolatile(bd, intValOffset, val); 4084 } 4085 } 4086 4087 /** 4088 * Reconstitute the {@code BigDecimal} instance from a stream (that is, 4089 * deserialize it). 4090 * 4091 * @param s the stream being read. 4092 */ 4093 private void readObject(java.io.ObjectInputStream s) 4094 throws java.io.IOException, ClassNotFoundException { 4095 // Read in all fields 4096 s.defaultReadObject(); 4097 // validate possibly bad fields 4098 if (intVal == null) { 4099 String message = "BigDecimal: null intVal in stream"; 4100 throw new java.io.StreamCorruptedException(message); 4101 // [all values of scale are now allowed] 4102 } 4103 UnsafeHolder.setIntCompact(this, compactValFor(intVal)); 4104 } 4105 4106 /** 4107 * Serialize this {@code BigDecimal} to the stream in question 4108 * 4109 * @param s the stream to serialize to. 4110 */ 4111 private void writeObject(java.io.ObjectOutputStream s) 4112 throws java.io.IOException { 4113 // Must inflate to maintain compatible serial form. 4114 if (this.intVal == null) 4115 UnsafeHolder.setIntValVolatile(this, BigInteger.valueOf(this.intCompact)); 4116 // Could reset intVal back to null if it has to be set. 4117 s.defaultWriteObject(); 4118 } 4119 4120 /** 4121 * Returns the length of the absolute value of a {@code long}, in decimal 4122 * digits. 4123 * 4124 * @param x the {@code long} 4125 * @return the length of the unscaled value, in deciaml digits. 4126 */ 4127 static int longDigitLength(long x) { 4128 /* 4129 * As described in "Bit Twiddling Hacks" by Sean Anderson, 4130 * (http://graphics.stanford.edu/~seander/bithacks.html) 4131 * integer log 10 of x is within 1 of (1233/4096)* (1 + 4132 * integer log 2 of x). The fraction 1233/4096 approximates 4133 * log10(2). So we first do a version of log2 (a variant of 4134 * Long class with pre-checks and opposite directionality) and 4135 * then scale and check against powers table. This is a little 4136 * simpler in present context than the version in Hacker's 4137 * Delight sec 11-4. Adding one to bit length allows comparing 4138 * downward from the LONG_TEN_POWERS_TABLE that we need 4139 * anyway. 4140 */ 4141 assert x != BigDecimal.INFLATED; 4142 if (x < 0) 4143 x = -x; 4144 if (x < 10) // must screen for 0, might as well 10 4145 return 1; 4146 int r = ((64 - Long.numberOfLeadingZeros(x) + 1) * 1233) >>> 12; 4147 long[] tab = LONG_TEN_POWERS_TABLE; 4148 // if r >= length, must have max possible digits for long 4149 return (r >= tab.length || x < tab[r]) ? r : r + 1; 4150 } 4151 4152 /** 4153 * Returns the length of the absolute value of a BigInteger, in 4154 * decimal digits. 4155 * 4156 * @param b the BigInteger 4157 * @return the length of the unscaled value, in decimal digits 4158 */ 4159 private static int bigDigitLength(BigInteger b) { 4160 /* 4161 * Same idea as the long version, but we need a better 4162 * approximation of log10(2). Using 646456993/2^31 4163 * is accurate up to max possible reported bitLength. 4164 */ 4165 if (b.signum == 0) 4166 return 1; 4167 int r = (int)((((long)b.bitLength() + 1) * 646456993) >>> 31); 4168 return b.compareMagnitude(bigTenToThe(r)) < 0? r : r+1; 4169 } 4170 4171 /** 4172 * Check a scale for Underflow or Overflow. If this BigDecimal is 4173 * nonzero, throw an exception if the scale is outof range. If this 4174 * is zero, saturate the scale to the extreme value of the right 4175 * sign if the scale is out of range. 4176 * 4177 * @param val The new scale. 4178 * @throws ArithmeticException (overflow or underflow) if the new 4179 * scale is out of range. 4180 * @return validated scale as an int. 4181 */ 4182 private int checkScale(long val) { 4183 int asInt = (int)val; 4184 if (asInt != val) { 4185 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 4186 BigInteger b; 4187 if (intCompact != 0 && 4188 ((b = intVal) == null || b.signum() != 0)) 4189 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 4190 } 4191 return asInt; 4192 } 4193 4194 /** 4195 * Returns the compact value for given {@code BigInteger}, or 4196 * INFLATED if too big. Relies on internal representation of 4197 * {@code BigInteger}. 4198 */ 4199 private static long compactValFor(BigInteger b) { 4200 int[] m = b.mag; 4201 int len = m.length; 4202 if (len == 0) 4203 return 0; 4204 int d = m[0]; 4205 if (len > 2 || (len == 2 && d < 0)) 4206 return INFLATED; 4207 4208 long u = (len == 2)? 4209 (((long) m[1] & LONG_MASK) + (((long)d) << 32)) : 4210 (((long)d) & LONG_MASK); 4211 return (b.signum < 0)? -u : u; 4212 } 4213 4214 private static int longCompareMagnitude(long x, long y) { 4215 if (x < 0) 4216 x = -x; 4217 if (y < 0) 4218 y = -y; 4219 return (x < y) ? -1 : ((x == y) ? 0 : 1); 4220 } 4221 4222 private static int saturateLong(long s) { 4223 int i = (int)s; 4224 return (s == i) ? i : (s < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE); 4225 } 4226 4227 /* 4228 * Internal printing routine 4229 */ 4230 private static void print(String name, BigDecimal bd) { 4231 System.err.format("%s:\tintCompact %d\tintVal %d\tscale %d\tprecision %d%n", 4232 name, 4233 bd.intCompact, 4234 bd.intVal, 4235 bd.scale, 4236 bd.precision); 4237 } 4238 4239 /** 4240 * Check internal invariants of this BigDecimal. These invariants 4241 * include: 4242 * 4243 * <ul> 4244 * 4245 * <li>The object must be initialized; either intCompact must not be 4246 * INFLATED or intVal is non-null. Both of these conditions may 4247 * be true. 4248 * 4249 * <li>If both intCompact and intVal and set, their values must be 4250 * consistent. 4251 * 4252 * <li>If precision is nonzero, it must have the right value. 4253 * </ul> 4254 * 4255 * Note: Since this is an audit method, we are not supposed to change the 4256 * state of this BigDecimal object. 4257 */ 4258 private BigDecimal audit() { 4259 if (intCompact == INFLATED) { 4260 if (intVal == null) { 4261 print("audit", this); 4262 throw new AssertionError("null intVal"); 4263 } 4264 // Check precision 4265 if (precision > 0 && precision != bigDigitLength(intVal)) { 4266 print("audit", this); 4267 throw new AssertionError("precision mismatch"); 4268 } 4269 } else { 4270 if (intVal != null) { 4271 long val = intVal.longValue(); 4272 if (val != intCompact) { 4273 print("audit", this); 4274 throw new AssertionError("Inconsistent state, intCompact=" + 4275 intCompact + "\t intVal=" + val); 4276 } 4277 } 4278 // Check precision 4279 if (precision > 0 && precision != longDigitLength(intCompact)) { 4280 print("audit", this); 4281 throw new AssertionError("precision mismatch"); 4282 } 4283 } 4284 return this; 4285 } 4286 4287 /* the same as checkScale where value!=0 */ 4288 private static int checkScaleNonZero(long val) { 4289 int asInt = (int)val; 4290 if (asInt != val) { 4291 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 4292 } 4293 return asInt; 4294 } 4295 4296 private static int checkScale(long intCompact, long val) { 4297 int asInt = (int)val; 4298 if (asInt != val) { 4299 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 4300 if (intCompact != 0) 4301 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 4302 } 4303 return asInt; 4304 } 4305 4306 private static int checkScale(BigInteger intVal, long val) { 4307 int asInt = (int)val; 4308 if (asInt != val) { 4309 asInt = val>Integer.MAX_VALUE ? Integer.MAX_VALUE : Integer.MIN_VALUE; 4310 if (intVal.signum() != 0) 4311 throw new ArithmeticException(asInt>0 ? "Underflow":"Overflow"); 4312 } 4313 return asInt; 4314 } 4315 4316 /** 4317 * Returns a {@code BigDecimal} rounded according to the MathContext 4318 * settings; 4319 * If rounding is needed a new {@code BigDecimal} is created and returned. 4320 * 4321 * @param val the value to be rounded 4322 * @param mc the context to use. 4323 * @return a {@code BigDecimal} rounded according to the MathContext 4324 * settings. May return {@code value}, if no rounding needed. 4325 * @throws ArithmeticException if the rounding mode is 4326 * {@code RoundingMode.UNNECESSARY} and the 4327 * result is inexact. 4328 */ 4329 private static BigDecimal doRound(BigDecimal val, MathContext mc) { 4330 int mcp = mc.precision; 4331 boolean wasDivided = false; 4332 if (mcp > 0) { 4333 BigInteger intVal = val.intVal; 4334 long compactVal = val.intCompact; 4335 int scale = val.scale; 4336 int prec = val.precision(); 4337 int mode = mc.roundingMode.oldMode; 4338 int drop; 4339 if (compactVal == INFLATED) { 4340 drop = prec - mcp; 4341 while (drop > 0) { 4342 scale = checkScaleNonZero((long) scale - drop); 4343 intVal = divideAndRoundByTenPow(intVal, drop, mode); 4344 wasDivided = true; 4345 compactVal = compactValFor(intVal); 4346 if (compactVal != INFLATED) { 4347 prec = longDigitLength(compactVal); 4348 break; 4349 } 4350 prec = bigDigitLength(intVal); 4351 drop = prec - mcp; 4352 } 4353 } 4354 if (compactVal != INFLATED) { 4355 drop = prec - mcp; // drop can't be more than 18 4356 while (drop > 0) { 4357 scale = checkScaleNonZero((long) scale - drop); 4358 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4359 wasDivided = true; 4360 prec = longDigitLength(compactVal); 4361 drop = prec - mcp; 4362 intVal = null; 4363 } 4364 } 4365 return wasDivided ? new BigDecimal(intVal,compactVal,scale,prec) : val; 4366 } 4367 return val; 4368 } 4369 4370 /* 4371 * Returns a {@code BigDecimal} created from {@code long} value with 4372 * given scale rounded according to the MathContext settings 4373 */ 4374 private static BigDecimal doRound(long compactVal, int scale, MathContext mc) { 4375 int mcp = mc.precision; 4376 if (mcp > 0 && mcp < 19) { 4377 int prec = longDigitLength(compactVal); 4378 int drop = prec - mcp; // drop can't be more than 18 4379 while (drop > 0) { 4380 scale = checkScaleNonZero((long) scale - drop); 4381 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4382 prec = longDigitLength(compactVal); 4383 drop = prec - mcp; 4384 } 4385 return valueOf(compactVal, scale, prec); 4386 } 4387 return valueOf(compactVal, scale); 4388 } 4389 4390 /* 4391 * Returns a {@code BigDecimal} created from {@code BigInteger} value with 4392 * given scale rounded according to the MathContext settings 4393 */ 4394 private static BigDecimal doRound(BigInteger intVal, int scale, MathContext mc) { 4395 int mcp = mc.precision; 4396 int prec = 0; 4397 if (mcp > 0) { 4398 long compactVal = compactValFor(intVal); 4399 int mode = mc.roundingMode.oldMode; 4400 int drop; 4401 if (compactVal == INFLATED) { 4402 prec = bigDigitLength(intVal); 4403 drop = prec - mcp; 4404 while (drop > 0) { 4405 scale = checkScaleNonZero((long) scale - drop); 4406 intVal = divideAndRoundByTenPow(intVal, drop, mode); 4407 compactVal = compactValFor(intVal); 4408 if (compactVal != INFLATED) { 4409 break; 4410 } 4411 prec = bigDigitLength(intVal); 4412 drop = prec - mcp; 4413 } 4414 } 4415 if (compactVal != INFLATED) { 4416 prec = longDigitLength(compactVal); 4417 drop = prec - mcp; // drop can't be more than 18 4418 while (drop > 0) { 4419 scale = checkScaleNonZero((long) scale - drop); 4420 compactVal = divideAndRound(compactVal, LONG_TEN_POWERS_TABLE[drop], mc.roundingMode.oldMode); 4421 prec = longDigitLength(compactVal); 4422 drop = prec - mcp; 4423 } 4424 return valueOf(compactVal,scale,prec); 4425 } 4426 } 4427 return new BigDecimal(intVal,INFLATED,scale,prec); 4428 } 4429 4430 /* 4431 * Divides {@code BigInteger} value by ten power. 4432 */ 4433 private static BigInteger divideAndRoundByTenPow(BigInteger intVal, int tenPow, int roundingMode) { 4434 if (tenPow < LONG_TEN_POWERS_TABLE.length) 4435 intVal = divideAndRound(intVal, LONG_TEN_POWERS_TABLE[tenPow], roundingMode); 4436 else 4437 intVal = divideAndRound(intVal, bigTenToThe(tenPow), roundingMode); 4438 return intVal; 4439 } 4440 4441 /** 4442 * Internally used for division operation for division {@code long} by 4443 * {@code long}. 4444 * The returned {@code BigDecimal} object is the quotient whose scale is set 4445 * to the passed in scale. If the remainder is not zero, it will be rounded 4446 * based on the passed in roundingMode. Also, if the remainder is zero and 4447 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4448 * trailing zeros of the result is stripped to match the preferredScale. 4449 */ 4450 private static BigDecimal divideAndRound(long ldividend, long ldivisor, int scale, int roundingMode, 4451 int preferredScale) { 4452 4453 int qsign; // quotient sign 4454 long q = ldividend / ldivisor; // store quotient in long 4455 if (roundingMode == ROUND_DOWN && scale == preferredScale) 4456 return valueOf(q, scale); 4457 long r = ldividend % ldivisor; // store remainder in long 4458 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; 4459 if (r != 0) { 4460 boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r); 4461 return valueOf((increment ? q + qsign : q), scale); 4462 } else { 4463 if (preferredScale != scale) 4464 return createAndStripZerosToMatchScale(q, scale, preferredScale); 4465 else 4466 return valueOf(q, scale); 4467 } 4468 } 4469 4470 /** 4471 * Divides {@code long} by {@code long} and do rounding based on the 4472 * passed in roundingMode. 4473 */ 4474 private static long divideAndRound(long ldividend, long ldivisor, int roundingMode) { 4475 int qsign; // quotient sign 4476 long q = ldividend / ldivisor; // store quotient in long 4477 if (roundingMode == ROUND_DOWN) 4478 return q; 4479 long r = ldividend % ldivisor; // store remainder in long 4480 qsign = ((ldividend < 0) == (ldivisor < 0)) ? 1 : -1; 4481 if (r != 0) { 4482 boolean increment = needIncrement(ldivisor, roundingMode, qsign, q, r); 4483 return increment ? q + qsign : q; 4484 } else { 4485 return q; 4486 } 4487 } 4488 4489 /** 4490 * Shared logic of need increment computation. 4491 */ 4492 private static boolean commonNeedIncrement(int roundingMode, int qsign, 4493 int cmpFracHalf, boolean oddQuot) { 4494 switch(roundingMode) { 4495 case ROUND_UNNECESSARY: 4496 throw new ArithmeticException("Rounding necessary"); 4497 4498 case ROUND_UP: // Away from zero 4499 return true; 4500 4501 case ROUND_DOWN: // Towards zero 4502 return false; 4503 4504 case ROUND_CEILING: // Towards +infinity 4505 return qsign > 0; 4506 4507 case ROUND_FLOOR: // Towards -infinity 4508 return qsign < 0; 4509 4510 default: // Some kind of half-way rounding 4511 assert roundingMode >= ROUND_HALF_UP && 4512 roundingMode <= ROUND_HALF_EVEN: "Unexpected rounding mode" + RoundingMode.valueOf(roundingMode); 4513 4514 if (cmpFracHalf < 0 ) // We're closer to higher digit 4515 return false; 4516 else if (cmpFracHalf > 0 ) // We're closer to lower digit 4517 return true; 4518 else { // half-way 4519 assert cmpFracHalf == 0; 4520 4521 switch(roundingMode) { 4522 case ROUND_HALF_DOWN: 4523 return false; 4524 4525 case ROUND_HALF_UP: 4526 return true; 4527 4528 case ROUND_HALF_EVEN: 4529 return oddQuot; 4530 4531 default: 4532 throw new AssertionError("Unexpected rounding mode" + roundingMode); 4533 } 4534 } 4535 } 4536 } 4537 4538 /** 4539 * Tests if quotient has to be incremented according the roundingMode 4540 */ 4541 private static boolean needIncrement(long ldivisor, int roundingMode, 4542 int qsign, long q, long r) { 4543 assert r != 0L; 4544 4545 int cmpFracHalf; 4546 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { 4547 cmpFracHalf = 1; // 2 * r can't fit into long 4548 } else { 4549 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); 4550 } 4551 4552 return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, (q & 1L) != 0L); 4553 } 4554 4555 /** 4556 * Divides {@code BigInteger} value by {@code long} value and 4557 * do rounding based on the passed in roundingMode. 4558 */ 4559 private static BigInteger divideAndRound(BigInteger bdividend, long ldivisor, int roundingMode) { 4560 // Descend into mutables for faster remainder checks 4561 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4562 // store quotient 4563 MutableBigInteger mq = new MutableBigInteger(); 4564 // store quotient & remainder in long 4565 long r = mdividend.divide(ldivisor, mq); 4566 // record remainder is zero or not 4567 boolean isRemainderZero = (r == 0); 4568 // quotient sign 4569 int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; 4570 if (!isRemainderZero) { 4571 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) { 4572 mq.add(MutableBigInteger.ONE); 4573 } 4574 } 4575 return mq.toBigInteger(qsign); 4576 } 4577 4578 /** 4579 * Internally used for division operation for division {@code BigInteger} 4580 * by {@code long}. 4581 * The returned {@code BigDecimal} object is the quotient whose scale is set 4582 * to the passed in scale. If the remainder is not zero, it will be rounded 4583 * based on the passed in roundingMode. Also, if the remainder is zero and 4584 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4585 * trailing zeros of the result is stripped to match the preferredScale. 4586 */ 4587 private static BigDecimal divideAndRound(BigInteger bdividend, 4588 long ldivisor, int scale, int roundingMode, int preferredScale) { 4589 // Descend into mutables for faster remainder checks 4590 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4591 // store quotient 4592 MutableBigInteger mq = new MutableBigInteger(); 4593 // store quotient & remainder in long 4594 long r = mdividend.divide(ldivisor, mq); 4595 // record remainder is zero or not 4596 boolean isRemainderZero = (r == 0); 4597 // quotient sign 4598 int qsign = (ldivisor < 0) ? -bdividend.signum : bdividend.signum; 4599 if (!isRemainderZero) { 4600 if(needIncrement(ldivisor, roundingMode, qsign, mq, r)) { 4601 mq.add(MutableBigInteger.ONE); 4602 } 4603 return mq.toBigDecimal(qsign, scale); 4604 } else { 4605 if (preferredScale != scale) { 4606 long compactVal = mq.toCompactValue(qsign); 4607 if(compactVal!=INFLATED) { 4608 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); 4609 } 4610 BigInteger intVal = mq.toBigInteger(qsign); 4611 return createAndStripZerosToMatchScale(intVal,scale, preferredScale); 4612 } else { 4613 return mq.toBigDecimal(qsign, scale); 4614 } 4615 } 4616 } 4617 4618 /** 4619 * Tests if quotient has to be incremented according the roundingMode 4620 */ 4621 private static boolean needIncrement(long ldivisor, int roundingMode, 4622 int qsign, MutableBigInteger mq, long r) { 4623 assert r != 0L; 4624 4625 int cmpFracHalf; 4626 if (r <= HALF_LONG_MIN_VALUE || r > HALF_LONG_MAX_VALUE) { 4627 cmpFracHalf = 1; // 2 * r can't fit into long 4628 } else { 4629 cmpFracHalf = longCompareMagnitude(2 * r, ldivisor); 4630 } 4631 4632 return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd()); 4633 } 4634 4635 /** 4636 * Divides {@code BigInteger} value by {@code BigInteger} value and 4637 * do rounding based on the passed in roundingMode. 4638 */ 4639 private static BigInteger divideAndRound(BigInteger bdividend, BigInteger bdivisor, int roundingMode) { 4640 boolean isRemainderZero; // record remainder is zero or not 4641 int qsign; // quotient sign 4642 // Descend into mutables for faster remainder checks 4643 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4644 MutableBigInteger mq = new MutableBigInteger(); 4645 MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); 4646 MutableBigInteger mr = mdividend.divide(mdivisor, mq); 4647 isRemainderZero = mr.isZero(); 4648 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; 4649 if (!isRemainderZero) { 4650 if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { 4651 mq.add(MutableBigInteger.ONE); 4652 } 4653 } 4654 return mq.toBigInteger(qsign); 4655 } 4656 4657 /** 4658 * Internally used for division operation for division {@code BigInteger} 4659 * by {@code BigInteger}. 4660 * The returned {@code BigDecimal} object is the quotient whose scale is set 4661 * to the passed in scale. If the remainder is not zero, it will be rounded 4662 * based on the passed in roundingMode. Also, if the remainder is zero and 4663 * the last parameter, i.e. preferredScale is NOT equal to scale, the 4664 * trailing zeros of the result is stripped to match the preferredScale. 4665 */ 4666 private static BigDecimal divideAndRound(BigInteger bdividend, BigInteger bdivisor, int scale, int roundingMode, 4667 int preferredScale) { 4668 boolean isRemainderZero; // record remainder is zero or not 4669 int qsign; // quotient sign 4670 // Descend into mutables for faster remainder checks 4671 MutableBigInteger mdividend = new MutableBigInteger(bdividend.mag); 4672 MutableBigInteger mq = new MutableBigInteger(); 4673 MutableBigInteger mdivisor = new MutableBigInteger(bdivisor.mag); 4674 MutableBigInteger mr = mdividend.divide(mdivisor, mq); 4675 isRemainderZero = mr.isZero(); 4676 qsign = (bdividend.signum != bdivisor.signum) ? -1 : 1; 4677 if (!isRemainderZero) { 4678 if (needIncrement(mdivisor, roundingMode, qsign, mq, mr)) { 4679 mq.add(MutableBigInteger.ONE); 4680 } 4681 return mq.toBigDecimal(qsign, scale); 4682 } else { 4683 if (preferredScale != scale) { 4684 long compactVal = mq.toCompactValue(qsign); 4685 if (compactVal != INFLATED) { 4686 return createAndStripZerosToMatchScale(compactVal, scale, preferredScale); 4687 } 4688 BigInteger intVal = mq.toBigInteger(qsign); 4689 return createAndStripZerosToMatchScale(intVal, scale, preferredScale); 4690 } else { 4691 return mq.toBigDecimal(qsign, scale); 4692 } 4693 } 4694 } 4695 4696 /** 4697 * Tests if quotient has to be incremented according the roundingMode 4698 */ 4699 private static boolean needIncrement(MutableBigInteger mdivisor, int roundingMode, 4700 int qsign, MutableBigInteger mq, MutableBigInteger mr) { 4701 assert !mr.isZero(); 4702 int cmpFracHalf = mr.compareHalf(mdivisor); 4703 return commonNeedIncrement(roundingMode, qsign, cmpFracHalf, mq.isOdd()); 4704 } 4705 4706 /** 4707 * Remove insignificant trailing zeros from this 4708 * {@code BigInteger} value until the preferred scale is reached or no 4709 * more zeros can be removed. If the preferred scale is less than 4710 * Integer.MIN_VALUE, all the trailing zeros will be removed. 4711 * 4712 * @return new {@code BigDecimal} with a scale possibly reduced 4713 * to be closed to the preferred scale. 4714 */ 4715 private static BigDecimal createAndStripZerosToMatchScale(BigInteger intVal, int scale, long preferredScale) { 4716 BigInteger qr[]; // quotient-remainder pair 4717 while (intVal.compareMagnitude(BigInteger.TEN) >= 0 4718 && scale > preferredScale) { 4719 if (intVal.testBit(0)) 4720 break; // odd number cannot end in 0 4721 qr = intVal.divideAndRemainder(BigInteger.TEN); 4722 if (qr[1].signum() != 0) 4723 break; // non-0 remainder 4724 intVal = qr[0]; 4725 scale = checkScale(intVal,(long) scale - 1); // could Overflow 4726 } 4727 return valueOf(intVal, scale, 0); 4728 } 4729 4730 /** 4731 * Remove insignificant trailing zeros from this 4732 * {@code long} value until the preferred scale is reached or no 4733 * more zeros can be removed. If the preferred scale is less than 4734 * Integer.MIN_VALUE, all the trailing zeros will be removed. 4735 * 4736 * @return new {@code BigDecimal} with a scale possibly reduced 4737 * to be closed to the preferred scale. 4738 */ 4739 private static BigDecimal createAndStripZerosToMatchScale(long compactVal, int scale, long preferredScale) { 4740 while (Math.abs(compactVal) >= 10L && scale > preferredScale) { 4741 if ((compactVal & 1L) != 0L) 4742 break; // odd number cannot end in 0 4743 long r = compactVal % 10L; 4744 if (r != 0L) 4745 break; // non-0 remainder 4746 compactVal /= 10; 4747 scale = checkScale(compactVal, (long) scale - 1); // could Overflow 4748 } 4749 return valueOf(compactVal, scale); 4750 } 4751 4752 private static BigDecimal stripZerosToMatchScale(BigInteger intVal, long intCompact, int scale, int preferredScale) { 4753 if(intCompact!=INFLATED) { 4754 return createAndStripZerosToMatchScale(intCompact, scale, preferredScale); 4755 } else { 4756 return createAndStripZerosToMatchScale(intVal==null ? INFLATED_BIGINT : intVal, 4757 scale, preferredScale); 4758 } 4759 } 4760 4761 /* 4762 * returns INFLATED if oveflow 4763 */ 4764 private static long add(long xs, long ys){ 4765 long sum = xs + ys; 4766 // See "Hacker's Delight" section 2-12 for explanation of 4767 // the overflow test. 4768 if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) { // not overflowed 4769 return sum; 4770 } 4771 return INFLATED; 4772 } 4773 4774 private static BigDecimal add(long xs, long ys, int scale){ 4775 long sum = add(xs, ys); 4776 if (sum!=INFLATED) 4777 return BigDecimal.valueOf(sum, scale); 4778 return new BigDecimal(BigInteger.valueOf(xs).add(ys), scale); 4779 } 4780 4781 private static BigDecimal add(final long xs, int scale1, final long ys, int scale2) { 4782 long sdiff = (long) scale1 - scale2; 4783 if (sdiff == 0) { 4784 return add(xs, ys, scale1); 4785 } else if (sdiff < 0) { 4786 int raise = checkScale(xs,-sdiff); 4787 long scaledX = longMultiplyPowerTen(xs, raise); 4788 if (scaledX != INFLATED) { 4789 return add(scaledX, ys, scale2); 4790 } else { 4791 BigInteger bigsum = bigMultiplyPowerTen(xs,raise).add(ys); 4792 return ((xs^ys)>=0) ? // same sign test 4793 new BigDecimal(bigsum, INFLATED, scale2, 0) 4794 : valueOf(bigsum, scale2, 0); 4795 } 4796 } else { 4797 int raise = checkScale(ys,sdiff); 4798 long scaledY = longMultiplyPowerTen(ys, raise); 4799 if (scaledY != INFLATED) { 4800 return add(xs, scaledY, scale1); 4801 } else { 4802 BigInteger bigsum = bigMultiplyPowerTen(ys,raise).add(xs); 4803 return ((xs^ys)>=0) ? 4804 new BigDecimal(bigsum, INFLATED, scale1, 0) 4805 : valueOf(bigsum, scale1, 0); 4806 } 4807 } 4808 } 4809 4810 private static BigDecimal add(final long xs, int scale1, BigInteger snd, int scale2) { 4811 int rscale = scale1; 4812 long sdiff = (long)rscale - scale2; 4813 boolean sameSigns = (Long.signum(xs) == snd.signum); 4814 BigInteger sum; 4815 if (sdiff < 0) { 4816 int raise = checkScale(xs,-sdiff); 4817 rscale = scale2; 4818 long scaledX = longMultiplyPowerTen(xs, raise); 4819 if (scaledX == INFLATED) { 4820 sum = snd.add(bigMultiplyPowerTen(xs,raise)); 4821 } else { 4822 sum = snd.add(scaledX); 4823 } 4824 } else { //if (sdiff > 0) { 4825 int raise = checkScale(snd,sdiff); 4826 snd = bigMultiplyPowerTen(snd,raise); 4827 sum = snd.add(xs); 4828 } 4829 return (sameSigns) ? 4830 new BigDecimal(sum, INFLATED, rscale, 0) : 4831 valueOf(sum, rscale, 0); 4832 } 4833 4834 private static BigDecimal add(BigInteger fst, int scale1, BigInteger snd, int scale2) { 4835 int rscale = scale1; 4836 long sdiff = (long)rscale - scale2; 4837 if (sdiff != 0) { 4838 if (sdiff < 0) { 4839 int raise = checkScale(fst,-sdiff); 4840 rscale = scale2; 4841 fst = bigMultiplyPowerTen(fst,raise); 4842 } else { 4843 int raise = checkScale(snd,sdiff); 4844 snd = bigMultiplyPowerTen(snd,raise); 4845 } 4846 } 4847 BigInteger sum = fst.add(snd); 4848 return (fst.signum == snd.signum) ? 4849 new BigDecimal(sum, INFLATED, rscale, 0) : 4850 valueOf(sum, rscale, 0); 4851 } 4852 4853 private static BigInteger bigMultiplyPowerTen(long value, int n) { 4854 if (n <= 0) 4855 return BigInteger.valueOf(value); 4856 return bigTenToThe(n).multiply(value); 4857 } 4858 4859 private static BigInteger bigMultiplyPowerTen(BigInteger value, int n) { 4860 if (n <= 0) 4861 return value; 4862 if(n<LONG_TEN_POWERS_TABLE.length) { 4863 return value.multiply(LONG_TEN_POWERS_TABLE[n]); 4864 } 4865 return value.multiply(bigTenToThe(n)); 4866 } 4867 4868 /** 4869 * Returns a {@code BigDecimal} whose value is {@code (xs / 4870 * ys)}, with rounding according to the context settings. 4871 * 4872 * Fast path - used only when (xscale <= yscale && yscale < 18 4873 * && mc.presision<18) { 4874 */ 4875 private static BigDecimal divideSmallFastPath(final long xs, int xscale, 4876 final long ys, int yscale, 4877 long preferredScale, MathContext mc) { 4878 int mcp = mc.precision; 4879 int roundingMode = mc.roundingMode.oldMode; 4880 4881 assert (xscale <= yscale) && (yscale < 18) && (mcp < 18); 4882 int xraise = yscale - xscale; // xraise >=0 4883 long scaledX = (xraise==0) ? xs : 4884 longMultiplyPowerTen(xs, xraise); // can't overflow here! 4885 BigDecimal quotient; 4886 4887 int cmp = longCompareMagnitude(scaledX, ys); 4888 if(cmp > 0) { // satisfy constraint (b) 4889 yscale -= 1; // [that is, divisor *= 10] 4890 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4891 if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) { 4892 // assert newScale >= xscale 4893 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4894 long scaledXs; 4895 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) { 4896 quotient = null; 4897 if((mcp-1) >=0 && (mcp-1)<LONG_TEN_POWERS_TABLE.length) { 4898 quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp-1], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4899 } 4900 if(quotient==null) { 4901 BigInteger rb = bigMultiplyPowerTen(scaledX,mcp-1); 4902 quotient = divideAndRound(rb, ys, 4903 scl, roundingMode, checkScaleNonZero(preferredScale)); 4904 } 4905 } else { 4906 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4907 } 4908 } else { 4909 int newScale = checkScaleNonZero((long) xscale - mcp); 4910 // assert newScale >= yscale 4911 if (newScale == yscale) { // easy case 4912 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 4913 } else { 4914 int raise = checkScaleNonZero((long) newScale - yscale); 4915 long scaledYs; 4916 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 4917 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4918 quotient = divideAndRound(BigInteger.valueOf(xs), 4919 rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4920 } else { 4921 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 4922 } 4923 } 4924 } 4925 } else { 4926 // abs(scaledX) <= abs(ys) 4927 // result is "scaledX * 10^msp / ys" 4928 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4929 if(cmp==0) { 4930 // abs(scaleX)== abs(ys) => result will be scaled 10^mcp + correct sign 4931 quotient = roundedTenPower(((scaledX < 0) == (ys < 0)) ? 1 : -1, mcp, scl, checkScaleNonZero(preferredScale)); 4932 } else { 4933 // abs(scaledX) < abs(ys) 4934 long scaledXs; 4935 if ((scaledXs = longMultiplyPowerTen(scaledX, mcp)) == INFLATED) { 4936 quotient = null; 4937 if(mcp<LONG_TEN_POWERS_TABLE.length) { 4938 quotient = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[mcp], scaledX, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4939 } 4940 if(quotient==null) { 4941 BigInteger rb = bigMultiplyPowerTen(scaledX,mcp); 4942 quotient = divideAndRound(rb, ys, 4943 scl, roundingMode, checkScaleNonZero(preferredScale)); 4944 } 4945 } else { 4946 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4947 } 4948 } 4949 } 4950 // doRound, here, only affects 1000000000 case. 4951 return doRound(quotient,mc); 4952 } 4953 4954 /** 4955 * Returns a {@code BigDecimal} whose value is {@code (xs / 4956 * ys)}, with rounding according to the context settings. 4957 */ 4958 private static BigDecimal divide(final long xs, int xscale, final long ys, int yscale, long preferredScale, MathContext mc) { 4959 int mcp = mc.precision; 4960 if(xscale <= yscale && yscale < 18 && mcp<18) { 4961 return divideSmallFastPath(xs, xscale, ys, yscale, preferredScale, mc); 4962 } 4963 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 4964 yscale -= 1; // [that is, divisor *= 10] 4965 } 4966 int roundingMode = mc.roundingMode.oldMode; 4967 // In order to find out whether the divide generates the exact result, 4968 // we avoid calling the above divide method. 'quotient' holds the 4969 // return BigDecimal object whose scale will be set to 'scl'. 4970 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 4971 BigDecimal quotient; 4972 if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) { 4973 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 4974 long scaledXs; 4975 if ((scaledXs = longMultiplyPowerTen(xs, raise)) == INFLATED) { 4976 BigInteger rb = bigMultiplyPowerTen(xs,raise); 4977 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4978 } else { 4979 quotient = divideAndRound(scaledXs, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 4980 } 4981 } else { 4982 int newScale = checkScaleNonZero((long) xscale - mcp); 4983 // assert newScale >= yscale 4984 if (newScale == yscale) { // easy case 4985 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 4986 } else { 4987 int raise = checkScaleNonZero((long) newScale - yscale); 4988 long scaledYs; 4989 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 4990 BigInteger rb = bigMultiplyPowerTen(ys,raise); 4991 quotient = divideAndRound(BigInteger.valueOf(xs), 4992 rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 4993 } else { 4994 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 4995 } 4996 } 4997 } 4998 // doRound, here, only affects 1000000000 case. 4999 return doRound(quotient,mc); 5000 } 5001 5002 /** 5003 * Returns a {@code BigDecimal} whose value is {@code (xs / 5004 * ys)}, with rounding according to the context settings. 5005 */ 5006 private static BigDecimal divide(BigInteger xs, int xscale, long ys, int yscale, long preferredScale, MathContext mc) { 5007 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5008 if ((-compareMagnitudeNormalized(ys, yscale, xs, xscale)) > 0) {// satisfy constraint (b) 5009 yscale -= 1; // [that is, divisor *= 10] 5010 } 5011 int mcp = mc.precision; 5012 int roundingMode = mc.roundingMode.oldMode; 5013 5014 // In order to find out whether the divide generates the exact result, 5015 // we avoid calling the above divide method. 'quotient' holds the 5016 // return BigDecimal object whose scale will be set to 'scl'. 5017 BigDecimal quotient; 5018 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 5019 if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) { 5020 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 5021 BigInteger rb = bigMultiplyPowerTen(xs,raise); 5022 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 5023 } else { 5024 int newScale = checkScaleNonZero((long) xscale - mcp); 5025 // assert newScale >= yscale 5026 if (newScale == yscale) { // easy case 5027 quotient = divideAndRound(xs, ys, scl, roundingMode,checkScaleNonZero(preferredScale)); 5028 } else { 5029 int raise = checkScaleNonZero((long) newScale - yscale); 5030 long scaledYs; 5031 if ((scaledYs = longMultiplyPowerTen(ys, raise)) == INFLATED) { 5032 BigInteger rb = bigMultiplyPowerTen(ys,raise); 5033 quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 5034 } else { 5035 quotient = divideAndRound(xs, scaledYs, scl, roundingMode,checkScaleNonZero(preferredScale)); 5036 } 5037 } 5038 } 5039 // doRound, here, only affects 1000000000 case. 5040 return doRound(quotient, mc); 5041 } 5042 5043 /** 5044 * Returns a {@code BigDecimal} whose value is {@code (xs / 5045 * ys)}, with rounding according to the context settings. 5046 */ 5047 private static BigDecimal divide(long xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) { 5048 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5049 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 5050 yscale -= 1; // [that is, divisor *= 10] 5051 } 5052 int mcp = mc.precision; 5053 int roundingMode = mc.roundingMode.oldMode; 5054 5055 // In order to find out whether the divide generates the exact result, 5056 // we avoid calling the above divide method. 'quotient' holds the 5057 // return BigDecimal object whose scale will be set to 'scl'. 5058 BigDecimal quotient; 5059 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 5060 if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) { 5061 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 5062 BigInteger rb = bigMultiplyPowerTen(xs,raise); 5063 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 5064 } else { 5065 int newScale = checkScaleNonZero((long) xscale - mcp); 5066 int raise = checkScaleNonZero((long) newScale - yscale); 5067 BigInteger rb = bigMultiplyPowerTen(ys,raise); 5068 quotient = divideAndRound(BigInteger.valueOf(xs), rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 5069 } 5070 // doRound, here, only affects 1000000000 case. 5071 return doRound(quotient, mc); 5072 } 5073 5074 /** 5075 * Returns a {@code BigDecimal} whose value is {@code (xs / 5076 * ys)}, with rounding according to the context settings. 5077 */ 5078 private static BigDecimal divide(BigInteger xs, int xscale, BigInteger ys, int yscale, long preferredScale, MathContext mc) { 5079 // Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5080 if (compareMagnitudeNormalized(xs, xscale, ys, yscale) > 0) {// satisfy constraint (b) 5081 yscale -= 1; // [that is, divisor *= 10] 5082 } 5083 int mcp = mc.precision; 5084 int roundingMode = mc.roundingMode.oldMode; 5085 5086 // In order to find out whether the divide generates the exact result, 5087 // we avoid calling the above divide method. 'quotient' holds the 5088 // return BigDecimal object whose scale will be set to 'scl'. 5089 BigDecimal quotient; 5090 int scl = checkScaleNonZero(preferredScale + yscale - xscale + mcp); 5091 if (checkScaleNonZero((long) mcp + yscale - xscale) > 0) { 5092 int raise = checkScaleNonZero((long) mcp + yscale - xscale); 5093 BigInteger rb = bigMultiplyPowerTen(xs,raise); 5094 quotient = divideAndRound(rb, ys, scl, roundingMode, checkScaleNonZero(preferredScale)); 5095 } else { 5096 int newScale = checkScaleNonZero((long) xscale - mcp); 5097 int raise = checkScaleNonZero((long) newScale - yscale); 5098 BigInteger rb = bigMultiplyPowerTen(ys,raise); 5099 quotient = divideAndRound(xs, rb, scl, roundingMode,checkScaleNonZero(preferredScale)); 5100 } 5101 // doRound, here, only affects 1000000000 case. 5102 return doRound(quotient, mc); 5103 } 5104 5105 /* 5106 * performs divideAndRound for (dividend0*dividend1, divisor) 5107 * returns null if quotient can't fit into long value; 5108 */ 5109 private static BigDecimal multiplyDivideAndRound(long dividend0, long dividend1, long divisor, int scale, int roundingMode, 5110 int preferredScale) { 5111 int qsign = Long.signum(dividend0)*Long.signum(dividend1)*Long.signum(divisor); 5112 dividend0 = Math.abs(dividend0); 5113 dividend1 = Math.abs(dividend1); 5114 divisor = Math.abs(divisor); 5115 // multiply dividend0 * dividend1 5116 long d0_hi = dividend0 >>> 32; 5117 long d0_lo = dividend0 & LONG_MASK; 5118 long d1_hi = dividend1 >>> 32; 5119 long d1_lo = dividend1 & LONG_MASK; 5120 long product = d0_lo * d1_lo; 5121 long d0 = product & LONG_MASK; 5122 long d1 = product >>> 32; 5123 product = d0_hi * d1_lo + d1; 5124 d1 = product & LONG_MASK; 5125 long d2 = product >>> 32; 5126 product = d0_lo * d1_hi + d1; 5127 d1 = product & LONG_MASK; 5128 d2 += product >>> 32; 5129 long d3 = d2>>>32; 5130 d2 &= LONG_MASK; 5131 product = d0_hi*d1_hi + d2; 5132 d2 = product & LONG_MASK; 5133 d3 = ((product>>>32) + d3) & LONG_MASK; 5134 final long dividendHi = make64(d3,d2); 5135 final long dividendLo = make64(d1,d0); 5136 // divide 5137 return divideAndRound128(dividendHi, dividendLo, divisor, qsign, scale, roundingMode, preferredScale); 5138 } 5139 5140 private static final long DIV_NUM_BASE = (1L<<32); // Number base (32 bits). 5141 5142 /* 5143 * divideAndRound 128-bit value by long divisor. 5144 * returns null if quotient can't fit into long value; 5145 * Specialized version of Knuth's division 5146 */ 5147 private static BigDecimal divideAndRound128(final long dividendHi, final long dividendLo, long divisor, int sign, 5148 int scale, int roundingMode, int preferredScale) { 5149 if (dividendHi >= divisor) { 5150 return null; 5151 } 5152 5153 final int shift = Long.numberOfLeadingZeros(divisor); 5154 divisor <<= shift; 5155 5156 final long v1 = divisor >>> 32; 5157 final long v0 = divisor & LONG_MASK; 5158 5159 long tmp = dividendLo << shift; 5160 long u1 = tmp >>> 32; 5161 long u0 = tmp & LONG_MASK; 5162 5163 tmp = (dividendHi << shift) | (dividendLo >>> 64 - shift); 5164 long u2 = tmp & LONG_MASK; 5165 long q1, r_tmp; 5166 if (v1 == 1) { 5167 q1 = tmp; 5168 r_tmp = 0; 5169 } else if (tmp >= 0) { 5170 q1 = tmp / v1; 5171 r_tmp = tmp - q1 * v1; 5172 } else { 5173 long[] rq = divRemNegativeLong(tmp, v1); 5174 q1 = rq[1]; 5175 r_tmp = rq[0]; 5176 } 5177 5178 while(q1 >= DIV_NUM_BASE || unsignedLongCompare(q1*v0, make64(r_tmp, u1))) { 5179 q1--; 5180 r_tmp += v1; 5181 if (r_tmp >= DIV_NUM_BASE) 5182 break; 5183 } 5184 5185 tmp = mulsub(u2,u1,v1,v0,q1); 5186 u1 = tmp & LONG_MASK; 5187 long q0; 5188 if (v1 == 1) { 5189 q0 = tmp; 5190 r_tmp = 0; 5191 } else if (tmp >= 0) { 5192 q0 = tmp / v1; 5193 r_tmp = tmp - q0 * v1; 5194 } else { 5195 long[] rq = divRemNegativeLong(tmp, v1); 5196 q0 = rq[1]; 5197 r_tmp = rq[0]; 5198 } 5199 5200 while(q0 >= DIV_NUM_BASE || unsignedLongCompare(q0*v0,make64(r_tmp,u0))) { 5201 q0--; 5202 r_tmp += v1; 5203 if (r_tmp >= DIV_NUM_BASE) 5204 break; 5205 } 5206 5207 if((int)q1 < 0) { 5208 // result (which is positive and unsigned here) 5209 // can't fit into long due to sign bit is used for value 5210 MutableBigInteger mq = new MutableBigInteger(new int[]{(int)q1, (int)q0}); 5211 if (roundingMode == ROUND_DOWN && scale == preferredScale) { 5212 return mq.toBigDecimal(sign, scale); 5213 } 5214 long r = mulsub(u1, u0, v1, v0, q0) >>> shift; 5215 if (r != 0) { 5216 if(needIncrement(divisor >>> shift, roundingMode, sign, mq, r)){ 5217 mq.add(MutableBigInteger.ONE); 5218 } 5219 return mq.toBigDecimal(sign, scale); 5220 } else { 5221 if (preferredScale != scale) { 5222 BigInteger intVal = mq.toBigInteger(sign); 5223 return createAndStripZerosToMatchScale(intVal,scale, preferredScale); 5224 } else { 5225 return mq.toBigDecimal(sign, scale); 5226 } 5227 } 5228 } 5229 5230 long q = make64(q1,q0); 5231 q*=sign; 5232 5233 if (roundingMode == ROUND_DOWN && scale == preferredScale) 5234 return valueOf(q, scale); 5235 5236 long r = mulsub(u1, u0, v1, v0, q0) >>> shift; 5237 if (r != 0) { 5238 boolean increment = needIncrement(divisor >>> shift, roundingMode, sign, q, r); 5239 return valueOf((increment ? q + sign : q), scale); 5240 } else { 5241 if (preferredScale != scale) { 5242 return createAndStripZerosToMatchScale(q, scale, preferredScale); 5243 } else { 5244 return valueOf(q, scale); 5245 } 5246 } 5247 } 5248 5249 /* 5250 * calculate divideAndRound for ldividend*10^raise / divisor 5251 * when abs(dividend)==abs(divisor); 5252 */ 5253 private static BigDecimal roundedTenPower(int qsign, int raise, int scale, int preferredScale) { 5254 if (scale > preferredScale) { 5255 int diff = scale - preferredScale; 5256 if(diff < raise) { 5257 return scaledTenPow(raise - diff, qsign, preferredScale); 5258 } else { 5259 return valueOf(qsign,scale-raise); 5260 } 5261 } else { 5262 return scaledTenPow(raise, qsign, scale); 5263 } 5264 } 5265 5266 static BigDecimal scaledTenPow(int n, int sign, int scale) { 5267 if (n < LONG_TEN_POWERS_TABLE.length) 5268 return valueOf(sign*LONG_TEN_POWERS_TABLE[n],scale); 5269 else { 5270 BigInteger unscaledVal = bigTenToThe(n); 5271 if(sign==-1) { 5272 unscaledVal = unscaledVal.negate(); 5273 } 5274 return new BigDecimal(unscaledVal, INFLATED, scale, n+1); 5275 } 5276 } 5277 5278 /** 5279 * Calculate the quotient and remainder of dividing a negative long by 5280 * another long. 5281 * 5282 * @param n the numerator; must be negative 5283 * @param d the denominator; must not be unity 5284 * @return a two-element {@long} array with the remainder and quotient in 5285 * the initial and final elements, respectively 5286 */ 5287 private static long[] divRemNegativeLong(long n, long d) { 5288 assert n < 0 : "Non-negative numerator " + n; 5289 assert d != 1 : "Unity denominator"; 5290 5291 // Approximate the quotient and remainder 5292 long q = (n >>> 1) / (d >>> 1); 5293 long r = n - q * d; 5294 5295 // Correct the approximation 5296 while (r < 0) { 5297 r += d; 5298 q--; 5299 } 5300 while (r >= d) { 5301 r -= d; 5302 q++; 5303 } 5304 5305 // n - q*d == r && 0 <= r < d, hence we're done. 5306 return new long[] {r, q}; 5307 } 5308 5309 private static long make64(long hi, long lo) { 5310 return hi<<32 | lo; 5311 } 5312 5313 private static long mulsub(long u1, long u0, final long v1, final long v0, long q0) { 5314 long tmp = u0 - q0*v0; 5315 return make64(u1 + (tmp>>>32) - q0*v1,tmp & LONG_MASK); 5316 } 5317 5318 private static boolean unsignedLongCompare(long one, long two) { 5319 return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE); 5320 } 5321 5322 private static boolean unsignedLongCompareEq(long one, long two) { 5323 return (one+Long.MIN_VALUE) >= (two+Long.MIN_VALUE); 5324 } 5325 5326 5327 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5328 private static int compareMagnitudeNormalized(long xs, int xscale, long ys, int yscale) { 5329 // assert xs!=0 && ys!=0 5330 int sdiff = xscale - yscale; 5331 if (sdiff != 0) { 5332 if (sdiff < 0) { 5333 xs = longMultiplyPowerTen(xs, -sdiff); 5334 } else { // sdiff > 0 5335 ys = longMultiplyPowerTen(ys, sdiff); 5336 } 5337 } 5338 if (xs != INFLATED) 5339 return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1; 5340 else 5341 return 1; 5342 } 5343 5344 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5345 private static int compareMagnitudeNormalized(long xs, int xscale, BigInteger ys, int yscale) { 5346 // assert "ys can't be represented as long" 5347 if (xs == 0) 5348 return -1; 5349 int sdiff = xscale - yscale; 5350 if (sdiff < 0) { 5351 if (longMultiplyPowerTen(xs, -sdiff) == INFLATED ) { 5352 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys); 5353 } 5354 } 5355 return -1; 5356 } 5357 5358 // Compare Normalize dividend & divisor so that both fall into [0.1, 0.999...] 5359 private static int compareMagnitudeNormalized(BigInteger xs, int xscale, BigInteger ys, int yscale) { 5360 int sdiff = xscale - yscale; 5361 if (sdiff < 0) { 5362 return bigMultiplyPowerTen(xs, -sdiff).compareMagnitude(ys); 5363 } else { // sdiff >= 0 5364 return xs.compareMagnitude(bigMultiplyPowerTen(ys, sdiff)); 5365 } 5366 } 5367 5368 private static long multiply(long x, long y){ 5369 long product = x * y; 5370 long ax = Math.abs(x); 5371 long ay = Math.abs(y); 5372 if (((ax | ay) >>> 31 == 0) || (y == 0) || (product / y == x)){ 5373 return product; 5374 } 5375 return INFLATED; 5376 } 5377 5378 private static BigDecimal multiply(long x, long y, int scale) { 5379 long product = multiply(x, y); 5380 if(product!=INFLATED) { 5381 return valueOf(product,scale); 5382 } 5383 return new BigDecimal(BigInteger.valueOf(x).multiply(y),INFLATED,scale,0); 5384 } 5385 5386 private static BigDecimal multiply(long x, BigInteger y, int scale) { 5387 if(x==0) { 5388 return zeroValueOf(scale); 5389 } 5390 return new BigDecimal(y.multiply(x),INFLATED,scale,0); 5391 } 5392 5393 private static BigDecimal multiply(BigInteger x, BigInteger y, int scale) { 5394 return new BigDecimal(x.multiply(y),INFLATED,scale,0); 5395 } 5396 5397 /** 5398 * Multiplies two long values and rounds according {@code MathContext} 5399 */ 5400 private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) { 5401 long product = multiply(x, y); 5402 if(product!=INFLATED) { 5403 return doRound(product, scale, mc); 5404 } 5405 // attempt to do it in 128 bits 5406 int rsign = 1; 5407 if(x < 0) { 5408 x = -x; 5409 rsign = -1; 5410 } 5411 if(y < 0) { 5412 y = -y; 5413 rsign *= -1; 5414 } 5415 // multiply dividend0 * dividend1 5416 long m0_hi = x >>> 32; 5417 long m0_lo = x & LONG_MASK; 5418 long m1_hi = y >>> 32; 5419 long m1_lo = y & LONG_MASK; 5420 product = m0_lo * m1_lo; 5421 long m0 = product & LONG_MASK; 5422 long m1 = product >>> 32; 5423 product = m0_hi * m1_lo + m1; 5424 m1 = product & LONG_MASK; 5425 long m2 = product >>> 32; 5426 product = m0_lo * m1_hi + m1; 5427 m1 = product & LONG_MASK; 5428 m2 += product >>> 32; 5429 long m3 = m2>>>32; 5430 m2 &= LONG_MASK; 5431 product = m0_hi*m1_hi + m2; 5432 m2 = product & LONG_MASK; 5433 m3 = ((product>>>32) + m3) & LONG_MASK; 5434 final long mHi = make64(m3,m2); 5435 final long mLo = make64(m1,m0); 5436 BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc); 5437 if(res!=null) { 5438 return res; 5439 } 5440 res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0); 5441 return doRound(res,mc); 5442 } 5443 5444 private static BigDecimal multiplyAndRound(long x, BigInteger y, int scale, MathContext mc) { 5445 if(x==0) { 5446 return zeroValueOf(scale); 5447 } 5448 return doRound(y.multiply(x), scale, mc); 5449 } 5450 5451 private static BigDecimal multiplyAndRound(BigInteger x, BigInteger y, int scale, MathContext mc) { 5452 return doRound(x.multiply(y), scale, mc); 5453 } 5454 5455 /** 5456 * rounds 128-bit value according {@code MathContext} 5457 * returns null if result can't be repsented as compact BigDecimal. 5458 */ 5459 private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) { 5460 int mcp = mc.precision; 5461 int drop; 5462 BigDecimal res = null; 5463 if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) { 5464 scale = checkScaleNonZero((long)scale - drop); 5465 res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale); 5466 } 5467 if(res!=null) { 5468 return doRound(res,mc); 5469 } 5470 return null; 5471 } 5472 5473 private static final long[][] LONGLONG_TEN_POWERS_TABLE = { 5474 { 0L, 0x8AC7230489E80000L }, //10^19 5475 { 0x5L, 0x6bc75e2d63100000L }, //10^20 5476 { 0x36L, 0x35c9adc5dea00000L }, //10^21 5477 { 0x21eL, 0x19e0c9bab2400000L }, //10^22 5478 { 0x152dL, 0x02c7e14af6800000L }, //10^23 5479 { 0xd3c2L, 0x1bcecceda1000000L }, //10^24 5480 { 0x84595L, 0x161401484a000000L }, //10^25 5481 { 0x52b7d2L, 0xdcc80cd2e4000000L }, //10^26 5482 { 0x33b2e3cL, 0x9fd0803ce8000000L }, //10^27 5483 { 0x204fce5eL, 0x3e25026110000000L }, //10^28 5484 { 0x1431e0faeL, 0x6d7217caa0000000L }, //10^29 5485 { 0xc9f2c9cd0L, 0x4674edea40000000L }, //10^30 5486 { 0x7e37be2022L, 0xc0914b2680000000L }, //10^31 5487 { 0x4ee2d6d415bL, 0x85acef8100000000L }, //10^32 5488 { 0x314dc6448d93L, 0x38c15b0a00000000L }, //10^33 5489 { 0x1ed09bead87c0L, 0x378d8e6400000000L }, //10^34 5490 { 0x13426172c74d82L, 0x2b878fe800000000L }, //10^35 5491 { 0xc097ce7bc90715L, 0xb34b9f1000000000L }, //10^36 5492 { 0x785ee10d5da46d9L, 0x00f436a000000000L }, //10^37 5493 { 0x4b3b4ca85a86c47aL, 0x098a224000000000L }, //10^38 5494 }; 5495 5496 /* 5497 * returns precision of 128-bit value 5498 */ 5499 private static int precision(long hi, long lo){ 5500 if(hi==0) { 5501 if(lo>=0) { 5502 return longDigitLength(lo); 5503 } 5504 return (unsignedLongCompareEq(lo, LONGLONG_TEN_POWERS_TABLE[0][1])) ? 20 : 19; 5505 // 0x8AC7230489E80000L = unsigned 2^19 5506 } 5507 int r = ((128 - Long.numberOfLeadingZeros(hi) + 1) * 1233) >>> 12; 5508 int idx = r-19; 5509 return (idx >= LONGLONG_TEN_POWERS_TABLE.length || longLongCompareMagnitude(hi, lo, 5510 LONGLONG_TEN_POWERS_TABLE[idx][0], LONGLONG_TEN_POWERS_TABLE[idx][1])) ? r : r + 1; 5511 } 5512 5513 /* 5514 * returns true if 128 bit number <hi0,lo0> is less than <hi1,lo1> 5515 * hi0 & hi1 should be non-negative 5516 */ 5517 private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) { 5518 if(hi0!=hi1) { 5519 return hi0<hi1; 5520 } 5521 return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE); 5522 } 5523 5524 private static BigDecimal divide(long dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) { 5525 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5526 int newScale = scale + divisorScale; 5527 int raise = newScale - dividendScale; 5528 if(raise<LONG_TEN_POWERS_TABLE.length) { 5529 long xs = dividend; 5530 if ((xs = longMultiplyPowerTen(xs, raise)) != INFLATED) { 5531 return divideAndRound(xs, divisor, scale, roundingMode, scale); 5532 } 5533 BigDecimal q = multiplyDivideAndRound(LONG_TEN_POWERS_TABLE[raise], dividend, divisor, scale, roundingMode, scale); 5534 if(q!=null) { 5535 return q; 5536 } 5537 } 5538 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5539 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5540 } else { 5541 int newScale = checkScale(divisor,(long)dividendScale - scale); 5542 int raise = newScale - divisorScale; 5543 if(raise<LONG_TEN_POWERS_TABLE.length) { 5544 long ys = divisor; 5545 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) { 5546 return divideAndRound(dividend, ys, scale, roundingMode, scale); 5547 } 5548 } 5549 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5550 return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale); 5551 } 5552 } 5553 5554 private static BigDecimal divide(BigInteger dividend, int dividendScale, long divisor, int divisorScale, int scale, int roundingMode) { 5555 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5556 int newScale = scale + divisorScale; 5557 int raise = newScale - dividendScale; 5558 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5559 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5560 } else { 5561 int newScale = checkScale(divisor,(long)dividendScale - scale); 5562 int raise = newScale - divisorScale; 5563 if(raise<LONG_TEN_POWERS_TABLE.length) { 5564 long ys = divisor; 5565 if ((ys = longMultiplyPowerTen(ys, raise)) != INFLATED) { 5566 return divideAndRound(dividend, ys, scale, roundingMode, scale); 5567 } 5568 } 5569 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5570 return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale); 5571 } 5572 } 5573 5574 private static BigDecimal divide(long dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) { 5575 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5576 int newScale = scale + divisorScale; 5577 int raise = newScale - dividendScale; 5578 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5579 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5580 } else { 5581 int newScale = checkScale(divisor,(long)dividendScale - scale); 5582 int raise = newScale - divisorScale; 5583 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5584 return divideAndRound(BigInteger.valueOf(dividend), scaledDivisor, scale, roundingMode, scale); 5585 } 5586 } 5587 5588 private static BigDecimal divide(BigInteger dividend, int dividendScale, BigInteger divisor, int divisorScale, int scale, int roundingMode) { 5589 if (checkScale(dividend,(long)scale + divisorScale) > dividendScale) { 5590 int newScale = scale + divisorScale; 5591 int raise = newScale - dividendScale; 5592 BigInteger scaledDividend = bigMultiplyPowerTen(dividend, raise); 5593 return divideAndRound(scaledDividend, divisor, scale, roundingMode, scale); 5594 } else { 5595 int newScale = checkScale(divisor,(long)dividendScale - scale); 5596 int raise = newScale - divisorScale; 5597 BigInteger scaledDivisor = bigMultiplyPowerTen(divisor, raise); 5598 return divideAndRound(dividend, scaledDivisor, scale, roundingMode, scale); 5599 } 5600 } 5601 5602 }