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