1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package java.math; 19 20 import java.io.IOException; 21 import java.io.ObjectInputStream; 22 import java.io.ObjectOutputStream; 23 import java.io.Serializable; 24 import java.util.Arrays; 25 import libcore.math.MathUtils; 26 27 /** 28 * An immutable arbitrary-precision signed decimal. 29 * 30 * <p>A value is represented by an arbitrary-precision "unscaled value" and a signed 32-bit "scale", 31 * combined thus: {@code unscaled * 10<sup>-scale</sup>}. See {@link #unscaledValue} and {@link #scale}. 32 * 33 * <p>Most operations allow you to supply a {@link MathContext} to specify a desired rounding mode. 34 */ 35 public class BigDecimal extends Number implements Comparable<BigDecimal>, Serializable { 36 37 /** 38 * Rounding mode where positive values are rounded towards positive infinity 39 * and negative values towards negative infinity. 40 * 41 * @see RoundingMode#UP 42 */ 43 public static final int ROUND_UP = 0; 44 45 /** 46 * Rounding mode where the values are rounded towards zero. 47 * 48 * @see RoundingMode#DOWN 49 */ 50 public static final int ROUND_DOWN = 1; 51 52 /** 53 * Rounding mode to round towards positive infinity. For positive values 54 * this rounding mode behaves as {@link #ROUND_UP}, for negative values as 55 * {@link #ROUND_DOWN}. 56 * 57 * @see RoundingMode#CEILING 58 */ 59 public static final int ROUND_CEILING = 2; 60 61 /** 62 * Rounding mode to round towards negative infinity. For positive values 63 * this rounding mode behaves as {@link #ROUND_DOWN}, for negative values as 64 * {@link #ROUND_UP}. 65 * 66 * @see RoundingMode#FLOOR 67 */ 68 public static final int ROUND_FLOOR = 3; 69 70 /** 71 * Rounding mode where values are rounded towards the nearest neighbor. 72 * Ties are broken by rounding up. 73 * 74 * @see RoundingMode#HALF_UP 75 */ 76 public static final int ROUND_HALF_UP = 4; 77 78 /** 79 * Rounding mode where values are rounded towards the nearest neighbor. 80 * Ties are broken by rounding down. 81 * 82 * @see RoundingMode#HALF_DOWN 83 */ 84 public static final int ROUND_HALF_DOWN = 5; 85 86 /** 87 * Rounding mode where values are rounded towards the nearest neighbor. 88 * Ties are broken by rounding to the even neighbor. 89 * 90 * @see RoundingMode#HALF_EVEN 91 */ 92 public static final int ROUND_HALF_EVEN = 6; 93 94 /** 95 * Rounding mode where the rounding operations throws an {@code 96 * ArithmeticException} for the case that rounding is necessary, i.e. for 97 * the case that the value cannot be represented exactly. 98 * 99 * @see RoundingMode#UNNECESSARY 100 */ 101 public static final int ROUND_UNNECESSARY = 7; 102 103 /** This is the serialVersionUID used by the sun implementation. */ 104 private static final long serialVersionUID = 6108874887143696463L; 105 106 /** The double closest to {@code Log10(2)}. */ 107 private static final double LOG10_2 = 0.3010299956639812; 108 109 /** The <code>String</code> representation is cached. */ 110 private transient String toStringImage = null; 111 112 /** Cache for the hash code. */ 113 private transient int hashCode = 0; 114 115 /** 116 * An array with powers of five that fit in the type <code>long</code> 117 * (<code>5^0,5^1,...,5^27</code>). 118 */ 119 private static final BigInteger[] FIVE_POW; 120 121 /** 122 * An array with powers of ten that fit in the type <code>long</code> 123 * (<code>10^0,10^1,...,10^18</code>). 124 */ 125 private static final BigInteger[] TEN_POW; 126 127 private static final long[] LONG_FIVE_POW = new long[] 128 { 1L, 129 5L, 130 25L, 131 125L, 132 625L, 133 3125L, 134 15625L, 135 78125L, 136 390625L, 137 1953125L, 138 9765625L, 139 48828125L, 140 244140625L, 141 1220703125L, 142 6103515625L, 143 30517578125L, 144 152587890625L, 145 762939453125L, 146 3814697265625L, 147 19073486328125L, 148 95367431640625L, 149 476837158203125L, 150 2384185791015625L, 151 11920928955078125L, 152 59604644775390625L, 153 298023223876953125L, 154 1490116119384765625L, 155 7450580596923828125L, }; 156 157 private static final int[] LONG_FIVE_POW_BIT_LENGTH = new int[LONG_FIVE_POW.length]; 158 private static final int[] LONG_POWERS_OF_TEN_BIT_LENGTH = new int[MathUtils.LONG_POWERS_OF_TEN.length]; 159 160 private static final int BI_SCALED_BY_ZERO_LENGTH = 11; 161 162 /** 163 * An array with the first <code>BigInteger</code> scaled by zero. 164 * (<code>[0,0],[1,0],...,[10,0]</code>). 165 */ 166 private static final BigDecimal[] BI_SCALED_BY_ZERO = new BigDecimal[BI_SCALED_BY_ZERO_LENGTH]; 167 168 /** 169 * An array with the zero number scaled by the first positive scales. 170 * (<code>0*10^0, 0*10^1, ..., 0*10^10</code>). 171 */ 172 private static final BigDecimal[] ZERO_SCALED_BY = new BigDecimal[11]; 173 174 /** An array filled with characters <code>'0'</code>. */ 175 private static final char[] CH_ZEROS = new char[100]; 176 177 static { Arrays.fill(CH_ZEROS, '0')178 Arrays.fill(CH_ZEROS, '0'); 179 180 for (int i = 0; i < ZERO_SCALED_BY.length; ++i) { 181 BI_SCALED_BY_ZERO[i] = new BigDecimal(i, 0); 182 ZERO_SCALED_BY[i] = new BigDecimal(0, i); 183 } 184 for (int i = 0; i < LONG_FIVE_POW_BIT_LENGTH.length; ++i) { 185 LONG_FIVE_POW_BIT_LENGTH[i] = bitLength(LONG_FIVE_POW[i]); 186 } 187 for (int i = 0; i < LONG_POWERS_OF_TEN_BIT_LENGTH.length; ++i) { 188 LONG_POWERS_OF_TEN_BIT_LENGTH[i] = bitLength(MathUtils.LONG_POWERS_OF_TEN[i]); 189 } 190 191 // Taking the references of useful powers. 192 TEN_POW = Multiplication.bigTenPows; 193 FIVE_POW = Multiplication.bigFivePows; 194 } 195 196 /** 197 * The constant zero as a {@code BigDecimal}. 198 */ 199 public static final BigDecimal ZERO = new BigDecimal(0, 0); 200 201 /** 202 * The constant one as a {@code BigDecimal}. 203 */ 204 public static final BigDecimal ONE = new BigDecimal(1, 0); 205 206 /** 207 * The constant ten as a {@code BigDecimal}. 208 */ 209 public static final BigDecimal TEN = new BigDecimal(10, 0); 210 211 /** 212 * The arbitrary precision integer (unscaled value) in the internal 213 * representation of {@code BigDecimal}. 214 */ 215 private BigInteger intVal; 216 217 private transient int bitLength; 218 219 private transient long smallValue; 220 221 /** 222 * The 32-bit integer scale in the internal representation of {@code BigDecimal}. 223 */ 224 private int scale; 225 226 /** 227 * Represent the number of decimal digits in the unscaled value. This 228 * precision is calculated the first time, and used in the following calls 229 * of method <code>precision()</code>. Note that some call to the private 230 * method <code>inplaceRound()</code> could update this field. 231 * 232 * @see #precision() 233 * @see #inplaceRound(MathContext) 234 */ 235 private transient int precision = 0; 236 BigDecimal(long smallValue, int scale)237 private BigDecimal(long smallValue, int scale){ 238 this.smallValue = smallValue; 239 this.scale = scale; 240 this.bitLength = bitLength(smallValue); 241 } 242 BigDecimal(int smallValue, int scale)243 private BigDecimal(int smallValue, int scale){ 244 this.smallValue = smallValue; 245 this.scale = scale; 246 this.bitLength = bitLength(smallValue); 247 } 248 249 /** 250 * Constructs a new {@code BigDecimal} instance from a string representation 251 * given as a character array. 252 * 253 * @param in 254 * array of characters containing the string representation of 255 * this {@code BigDecimal}. 256 * @param offset 257 * first index to be copied. 258 * @param len 259 * number of characters to be used. 260 * @throws NumberFormatException 261 * if {@code offset < 0 || len <= 0 || offset+len-1 < 0 || 262 * offset+len-1 >= in.length}, or if {@code in} does not 263 * contain a valid string representation of a big decimal. 264 */ BigDecimal(char[] in, int offset, int len)265 public BigDecimal(char[] in, int offset, int len) { 266 int begin = offset; // first index to be copied 267 int last = offset + (len - 1); // last index to be copied 268 String scaleString; // buffer for scale 269 StringBuilder unscaledBuffer; // buffer for unscaled value 270 long newScale; // the new scale 271 272 if (in == null) { 273 throw new NullPointerException("in == null"); 274 } 275 if ((last >= in.length) || (offset < 0) || (len <= 0) || (last < 0)) { 276 throw new NumberFormatException("Bad offset/length: offset=" + offset + 277 " len=" + len + " in.length=" + in.length); 278 } 279 unscaledBuffer = new StringBuilder(len); 280 int bufLength = 0; 281 // To skip a possible '+' symbol 282 if ((offset <= last) && (in[offset] == '+')) { 283 offset++; 284 begin++; 285 } 286 int counter = 0; 287 boolean wasNonZero = false; 288 // Accumulating all digits until a possible decimal point 289 for (; (offset <= last) && (in[offset] != '.') && (in[offset] != 'e') && (in[offset] != 'E'); offset++) { 290 if (!wasNonZero) { 291 if (in[offset] == '0') { 292 counter++; 293 } else { 294 wasNonZero = true; 295 } 296 } 297 298 } 299 unscaledBuffer.append(in, begin, offset - begin); 300 bufLength += offset - begin; 301 // A decimal point was found 302 if ((offset <= last) && (in[offset] == '.')) { 303 offset++; 304 // Accumulating all digits until a possible exponent 305 begin = offset; 306 for (; (offset <= last) && (in[offset] != 'e') 307 && (in[offset] != 'E'); offset++) { 308 if (!wasNonZero) { 309 if (in[offset] == '0') { 310 counter++; 311 } else { 312 wasNonZero = true; 313 } 314 } 315 } 316 scale = offset - begin; 317 bufLength +=scale; 318 unscaledBuffer.append(in, begin, scale); 319 } else { 320 scale = 0; 321 } 322 // An exponent was found 323 if ((offset <= last) && ((in[offset] == 'e') || (in[offset] == 'E'))) { 324 offset++; 325 // Checking for a possible sign of scale 326 begin = offset; 327 if ((offset <= last) && (in[offset] == '+')) { 328 offset++; 329 if ((offset <= last) && (in[offset] != '-')) { 330 begin++; 331 } 332 } 333 // Accumulating all remaining digits 334 scaleString = String.valueOf(in, begin, last + 1 - begin); 335 // Checking if the scale is defined 336 newScale = (long)scale - Integer.parseInt(scaleString); 337 scale = (int)newScale; 338 if (newScale != scale) { 339 throw new NumberFormatException("Scale out of range"); 340 } 341 } 342 // Parsing the unscaled value 343 if (bufLength < 19) { 344 smallValue = Long.parseLong(unscaledBuffer.toString()); 345 bitLength = bitLength(smallValue); 346 } else { 347 setUnscaledValue(new BigInteger(unscaledBuffer.toString())); 348 } 349 } 350 351 /** 352 * Constructs a new {@code BigDecimal} instance from a string representation 353 * given as a character array. 354 * 355 * @param in 356 * array of characters containing the string representation of 357 * this {@code BigDecimal}. 358 * @param offset 359 * first index to be copied. 360 * @param len 361 * number of characters to be used. 362 * @param mc 363 * rounding mode and precision for the result of this operation. 364 * @throws NumberFormatException 365 * if {@code offset < 0 || len <= 0 || offset+len-1 < 0 || 366 * offset+len-1 >= in.length}, or if {@code in} does not 367 * contain a valid string representation of a big decimal. 368 * @throws ArithmeticException 369 * if {@code mc.precision > 0} and {@code mc.roundingMode == 370 * UNNECESSARY} and the new big decimal cannot be represented 371 * within the given precision without rounding. 372 */ BigDecimal(char[] in, int offset, int len, MathContext mc)373 public BigDecimal(char[] in, int offset, int len, MathContext mc) { 374 this(in, offset, len); 375 inplaceRound(mc); 376 } 377 378 /** 379 * Constructs a new {@code BigDecimal} instance from a string representation 380 * given as a character array. 381 * 382 * @param in 383 * array of characters containing the string representation of 384 * this {@code BigDecimal}. 385 * @throws NumberFormatException 386 * if {@code in} does not contain a valid string representation 387 * of a big decimal. 388 */ BigDecimal(char[] in)389 public BigDecimal(char[] in) { 390 this(in, 0, in.length); 391 } 392 393 /** 394 * Constructs a new {@code BigDecimal} instance from a string representation 395 * given as a character array. The result is rounded according to the 396 * specified math context. 397 * 398 * @param in 399 * array of characters containing the string representation of 400 * this {@code BigDecimal}. 401 * @param mc 402 * rounding mode and precision for the result of this operation. 403 * @throws NumberFormatException 404 * if {@code in} does not contain a valid string representation 405 * of a big decimal. 406 * @throws ArithmeticException 407 * if {@code mc.precision > 0} and {@code mc.roundingMode == 408 * UNNECESSARY} and the new big decimal cannot be represented 409 * within the given precision without rounding. 410 */ BigDecimal(char[] in, MathContext mc)411 public BigDecimal(char[] in, MathContext mc) { 412 this(in, 0, in.length); 413 inplaceRound(mc); 414 } 415 416 /** 417 * Constructs a new {@code BigDecimal} instance from a string 418 * representation. 419 * 420 * @throws NumberFormatException 421 * if {@code val} does not contain a valid string representation 422 * of a big decimal. 423 */ BigDecimal(String val)424 public BigDecimal(String val) { 425 this(val.toCharArray(), 0, val.length()); 426 } 427 428 /** 429 * Constructs a new {@code BigDecimal} instance from a string 430 * representation. The result is rounded according to the specified math 431 * context. 432 * 433 * @param mc 434 * rounding mode and precision for the result of this operation. 435 * @throws NumberFormatException 436 * if {@code val} does not contain a valid string representation 437 * of a big decimal. 438 * @throws ArithmeticException 439 * if {@code mc.precision > 0} and {@code mc.roundingMode == 440 * UNNECESSARY} and the new big decimal cannot be represented 441 * within the given precision without rounding. 442 */ BigDecimal(String val, MathContext mc)443 public BigDecimal(String val, MathContext mc) { 444 this(val.toCharArray(), 0, val.length()); 445 inplaceRound(mc); 446 } 447 448 /** 449 * Constructs a new {@code BigDecimal} instance from the 64bit double 450 * {@code val}. The constructed big decimal is equivalent to the given 451 * double. For example, {@code new BigDecimal(0.1)} is equal to {@code 452 * 0.1000000000000000055511151231257827021181583404541015625}. This happens 453 * as {@code 0.1} cannot be represented exactly in binary. 454 * <p> 455 * To generate a big decimal instance which is equivalent to {@code 0.1} use 456 * the {@code BigDecimal(String)} constructor. 457 * 458 * @param val 459 * double value to be converted to a {@code BigDecimal} instance. 460 * @throws NumberFormatException 461 * if {@code val} is infinity or not a number. 462 */ BigDecimal(double val)463 public BigDecimal(double val) { 464 if (Double.isInfinite(val) || Double.isNaN(val)) { 465 throw new NumberFormatException("Infinity or NaN: " + val); 466 } 467 long bits = Double.doubleToLongBits(val); // IEEE-754 468 long mantissa; 469 int trailingZeros; 470 // Extracting the exponent, note that the bias is 1023 471 scale = 1075 - (int)((bits >> 52) & 0x7FFL); 472 // Extracting the 52 bits of the mantissa. 473 mantissa = (scale == 1075) ? (bits & 0xFFFFFFFFFFFFFL) << 1 474 : (bits & 0xFFFFFFFFFFFFFL) | 0x10000000000000L; 475 if (mantissa == 0) { 476 scale = 0; 477 precision = 1; 478 } 479 // To simplify all factors '2' in the mantissa 480 if (scale > 0) { 481 trailingZeros = Math.min(scale, Long.numberOfTrailingZeros(mantissa)); 482 mantissa >>>= trailingZeros; 483 scale -= trailingZeros; 484 } 485 // Calculating the new unscaled value and the new scale 486 if((bits >> 63) != 0) { 487 mantissa = -mantissa; 488 } 489 int mantissaBits = bitLength(mantissa); 490 if (scale < 0) { 491 bitLength = mantissaBits == 0 ? 0 : mantissaBits - scale; 492 if(bitLength < 64) { 493 smallValue = mantissa << (-scale); 494 } else { 495 BigInt bi = new BigInt(); 496 bi.putLongInt(mantissa); 497 bi.shift(-scale); 498 intVal = new BigInteger(bi); 499 } 500 scale = 0; 501 } else if (scale > 0) { 502 // m * 2^e = (m * 5^(-e)) * 10^e 503 if(scale < LONG_FIVE_POW.length 504 && mantissaBits+LONG_FIVE_POW_BIT_LENGTH[scale] < 64) { 505 smallValue = mantissa * LONG_FIVE_POW[scale]; 506 bitLength = bitLength(smallValue); 507 } else { 508 setUnscaledValue(Multiplication.multiplyByFivePow(BigInteger.valueOf(mantissa), scale)); 509 } 510 } else { // scale == 0 511 smallValue = mantissa; 512 bitLength = mantissaBits; 513 } 514 } 515 516 /** 517 * Constructs a new {@code BigDecimal} instance from the 64bit double 518 * {@code val}. The constructed big decimal is equivalent to the given 519 * double. For example, {@code new BigDecimal(0.1)} is equal to {@code 520 * 0.1000000000000000055511151231257827021181583404541015625}. This happens 521 * as {@code 0.1} cannot be represented exactly in binary. 522 * <p> 523 * To generate a big decimal instance which is equivalent to {@code 0.1} use 524 * the {@code BigDecimal(String)} constructor. 525 * 526 * @param val 527 * double value to be converted to a {@code BigDecimal} instance. 528 * @param mc 529 * rounding mode and precision for the result of this operation. 530 * @throws NumberFormatException 531 * if {@code val} is infinity or not a number. 532 * @throws ArithmeticException 533 * if {@code mc.precision > 0} and {@code mc.roundingMode == 534 * UNNECESSARY} and the new big decimal cannot be represented 535 * within the given precision without rounding. 536 */ BigDecimal(double val, MathContext mc)537 public BigDecimal(double val, MathContext mc) { 538 this(val); 539 inplaceRound(mc); 540 } 541 542 /** 543 * Constructs a new {@code BigDecimal} instance from the given big integer 544 * {@code val}. The scale of the result is {@code 0}. 545 */ BigDecimal(BigInteger val)546 public BigDecimal(BigInteger val) { 547 this(val, 0); 548 } 549 550 /** 551 * Constructs a new {@code BigDecimal} instance from the given big integer 552 * {@code val}. The scale of the result is {@code 0}. 553 * 554 * @param mc 555 * rounding mode and precision for the result of this operation. 556 * @throws ArithmeticException 557 * if {@code mc.precision > 0} and {@code mc.roundingMode == 558 * UNNECESSARY} and the new big decimal cannot be represented 559 * within the given precision without rounding. 560 */ BigDecimal(BigInteger val, MathContext mc)561 public BigDecimal(BigInteger val, MathContext mc) { 562 this(val); 563 inplaceRound(mc); 564 } 565 566 /** 567 * Constructs a new {@code BigDecimal} instance from a given unscaled value 568 * {@code unscaledVal} and a given scale. The value of this instance is 569 * {@code unscaledVal * 10<sup>-scale</sup>}). 570 * 571 * @throws NullPointerException 572 * if {@code unscaledVal == null}. 573 */ BigDecimal(BigInteger unscaledVal, int scale)574 public BigDecimal(BigInteger unscaledVal, int scale) { 575 if (unscaledVal == null) { 576 throw new NullPointerException("unscaledVal == null"); 577 } 578 this.scale = scale; 579 setUnscaledValue(unscaledVal); 580 } 581 582 /** 583 * Constructs a new {@code BigDecimal} instance from a given unscaled value 584 * {@code unscaledVal} and a given scale. The value of this instance is 585 * {@code unscaledVal * 10<sup>-scale</sup>). The result is rounded according 586 * to the specified math context. 587 * 588 * @param mc 589 * rounding mode and precision for the result of this operation. 590 * @throws ArithmeticException 591 * if {@code mc.precision > 0} and {@code mc.roundingMode == 592 * UNNECESSARY} and the new big decimal cannot be represented 593 * within the given precision without rounding. 594 * @throws NullPointerException 595 * if {@code unscaledVal == null}. 596 */ BigDecimal(BigInteger unscaledVal, int scale, MathContext mc)597 public BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) { 598 this(unscaledVal, scale); 599 inplaceRound(mc); 600 } 601 602 /** 603 * Constructs a new {@code BigDecimal} instance from the given int 604 * {@code val}. The scale of the result is 0. 605 * 606 * @param val 607 * int value to be converted to a {@code BigDecimal} instance. 608 */ BigDecimal(int val)609 public BigDecimal(int val) { 610 this(val,0); 611 } 612 613 /** 614 * Constructs a new {@code BigDecimal} instance from the given int {@code 615 * val}. The scale of the result is {@code 0}. The result is rounded 616 * according to the specified math context. 617 * 618 * @param val 619 * int value to be converted to a {@code BigDecimal} instance. 620 * @param mc 621 * rounding mode and precision for the result of this operation. 622 * @throws ArithmeticException 623 * if {@code mc.precision > 0} and {@code c.roundingMode == 624 * UNNECESSARY} and the new big decimal cannot be represented 625 * within the given precision without rounding. 626 */ BigDecimal(int val, MathContext mc)627 public BigDecimal(int val, MathContext mc) { 628 this(val,0); 629 inplaceRound(mc); 630 } 631 632 /** 633 * Constructs a new {@code BigDecimal} instance from the given long {@code 634 * val}. The scale of the result is {@code 0}. 635 * 636 * @param val 637 * long value to be converted to a {@code BigDecimal} instance. 638 */ BigDecimal(long val)639 public BigDecimal(long val) { 640 this(val,0); 641 } 642 643 /** 644 * Constructs a new {@code BigDecimal} instance from the given long {@code 645 * val}. The scale of the result is {@code 0}. The result is rounded 646 * according to the specified math context. 647 * 648 * @param val 649 * long value to be converted to a {@code BigDecimal} instance. 650 * @param mc 651 * rounding mode and precision for the result of this operation. 652 * @throws ArithmeticException 653 * if {@code mc.precision > 0} and {@code mc.roundingMode == 654 * UNNECESSARY} and the new big decimal cannot be represented 655 * within the given precision without rounding. 656 */ BigDecimal(long val, MathContext mc)657 public BigDecimal(long val, MathContext mc) { 658 this(val); 659 inplaceRound(mc); 660 } 661 662 /* Public Methods */ 663 664 /** 665 * Returns a new {@code BigDecimal} instance whose value is equal to {@code 666 * unscaledVal * 10<sup>-scale</sup>}). The scale of the result is {@code 667 * scale}, and its unscaled value is {@code unscaledVal}. 668 */ valueOf(long unscaledVal, int scale)669 public static BigDecimal valueOf(long unscaledVal, int scale) { 670 if (scale == 0) { 671 return valueOf(unscaledVal); 672 } 673 if ((unscaledVal == 0) && (scale >= 0) 674 && (scale < ZERO_SCALED_BY.length)) { 675 return ZERO_SCALED_BY[scale]; 676 } 677 return new BigDecimal(unscaledVal, scale); 678 } 679 680 /** 681 * Returns a new {@code BigDecimal} instance whose value is equal to {@code 682 * unscaledVal}. The scale of the result is {@code 0}, and its unscaled 683 * value is {@code unscaledVal}. 684 * 685 * @param unscaledVal 686 * value to be converted to a {@code BigDecimal}. 687 * @return {@code BigDecimal} instance with the value {@code unscaledVal}. 688 */ valueOf(long unscaledVal)689 public static BigDecimal valueOf(long unscaledVal) { 690 if ((unscaledVal >= 0) && (unscaledVal < BI_SCALED_BY_ZERO_LENGTH)) { 691 return BI_SCALED_BY_ZERO[(int)unscaledVal]; 692 } 693 return new BigDecimal(unscaledVal,0); 694 } 695 696 /** 697 * Returns a new {@code BigDecimal} instance whose value is equal to {@code 698 * val}. The new decimal is constructed as if the {@code BigDecimal(String)} 699 * constructor is called with an argument which is equal to {@code 700 * Double.toString(val)}. For example, {@code valueOf("0.1")} is converted to 701 * (unscaled=1, scale=1), although the double {@code 0.1} cannot be 702 * represented exactly as a double value. In contrast to that, a new {@code 703 * BigDecimal(0.1)} instance has the value {@code 704 * 0.1000000000000000055511151231257827021181583404541015625} with an 705 * unscaled value {@code 1000000000000000055511151231257827021181583404541015625} 706 * and the scale {@code 55}. 707 * 708 * @param val 709 * double value to be converted to a {@code BigDecimal}. 710 * @return {@code BigDecimal} instance with the value {@code val}. 711 * @throws NumberFormatException 712 * if {@code val} is infinite or {@code val} is not a number 713 */ valueOf(double val)714 public static BigDecimal valueOf(double val) { 715 if (Double.isInfinite(val) || Double.isNaN(val)) { 716 throw new NumberFormatException("Infinity or NaN: " + val); 717 } 718 return new BigDecimal(Double.toString(val)); 719 } 720 721 /** 722 * Returns a new {@code BigDecimal} whose value is {@code this + augend}. 723 * The scale of the result is the maximum of the scales of the two 724 * arguments. 725 * 726 * @param augend 727 * value to be added to {@code this}. 728 * @return {@code this + augend}. 729 * @throws NullPointerException 730 * if {@code augend == null}. 731 */ add(BigDecimal augend)732 public BigDecimal add(BigDecimal augend) { 733 int diffScale = this.scale - augend.scale; 734 // Fast return when some operand is zero 735 if (this.isZero()) { 736 if (diffScale <= 0) { 737 return augend; 738 } 739 if (augend.isZero()) { 740 return this; 741 } 742 } else if (augend.isZero()) { 743 if (diffScale >= 0) { 744 return this; 745 } 746 } 747 // Let be: this = [u1,s1] and augend = [u2,s2] 748 if (diffScale == 0) { 749 // case s1 == s2: [u1 + u2 , s1] 750 if (Math.max(this.bitLength, augend.bitLength) + 1 < 64) { 751 return valueOf(this.smallValue + augend.smallValue, this.scale); 752 } 753 return new BigDecimal(this.getUnscaledValue().add(augend.getUnscaledValue()), this.scale); 754 } else if (diffScale > 0) { 755 // case s1 > s2 : [(u1 + u2) * 10 ^ (s1 - s2) , s1] 756 return addAndMult10(this, augend, diffScale); 757 } else {// case s2 > s1 : [(u2 + u1) * 10 ^ (s2 - s1) , s2] 758 return addAndMult10(augend, this, -diffScale); 759 } 760 } 761 addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale)762 private static BigDecimal addAndMult10(BigDecimal thisValue,BigDecimal augend, int diffScale) { 763 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 764 Math.max(thisValue.bitLength,augend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) { 765 return valueOf(thisValue.smallValue+augend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],thisValue.scale); 766 } else { 767 BigInt bi = Multiplication.multiplyByTenPow(augend.getUnscaledValue(),diffScale).getBigInt(); 768 bi.add(thisValue.getUnscaledValue().getBigInt()); 769 return new BigDecimal(new BigInteger(bi), thisValue.scale); 770 } 771 } 772 773 /** 774 * Returns a new {@code BigDecimal} whose value is {@code this + augend}. 775 * The result is rounded according to the passed context {@code mc}. 776 * 777 * @param augend 778 * value to be added to {@code this}. 779 * @param mc 780 * rounding mode and precision for the result of this operation. 781 * @return {@code this + augend}. 782 * @throws NullPointerException 783 * if {@code augend == null} or {@code mc == null}. 784 */ add(BigDecimal augend, MathContext mc)785 public BigDecimal add(BigDecimal augend, MathContext mc) { 786 BigDecimal larger; // operand with the largest unscaled value 787 BigDecimal smaller; // operand with the smallest unscaled value 788 BigInteger tempBI; 789 long diffScale = (long)this.scale - augend.scale; 790 int largerSignum; 791 // Some operand is zero or the precision is infinity 792 if ((augend.isZero()) || (this.isZero()) 793 || (mc.getPrecision() == 0)) { 794 return add(augend).round(mc); 795 } 796 // Cases where there is room for optimizations 797 if (this.approxPrecision() < diffScale - 1) { 798 larger = augend; 799 smaller = this; 800 } else if (augend.approxPrecision() < -diffScale - 1) { 801 larger = this; 802 smaller = augend; 803 } else {// No optimization is done 804 return add(augend).round(mc); 805 } 806 if (mc.getPrecision() >= larger.approxPrecision()) { 807 // No optimization is done 808 return add(augend).round(mc); 809 } 810 // Cases where it's unnecessary to add two numbers with very different scales 811 largerSignum = larger.signum(); 812 if (largerSignum == smaller.signum()) { 813 tempBI = Multiplication.multiplyByPositiveInt(larger.getUnscaledValue(),10) 814 .add(BigInteger.valueOf(largerSignum)); 815 } else { 816 tempBI = larger.getUnscaledValue().subtract( 817 BigInteger.valueOf(largerSignum)); 818 tempBI = Multiplication.multiplyByPositiveInt(tempBI,10) 819 .add(BigInteger.valueOf(largerSignum * 9)); 820 } 821 // Rounding the improved adding 822 larger = new BigDecimal(tempBI, larger.scale + 1); 823 return larger.round(mc); 824 } 825 826 /** 827 * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}. 828 * The scale of the result is the maximum of the scales of the two arguments. 829 * 830 * @param subtrahend 831 * value to be subtracted from {@code this}. 832 * @return {@code this - subtrahend}. 833 * @throws NullPointerException 834 * if {@code subtrahend == null}. 835 */ subtract(BigDecimal subtrahend)836 public BigDecimal subtract(BigDecimal subtrahend) { 837 int diffScale = this.scale - subtrahend.scale; 838 // Fast return when some operand is zero 839 if (this.isZero()) { 840 if (diffScale <= 0) { 841 return subtrahend.negate(); 842 } 843 if (subtrahend.isZero()) { 844 return this; 845 } 846 } else if (subtrahend.isZero()) { 847 if (diffScale >= 0) { 848 return this; 849 } 850 } 851 // Let be: this = [u1,s1] and subtrahend = [u2,s2] so: 852 if (diffScale == 0) { 853 // case s1 = s2 : [u1 - u2 , s1] 854 if (Math.max(this.bitLength, subtrahend.bitLength) + 1 < 64) { 855 return valueOf(this.smallValue - subtrahend.smallValue,this.scale); 856 } 857 return new BigDecimal(this.getUnscaledValue().subtract(subtrahend.getUnscaledValue()), this.scale); 858 } else if (diffScale > 0) { 859 // case s1 > s2 : [ u1 - u2 * 10 ^ (s1 - s2) , s1 ] 860 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 861 Math.max(this.bitLength,subtrahend.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale])+1<64) { 862 return valueOf(this.smallValue-subtrahend.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale],this.scale); 863 } 864 return new BigDecimal(this.getUnscaledValue().subtract( 865 Multiplication.multiplyByTenPow(subtrahend.getUnscaledValue(),diffScale)), this.scale); 866 } else {// case s2 > s1 : [ u1 * 10 ^ (s2 - s1) - u2 , s2 ] 867 diffScale = -diffScale; 868 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 869 Math.max(this.bitLength+LONG_POWERS_OF_TEN_BIT_LENGTH[diffScale],subtrahend.bitLength)+1<64) { 870 return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[diffScale]-subtrahend.smallValue,subtrahend.scale); 871 } 872 return new BigDecimal(Multiplication.multiplyByTenPow(this.getUnscaledValue(),diffScale) 873 .subtract(subtrahend.getUnscaledValue()), subtrahend.scale); 874 } 875 } 876 877 /** 878 * Returns a new {@code BigDecimal} whose value is {@code this - subtrahend}. 879 * The result is rounded according to the passed context {@code mc}. 880 * 881 * @param subtrahend 882 * value to be subtracted from {@code this}. 883 * @param mc 884 * rounding mode and precision for the result of this operation. 885 * @return {@code this - subtrahend}. 886 * @throws NullPointerException 887 * if {@code subtrahend == null} or {@code mc == null}. 888 */ subtract(BigDecimal subtrahend, MathContext mc)889 public BigDecimal subtract(BigDecimal subtrahend, MathContext mc) { 890 long diffScale = subtrahend.scale - (long)this.scale; 891 int thisSignum; 892 BigDecimal leftOperand; // it will be only the left operand (this) 893 BigInteger tempBI; 894 // Some operand is zero or the precision is infinity 895 if ((subtrahend.isZero()) || (this.isZero()) 896 || (mc.getPrecision() == 0)) { 897 return subtract(subtrahend).round(mc); 898 } 899 // Now: this != 0 and subtrahend != 0 900 if (subtrahend.approxPrecision() < diffScale - 1) { 901 // Cases where it is unnecessary to subtract two numbers with very different scales 902 if (mc.getPrecision() < this.approxPrecision()) { 903 thisSignum = this.signum(); 904 if (thisSignum != subtrahend.signum()) { 905 tempBI = Multiplication.multiplyByPositiveInt(this.getUnscaledValue(), 10) 906 .add(BigInteger.valueOf(thisSignum)); 907 } else { 908 tempBI = this.getUnscaledValue().subtract(BigInteger.valueOf(thisSignum)); 909 tempBI = Multiplication.multiplyByPositiveInt(tempBI, 10) 910 .add(BigInteger.valueOf(thisSignum * 9)); 911 } 912 // Rounding the improved subtracting 913 leftOperand = new BigDecimal(tempBI, this.scale + 1); 914 return leftOperand.round(mc); 915 } 916 } 917 // No optimization is done 918 return subtract(subtrahend).round(mc); 919 } 920 921 /** 922 * Returns a new {@code BigDecimal} whose value is {@code this * 923 * multiplicand}. The scale of the result is the sum of the scales of the 924 * two arguments. 925 * 926 * @param multiplicand 927 * value to be multiplied with {@code this}. 928 * @return {@code this * multiplicand}. 929 * @throws NullPointerException 930 * if {@code multiplicand == null}. 931 */ multiply(BigDecimal multiplicand)932 public BigDecimal multiply(BigDecimal multiplicand) { 933 long newScale = (long)this.scale + multiplicand.scale; 934 935 if ((this.isZero()) || (multiplicand.isZero())) { 936 return zeroScaledBy(newScale); 937 } 938 /* Let be: this = [u1,s1] and multiplicand = [u2,s2] so: 939 * this x multiplicand = [ s1 * s2 , s1 + s2 ] */ 940 if (this.bitLength + multiplicand.bitLength < 64) { 941 long unscaledValue = this.smallValue * multiplicand.smallValue; 942 // b/19185440 Case where result should be +2^63 but unscaledValue overflowed to -2^63 943 boolean longMultiplicationOverflowed = (unscaledValue == Long.MIN_VALUE) && 944 (Math.signum(smallValue) * Math.signum(multiplicand.smallValue) > 0); 945 if (!longMultiplicationOverflowed) { 946 return valueOf(unscaledValue, safeLongToInt(newScale)); 947 } 948 } 949 return new BigDecimal(this.getUnscaledValue().multiply( 950 multiplicand.getUnscaledValue()), safeLongToInt(newScale)); 951 } 952 953 /** 954 * Returns a new {@code BigDecimal} whose value is {@code this * 955 * multiplicand}. The result is rounded according to the passed context 956 * {@code mc}. 957 * 958 * @param multiplicand 959 * value to be multiplied with {@code this}. 960 * @param mc 961 * rounding mode and precision for the result of this operation. 962 * @return {@code this * multiplicand}. 963 * @throws NullPointerException 964 * if {@code multiplicand == null} or {@code mc == null}. 965 */ multiply(BigDecimal multiplicand, MathContext mc)966 public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { 967 BigDecimal result = multiply(multiplicand); 968 969 result.inplaceRound(mc); 970 return result; 971 } 972 973 /** 974 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 975 * As scale of the result the parameter {@code scale} is used. If rounding 976 * is required to meet the specified scale, then the specified rounding mode 977 * {@code roundingMode} is applied. 978 * 979 * @param divisor 980 * value by which {@code this} is divided. 981 * @param scale 982 * the scale of the result returned. 983 * @param roundingMode 984 * rounding mode to be used to round the result. 985 * @return {@code this / divisor} rounded according to the given rounding 986 * mode. 987 * @throws NullPointerException 988 * if {@code divisor == null}. 989 * @throws IllegalArgumentException 990 * if {@code roundingMode} is not a valid rounding mode. 991 * @throws ArithmeticException 992 * if {@code divisor == 0}. 993 * @throws ArithmeticException 994 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 995 * necessary according to the given scale. 996 */ divide(BigDecimal divisor, int scale, int roundingMode)997 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { 998 return divide(divisor, scale, RoundingMode.valueOf(roundingMode)); 999 } 1000 1001 /** 1002 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1003 * As scale of the result the parameter {@code scale} is used. If rounding 1004 * is required to meet the specified scale, then the specified rounding mode 1005 * {@code roundingMode} is applied. 1006 * 1007 * @param divisor 1008 * value by which {@code this} is divided. 1009 * @param scale 1010 * the scale of the result returned. 1011 * @param roundingMode 1012 * rounding mode to be used to round the result. 1013 * @return {@code this / divisor} rounded according to the given rounding 1014 * mode. 1015 * @throws NullPointerException 1016 * if {@code divisor == null} or {@code roundingMode == null}. 1017 * @throws ArithmeticException 1018 * if {@code divisor == 0}. 1019 * @throws ArithmeticException 1020 * if {@code roundingMode == RoundingMode.UNNECESSAR}Y and 1021 * rounding is necessary according to the given scale and given 1022 * precision. 1023 */ divide(BigDecimal divisor, int scale, RoundingMode roundingMode)1024 public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { 1025 // Let be: this = [u1,s1] and divisor = [u2,s2] 1026 if (roundingMode == null) { 1027 throw new NullPointerException("roundingMode == null"); 1028 } 1029 if (divisor.isZero()) { 1030 throw new ArithmeticException("Division by zero"); 1031 } 1032 1033 long diffScale = ((long)this.scale - divisor.scale) - scale; 1034 1035 // Check whether the diffScale will fit into an int. See http://b/17393664. 1036 if (bitLength(diffScale) > 32) { 1037 throw new ArithmeticException( 1038 "Unable to perform divisor / dividend scaling: the difference in scale is too" + 1039 " big (" + diffScale + ")"); 1040 } 1041 1042 if(this.bitLength < 64 && divisor.bitLength < 64 ) { 1043 if(diffScale == 0) { 1044 // http://b/26105053 - corner case: Long.MIN_VALUE / (-1) overflows a long 1045 if (this.smallValue != Long.MIN_VALUE || divisor.smallValue != -1) { 1046 return dividePrimitiveLongs(this.smallValue, 1047 divisor.smallValue, 1048 scale, 1049 roundingMode); 1050 } 1051 } else if(diffScale > 0) { 1052 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1053 divisor.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale] < 64) { 1054 return dividePrimitiveLongs(this.smallValue, 1055 divisor.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale], 1056 scale, 1057 roundingMode); 1058 } 1059 } else { // diffScale < 0 1060 if(-diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1061 this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-diffScale] < 64) { 1062 return dividePrimitiveLongs(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], 1063 divisor.smallValue, 1064 scale, 1065 roundingMode); 1066 } 1067 1068 } 1069 } 1070 BigInteger scaledDividend = this.getUnscaledValue(); 1071 BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2' 1072 1073 if (diffScale > 0) { 1074 // Multiply 'u2' by: 10^((s1 - s2) - scale) 1075 scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale); 1076 } else if (diffScale < 0) { 1077 // Multiply 'u1' by: 10^(scale - (s1 - s2)) 1078 scaledDividend = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale); 1079 } 1080 return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode); 1081 } 1082 divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode)1083 private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) { 1084 1085 BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor); // quotient and remainder 1086 // If after division there is a remainder... 1087 BigInteger quotient = quotAndRem[0]; 1088 BigInteger remainder = quotAndRem[1]; 1089 if (remainder.signum() == 0) { 1090 return new BigDecimal(quotient, scale); 1091 } 1092 int sign = scaledDividend.signum() * scaledDivisor.signum(); 1093 int compRem; // 'compare to remainder' 1094 if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2 1095 long rem = remainder.longValue(); 1096 long divisor = scaledDivisor.longValue(); 1097 compRem = compareForRounding(rem, divisor); 1098 // To look if there is a carry 1099 compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0, 1100 sign * (5 + compRem), roundingMode); 1101 1102 } else { 1103 // Checking if: remainder * 2 >= scaledDivisor 1104 compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs()); 1105 compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0, 1106 sign * (5 + compRem), roundingMode); 1107 } 1108 if (compRem != 0) { 1109 if(quotient.bitLength() < 63) { 1110 return valueOf(quotient.longValue() + compRem,scale); 1111 } 1112 quotient = quotient.add(BigInteger.valueOf(compRem)); 1113 return new BigDecimal(quotient, scale); 1114 } 1115 // Constructing the result with the appropriate unscaled value 1116 return new BigDecimal(quotient, scale); 1117 } 1118 dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode)1119 private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) { 1120 long quotient = scaledDividend / scaledDivisor; 1121 long remainder = scaledDividend % scaledDivisor; 1122 int sign = Long.signum( scaledDividend ) * Long.signum( scaledDivisor ); 1123 if (remainder != 0) { 1124 // Checking if: remainder * 2 >= scaledDivisor 1125 int compRem = compareForRounding(remainder, scaledDivisor); // 'compare to remainder' 1126 // To look if there is a carry 1127 quotient += roundingBehavior(((int)quotient) & 1, 1128 sign * (5 + compRem), 1129 roundingMode); 1130 } 1131 // Constructing the result with the appropriate unscaled value 1132 return valueOf(quotient, scale); 1133 } 1134 1135 /** 1136 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1137 * The scale of the result is the scale of {@code this}. If rounding is 1138 * required to meet the specified scale, then the specified rounding mode 1139 * {@code roundingMode} is applied. 1140 * 1141 * @param divisor 1142 * value by which {@code this} is divided. 1143 * @param roundingMode 1144 * rounding mode to be used to round the result. 1145 * @return {@code this / divisor} rounded according to the given rounding 1146 * mode. 1147 * @throws NullPointerException 1148 * if {@code divisor == null}. 1149 * @throws IllegalArgumentException 1150 * if {@code roundingMode} is not a valid rounding mode. 1151 * @throws ArithmeticException 1152 * if {@code divisor == 0}. 1153 * @throws ArithmeticException 1154 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1155 * necessary according to the scale of this. 1156 */ divide(BigDecimal divisor, int roundingMode)1157 public BigDecimal divide(BigDecimal divisor, int roundingMode) { 1158 return divide(divisor, scale, RoundingMode.valueOf(roundingMode)); 1159 } 1160 1161 /** 1162 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1163 * The scale of the result is the scale of {@code this}. If rounding is 1164 * required to meet the specified scale, then the specified rounding mode 1165 * {@code roundingMode} is applied. 1166 * 1167 * @param divisor 1168 * value by which {@code this} is divided. 1169 * @param roundingMode 1170 * rounding mode to be used to round the result. 1171 * @return {@code this / divisor} rounded according to the given rounding 1172 * mode. 1173 * @throws NullPointerException 1174 * if {@code divisor == null} or {@code roundingMode == null}. 1175 * @throws ArithmeticException 1176 * if {@code divisor == 0}. 1177 * @throws ArithmeticException 1178 * if {@code roundingMode == RoundingMode.UNNECESSARY} and 1179 * rounding is necessary according to the scale of this. 1180 */ divide(BigDecimal divisor, RoundingMode roundingMode)1181 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { 1182 return divide(divisor, scale, roundingMode); 1183 } 1184 1185 /** 1186 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1187 * The scale of the result is the difference of the scales of {@code this} 1188 * and {@code divisor}. If the exact result requires more digits, then the 1189 * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125} 1190 * which has a scale of {@code 7} and precision {@code 5}. 1191 * 1192 * @param divisor 1193 * value by which {@code this} is divided. 1194 * @return {@code this / divisor}. 1195 * @throws NullPointerException 1196 * if {@code divisor == null}. 1197 * @throws ArithmeticException 1198 * if {@code divisor == 0}. 1199 * @throws ArithmeticException 1200 * if the result cannot be represented exactly. 1201 */ divide(BigDecimal divisor)1202 public BigDecimal divide(BigDecimal divisor) { 1203 BigInteger p = this.getUnscaledValue(); 1204 BigInteger q = divisor.getUnscaledValue(); 1205 BigInteger gcd; // greatest common divisor between 'p' and 'q' 1206 BigInteger quotAndRem[]; 1207 long diffScale = (long)scale - divisor.scale; 1208 int newScale; // the new scale for final quotient 1209 int k; // number of factors "2" in 'q' 1210 int l = 0; // number of factors "5" in 'q' 1211 int i = 1; 1212 int lastPow = FIVE_POW.length - 1; 1213 1214 if (divisor.isZero()) { 1215 throw new ArithmeticException("Division by zero"); 1216 } 1217 if (p.signum() == 0) { 1218 return zeroScaledBy(diffScale); 1219 } 1220 // To divide both by the GCD 1221 gcd = p.gcd(q); 1222 p = p.divide(gcd); 1223 q = q.divide(gcd); 1224 // To simplify all "2" factors of q, dividing by 2^k 1225 k = q.getLowestSetBit(); 1226 q = q.shiftRight(k); 1227 // To simplify all "5" factors of q, dividing by 5^l 1228 do { 1229 quotAndRem = q.divideAndRemainder(FIVE_POW[i]); 1230 if (quotAndRem[1].signum() == 0) { 1231 l += i; 1232 if (i < lastPow) { 1233 i++; 1234 } 1235 q = quotAndRem[0]; 1236 } else { 1237 if (i == 1) { 1238 break; 1239 } 1240 i = 1; 1241 } 1242 } while (true); 1243 // If abs(q) != 1 then the quotient is periodic 1244 if (!q.abs().equals(BigInteger.ONE)) { 1245 throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result"); 1246 } 1247 // The sign of the is fixed and the quotient will be saved in 'p' 1248 if (q.signum() < 0) { 1249 p = p.negate(); 1250 } 1251 // Checking if the new scale is out of range 1252 newScale = safeLongToInt(diffScale + Math.max(k, l)); 1253 // k >= 0 and l >= 0 implies that k - l is in the 32-bit range 1254 i = k - l; 1255 1256 p = (i > 0) ? Multiplication.multiplyByFivePow(p, i) 1257 : p.shiftLeft(-i); 1258 return new BigDecimal(p, newScale); 1259 } 1260 1261 /** 1262 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1263 * The result is rounded according to the passed context {@code mc}. If the 1264 * passed math context specifies precision {@code 0}, then this call is 1265 * equivalent to {@code this.divide(divisor)}. 1266 * 1267 * @param divisor 1268 * value by which {@code this} is divided. 1269 * @param mc 1270 * rounding mode and precision for the result of this operation. 1271 * @return {@code this / divisor}. 1272 * @throws NullPointerException 1273 * if {@code divisor == null} or {@code mc == null}. 1274 * @throws ArithmeticException 1275 * if {@code divisor == 0}. 1276 * @throws ArithmeticException 1277 * if {@code mc.getRoundingMode() == UNNECESSARY} and rounding 1278 * is necessary according {@code mc.getPrecision()}. 1279 */ divide(BigDecimal divisor, MathContext mc)1280 public BigDecimal divide(BigDecimal divisor, MathContext mc) { 1281 /* Calculating how many zeros must be append to 'dividend' 1282 * to obtain a quotient with at least 'mc.precision()' digits */ 1283 long trailingZeros = mc.getPrecision() + 2L 1284 + divisor.approxPrecision() - approxPrecision(); 1285 long diffScale = (long)scale - divisor.scale; 1286 long newScale = diffScale; // scale of the final quotient 1287 int compRem; // to compare the remainder 1288 int i = 1; // index 1289 int lastPow = TEN_POW.length - 1; // last power of ten 1290 BigInteger integerQuot; // for temporal results 1291 BigInteger quotAndRem[] = {getUnscaledValue()}; 1292 // In special cases it reduces the problem to call the dual method 1293 if ((mc.getPrecision() == 0) || (this.isZero()) 1294 || (divisor.isZero())) { 1295 return this.divide(divisor); 1296 } 1297 if (trailingZeros > 0) { 1298 // To append trailing zeros at end of dividend 1299 quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(trailingZeros) ); 1300 newScale += trailingZeros; 1301 } 1302 quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() ); 1303 integerQuot = quotAndRem[0]; 1304 // Calculating the exact quotient with at least 'mc.precision()' digits 1305 if (quotAndRem[1].signum() != 0) { 1306 // Checking if: 2 * remainder >= divisor ? 1307 compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() ); 1308 // quot := quot * 10 + r; with 'r' in {-6,-5,-4, 0,+4,+5,+6} 1309 integerQuot = integerQuot.multiply(BigInteger.TEN) 1310 .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem))); 1311 newScale++; 1312 } else { 1313 // To strip trailing zeros until the preferred scale is reached 1314 while (!integerQuot.testBit(0)) { 1315 quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]); 1316 if ((quotAndRem[1].signum() == 0) 1317 && (newScale - i >= diffScale)) { 1318 newScale -= i; 1319 if (i < lastPow) { 1320 i++; 1321 } 1322 integerQuot = quotAndRem[0]; 1323 } else { 1324 if (i == 1) { 1325 break; 1326 } 1327 i = 1; 1328 } 1329 } 1330 } 1331 // To perform rounding 1332 return new BigDecimal(integerQuot, safeLongToInt(newScale), mc); 1333 } 1334 1335 /** 1336 * Returns a new {@code BigDecimal} whose value is the integral part of 1337 * {@code this / divisor}. The quotient is rounded down towards zero to the 1338 * next integer. For example, {@code 0.5/0.2 = 2}. 1339 * 1340 * @param divisor 1341 * value by which {@code this} is divided. 1342 * @return integral part of {@code this / divisor}. 1343 * @throws NullPointerException 1344 * if {@code divisor == null}. 1345 * @throws ArithmeticException 1346 * if {@code divisor == 0}. 1347 */ divideToIntegralValue(BigDecimal divisor)1348 public BigDecimal divideToIntegralValue(BigDecimal divisor) { 1349 BigInteger integralValue; // the integer of result 1350 BigInteger powerOfTen; // some power of ten 1351 1352 long newScale = (long)this.scale - divisor.scale; 1353 long tempScale = 0; 1354 int i = 1; 1355 int lastPow = TEN_POW.length - 1; 1356 1357 if (divisor.isZero()) { 1358 throw new ArithmeticException("Division by zero"); 1359 } 1360 if ((divisor.approxPrecision() + newScale > this.approxPrecision() + 1L) 1361 || (this.isZero())) { 1362 /* If the divisor's integer part is greater than this's integer part, 1363 * the result must be zero with the appropriate scale */ 1364 integralValue = BigInteger.ZERO; 1365 } else if (newScale == 0) { 1366 integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() ); 1367 } else if (newScale > 0) { 1368 powerOfTen = Multiplication.powerOf10(newScale); 1369 integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) ); 1370 integralValue = integralValue.multiply(powerOfTen); 1371 } else {// (newScale < 0) 1372 powerOfTen = Multiplication.powerOf10(-newScale); 1373 integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() ); 1374 // To strip trailing zeros approximating to the preferred scale 1375 while (!integralValue.testBit(0)) { 1376 BigInteger[] quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]); 1377 if ((quotAndRem[1].signum() == 0) 1378 && (tempScale - i >= newScale)) { 1379 tempScale -= i; 1380 if (i < lastPow) { 1381 i++; 1382 } 1383 integralValue = quotAndRem[0]; 1384 } else { 1385 if (i == 1) { 1386 break; 1387 } 1388 i = 1; 1389 } 1390 } 1391 newScale = tempScale; 1392 } 1393 return ((integralValue.signum() == 0) 1394 ? zeroScaledBy(newScale) 1395 : new BigDecimal(integralValue, safeLongToInt(newScale))); 1396 } 1397 1398 /** 1399 * Returns a new {@code BigDecimal} whose value is the integral part of 1400 * {@code this / divisor}. The quotient is rounded down towards zero to the 1401 * next integer. The rounding mode passed with the parameter {@code mc} is 1402 * not considered. But if the precision of {@code mc > 0} and the integral 1403 * part requires more digits, then an {@code ArithmeticException} is thrown. 1404 * 1405 * @param divisor 1406 * value by which {@code this} is divided. 1407 * @param mc 1408 * math context which determines the maximal precision of the 1409 * result. 1410 * @return integral part of {@code this / divisor}. 1411 * @throws NullPointerException 1412 * if {@code divisor == null} or {@code mc == null}. 1413 * @throws ArithmeticException 1414 * if {@code divisor == 0}. 1415 * @throws ArithmeticException 1416 * if {@code mc.getPrecision() > 0} and the result requires more 1417 * digits to be represented. 1418 */ divideToIntegralValue(BigDecimal divisor, MathContext mc)1419 public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { 1420 int mcPrecision = mc.getPrecision(); 1421 int diffPrecision = this.precision() - divisor.precision(); 1422 int lastPow = TEN_POW.length - 1; 1423 long diffScale = (long)this.scale - divisor.scale; 1424 long newScale = diffScale; 1425 long quotPrecision = diffPrecision - diffScale + 1; 1426 BigInteger quotAndRem[] = new BigInteger[2]; 1427 // In special cases it call the dual method 1428 if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) { 1429 return this.divideToIntegralValue(divisor); 1430 } 1431 // Let be: this = [u1,s1] and divisor = [u2,s2] 1432 if (quotPrecision <= 0) { 1433 quotAndRem[0] = BigInteger.ZERO; 1434 } else if (diffScale == 0) { 1435 // CASE s1 == s2: to calculate u1 / u2 1436 quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() ); 1437 } else if (diffScale > 0) { 1438 // CASE s1 >= s2: to calculate u1 / (u2 * 10^(s1-s2) 1439 quotAndRem[0] = this.getUnscaledValue().divide( 1440 divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) ); 1441 // To chose 10^newScale to get a quotient with at least 'mc.precision()' digits 1442 newScale = Math.min(diffScale, Math.max(mcPrecision - quotPrecision + 1, 0)); 1443 // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale 1444 quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale)); 1445 } else {// CASE s2 > s1: 1446 /* To calculate the minimum power of ten, such that the quotient 1447 * (u1 * 10^exp) / u2 has at least 'mc.precision()' digits. */ 1448 long exp = Math.min(-diffScale, Math.max((long)mcPrecision - diffPrecision, 0)); 1449 long compRemDiv; 1450 // Let be: (u1 * 10^exp) / u2 = [q,r] 1451 quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)). 1452 divideAndRemainder(divisor.getUnscaledValue()); 1453 newScale += exp; // To fix the scale 1454 exp = -newScale; // The remaining power of ten 1455 // If after division there is a remainder... 1456 if ((quotAndRem[1].signum() != 0) && (exp > 0)) { 1457 // Log10(r) + ((s2 - s1) - exp) > mc.precision ? 1458 compRemDiv = (new BigDecimal(quotAndRem[1])).precision() 1459 + exp - divisor.precision(); 1460 if (compRemDiv == 0) { 1461 // To calculate: (r * 10^exp2) / u2 1462 quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)). 1463 divide(divisor.getUnscaledValue()); 1464 compRemDiv = Math.abs(quotAndRem[1].signum()); 1465 } 1466 if (compRemDiv > 0) { 1467 throw new ArithmeticException("Division impossible"); 1468 } 1469 } 1470 } 1471 // Fast return if the quotient is zero 1472 if (quotAndRem[0].signum() == 0) { 1473 return zeroScaledBy(diffScale); 1474 } 1475 BigInteger strippedBI = quotAndRem[0]; 1476 BigDecimal integralValue = new BigDecimal(quotAndRem[0]); 1477 long resultPrecision = integralValue.precision(); 1478 int i = 1; 1479 // To strip trailing zeros until the specified precision is reached 1480 while (!strippedBI.testBit(0)) { 1481 quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]); 1482 if ((quotAndRem[1].signum() == 0) && 1483 ((resultPrecision - i >= mcPrecision) 1484 || (newScale - i >= diffScale)) ) { 1485 resultPrecision -= i; 1486 newScale -= i; 1487 if (i < lastPow) { 1488 i++; 1489 } 1490 strippedBI = quotAndRem[0]; 1491 } else { 1492 if (i == 1) { 1493 break; 1494 } 1495 i = 1; 1496 } 1497 } 1498 // To check if the result fit in 'mc.precision()' digits 1499 if (resultPrecision > mcPrecision) { 1500 throw new ArithmeticException("Division impossible"); 1501 } 1502 integralValue.scale = safeLongToInt(newScale); 1503 integralValue.setUnscaledValue(strippedBI); 1504 return integralValue; 1505 } 1506 1507 /** 1508 * Returns a new {@code BigDecimal} whose value is {@code this % divisor}. 1509 * <p> 1510 * The remainder is defined as {@code this - 1511 * this.divideToIntegralValue(divisor) * divisor}. 1512 * 1513 * @param divisor 1514 * value by which {@code this} is divided. 1515 * @return {@code this % divisor}. 1516 * @throws NullPointerException 1517 * if {@code divisor == null}. 1518 * @throws ArithmeticException 1519 * if {@code divisor == 0}. 1520 */ remainder(BigDecimal divisor)1521 public BigDecimal remainder(BigDecimal divisor) { 1522 return divideAndRemainder(divisor)[1]; 1523 } 1524 1525 /** 1526 * Returns a new {@code BigDecimal} whose value is {@code this % divisor}. 1527 * <p> 1528 * The remainder is defined as {@code this - 1529 * this.divideToIntegralValue(divisor) * divisor}. 1530 * <p> 1531 * The specified rounding mode {@code mc} is used for the division only. 1532 * 1533 * @param divisor 1534 * value by which {@code this} is divided. 1535 * @param mc 1536 * rounding mode and precision to be used. 1537 * @return {@code this % divisor}. 1538 * @throws NullPointerException 1539 * if {@code divisor == null}. 1540 * @throws ArithmeticException 1541 * if {@code divisor == 0}. 1542 * @throws ArithmeticException 1543 * if {@code mc.getPrecision() > 0} and the result of {@code 1544 * this.divideToIntegralValue(divisor, mc)} requires more digits 1545 * to be represented. 1546 */ remainder(BigDecimal divisor, MathContext mc)1547 public BigDecimal remainder(BigDecimal divisor, MathContext mc) { 1548 return divideAndRemainder(divisor, mc)[1]; 1549 } 1550 1551 /** 1552 * Returns a {@code BigDecimal} array which contains the integral part of 1553 * {@code this / divisor} at index 0 and the remainder {@code this % 1554 * divisor} at index 1. The quotient is rounded down towards zero to the 1555 * next integer. 1556 * 1557 * @param divisor 1558 * value by which {@code this} is divided. 1559 * @return {@code [this.divideToIntegralValue(divisor), 1560 * this.remainder(divisor)]}. 1561 * @throws NullPointerException 1562 * if {@code divisor == null}. 1563 * @throws ArithmeticException 1564 * if {@code divisor == 0}. 1565 * @see #divideToIntegralValue 1566 * @see #remainder 1567 */ divideAndRemainder(BigDecimal divisor)1568 public BigDecimal[] divideAndRemainder(BigDecimal divisor) { 1569 BigDecimal quotAndRem[] = new BigDecimal[2]; 1570 1571 quotAndRem[0] = this.divideToIntegralValue(divisor); 1572 quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) ); 1573 return quotAndRem; 1574 } 1575 1576 /** 1577 * Returns a {@code BigDecimal} array which contains the integral part of 1578 * {@code this / divisor} at index 0 and the remainder {@code this % 1579 * divisor} at index 1. The quotient is rounded down towards zero to the 1580 * next integer. The rounding mode passed with the parameter {@code mc} is 1581 * not considered. But if the precision of {@code mc > 0} and the integral 1582 * part requires more digits, then an {@code ArithmeticException} is thrown. 1583 * 1584 * @param divisor 1585 * value by which {@code this} is divided. 1586 * @param mc 1587 * math context which determines the maximal precision of the 1588 * result. 1589 * @return {@code [this.divideToIntegralValue(divisor), 1590 * this.remainder(divisor)]}. 1591 * @throws NullPointerException 1592 * if {@code divisor == null}. 1593 * @throws ArithmeticException 1594 * if {@code divisor == 0}. 1595 * @see #divideToIntegralValue 1596 * @see #remainder 1597 */ divideAndRemainder(BigDecimal divisor, MathContext mc)1598 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { 1599 BigDecimal quotAndRem[] = new BigDecimal[2]; 1600 1601 quotAndRem[0] = this.divideToIntegralValue(divisor, mc); 1602 quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) ); 1603 return quotAndRem; 1604 } 1605 1606 /** 1607 * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The 1608 * scale of the result is {@code n * this.scale()}. 1609 * 1610 * <p>{@code x.pow(0)} returns {@code 1}, even if {@code x == 0}. 1611 * 1612 * <p>Implementation Note: The implementation is based on the ANSI standard 1613 * X3.274-1996 algorithm. 1614 * 1615 * @throws ArithmeticException 1616 * if {@code n < 0} or {@code n > 999999999}. 1617 */ pow(int n)1618 public BigDecimal pow(int n) { 1619 if (n == 0) { 1620 return ONE; 1621 } 1622 if ((n < 0) || (n > 999999999)) { 1623 throw new ArithmeticException("Invalid operation"); 1624 } 1625 long newScale = scale * (long)n; 1626 // Let be: this = [u,s] so: this^n = [u^n, s*n] 1627 return isZero() ? zeroScaledBy(newScale) 1628 : new BigDecimal(getUnscaledValue().pow(n), safeLongToInt(newScale)); 1629 } 1630 1631 /** 1632 * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The 1633 * result is rounded according to the passed context {@code mc}. 1634 * 1635 * <p>Implementation Note: The implementation is based on the ANSI standard 1636 * X3.274-1996 algorithm. 1637 * 1638 * @param mc 1639 * rounding mode and precision for the result of this operation. 1640 * @throws ArithmeticException 1641 * if {@code n < 0} or {@code n > 999999999}. 1642 */ pow(int n, MathContext mc)1643 public BigDecimal pow(int n, MathContext mc) { 1644 // The ANSI standard X3.274-1996 algorithm 1645 int m = Math.abs(n); 1646 int mcPrecision = mc.getPrecision(); 1647 int elength = (int)Math.log10(m) + 1; // decimal digits in 'n' 1648 int oneBitMask; // mask of bits 1649 BigDecimal accum; // the single accumulator 1650 MathContext newPrecision = mc; // MathContext by default 1651 1652 // In particular cases, it reduces the problem to call the other 'pow()' 1653 if ((n == 0) || ((isZero()) && (n > 0))) { 1654 return pow(n); 1655 } 1656 if ((m > 999999999) || ((mcPrecision == 0) && (n < 0)) 1657 || ((mcPrecision > 0) && (elength > mcPrecision))) { 1658 throw new ArithmeticException("Invalid operation"); 1659 } 1660 if (mcPrecision > 0) { 1661 newPrecision = new MathContext( mcPrecision + elength + 1, 1662 mc.getRoundingMode()); 1663 } 1664 // The result is calculated as if 'n' were positive 1665 accum = round(newPrecision); 1666 oneBitMask = Integer.highestOneBit(m) >> 1; 1667 1668 while (oneBitMask > 0) { 1669 accum = accum.multiply(accum, newPrecision); 1670 if ((m & oneBitMask) == oneBitMask) { 1671 accum = accum.multiply(this, newPrecision); 1672 } 1673 oneBitMask >>= 1; 1674 } 1675 // If 'n' is negative, the value is divided into 'ONE' 1676 if (n < 0) { 1677 accum = ONE.divide(accum, newPrecision); 1678 } 1679 // The final value is rounded to the destination precision 1680 accum.inplaceRound(mc); 1681 return accum; 1682 } 1683 1684 /** 1685 * Returns a {@code BigDecimal} whose value is the absolute value of 1686 * {@code this}. The scale of the result is the same as the scale of this. 1687 */ abs()1688 public BigDecimal abs() { 1689 return ((signum() < 0) ? negate() : this); 1690 } 1691 1692 /** 1693 * Returns a {@code BigDecimal} whose value is the absolute value of 1694 * {@code this}. The result is rounded according to the passed context 1695 * {@code mc}. 1696 */ abs(MathContext mc)1697 public BigDecimal abs(MathContext mc) { 1698 BigDecimal result = (signum() < 0) ? negate() : new BigDecimal(getUnscaledValue(), scale); 1699 result.inplaceRound(mc); 1700 return result; 1701 } 1702 1703 /** 1704 * Returns a new {@code BigDecimal} whose value is the {@code -this}. The 1705 * scale of the result is the same as the scale of this. 1706 * 1707 * @return {@code -this} 1708 */ negate()1709 public BigDecimal negate() { 1710 if(bitLength < 63 || (bitLength == 63 && smallValue!=Long.MIN_VALUE)) { 1711 return valueOf(-smallValue,scale); 1712 } 1713 return new BigDecimal(getUnscaledValue().negate(), scale); 1714 } 1715 1716 /** 1717 * Returns a new {@code BigDecimal} whose value is the {@code -this}. The 1718 * result is rounded according to the passed context {@code mc}. 1719 * 1720 * @param mc 1721 * rounding mode and precision for the result of this operation. 1722 * @return {@code -this} 1723 */ negate(MathContext mc)1724 public BigDecimal negate(MathContext mc) { 1725 BigDecimal result = negate(); 1726 result.inplaceRound(mc); 1727 return result; 1728 } 1729 1730 /** 1731 * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale 1732 * of the result is the same as the scale of this. 1733 * 1734 * @return {@code this} 1735 */ plus()1736 public BigDecimal plus() { 1737 return this; 1738 } 1739 1740 /** 1741 * Returns a new {@code BigDecimal} whose value is {@code +this}. The result 1742 * is rounded according to the passed context {@code mc}. 1743 * 1744 * @param mc 1745 * rounding mode and precision for the result of this operation. 1746 * @return {@code this}, rounded 1747 */ plus(MathContext mc)1748 public BigDecimal plus(MathContext mc) { 1749 return round(mc); 1750 } 1751 1752 /** 1753 * Returns the sign of this {@code BigDecimal}. 1754 * 1755 * @return {@code -1} if {@code this < 0}, 1756 * {@code 0} if {@code this == 0}, 1757 * {@code 1} if {@code this > 0}. 1758 */ signum()1759 public int signum() { 1760 if( bitLength < 64) { 1761 return Long.signum( this.smallValue ); 1762 } 1763 return getUnscaledValue().signum(); 1764 } 1765 isZero()1766 private boolean isZero() { 1767 //Watch out: -1 has a bitLength=0 1768 return bitLength == 0 && this.smallValue != -1; 1769 } 1770 1771 /** 1772 * Returns the scale of this {@code BigDecimal}. The scale is the number of 1773 * digits behind the decimal point. The value of this {@code BigDecimal} is 1774 * the {@code unsignedValue * 10<sup>-scale</sup>}. If the scale is negative, 1775 * then this {@code BigDecimal} represents a big integer. 1776 * 1777 * @return the scale of this {@code BigDecimal}. 1778 */ scale()1779 public int scale() { 1780 return scale; 1781 } 1782 1783 /** 1784 * Returns the precision of this {@code BigDecimal}. The precision is the 1785 * number of decimal digits used to represent this decimal. It is equivalent 1786 * to the number of digits of the unscaled value. The precision of {@code 0} 1787 * is {@code 1} (independent of the scale). 1788 * 1789 * @return the precision of this {@code BigDecimal}. 1790 */ precision()1791 public int precision() { 1792 // Return the cached value if we have one. 1793 if (precision != 0) { 1794 return precision; 1795 } 1796 1797 if (bitLength == 0) { 1798 precision = 1; 1799 } else if (bitLength < 64) { 1800 precision = decimalDigitsInLong(smallValue); 1801 } else { 1802 int decimalDigits = 1 + (int) ((bitLength - 1) * LOG10_2); 1803 // If after division the number isn't zero, there exists an additional digit 1804 if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) { 1805 decimalDigits++; 1806 } 1807 precision = decimalDigits; 1808 } 1809 return precision; 1810 } 1811 decimalDigitsInLong(long value)1812 private int decimalDigitsInLong(long value) { 1813 if (value == Long.MIN_VALUE) { 1814 return 19; // special case required because abs(MIN_VALUE) == MIN_VALUE 1815 } else { 1816 int index = Arrays.binarySearch(MathUtils.LONG_POWERS_OF_TEN, Math.abs(value)); 1817 return (index < 0) ? (-index - 1) : (index + 1); 1818 } 1819 } 1820 1821 /** 1822 * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance 1823 * as a {@code BigInteger}. The unscaled value can be computed as 1824 * {@code this * 10<sup>scale</sup>}. 1825 */ unscaledValue()1826 public BigInteger unscaledValue() { 1827 return getUnscaledValue(); 1828 } 1829 1830 /** 1831 * Returns a new {@code BigDecimal} whose value is {@code this}, rounded 1832 * according to the passed context {@code mc}. 1833 * <p> 1834 * If {@code mc.precision = 0}, then no rounding is performed. 1835 * <p> 1836 * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY}, 1837 * then an {@code ArithmeticException} is thrown if the result cannot be 1838 * represented exactly within the given precision. 1839 * 1840 * @param mc 1841 * rounding mode and precision for the result of this operation. 1842 * @return {@code this} rounded according to the passed context. 1843 * @throws ArithmeticException 1844 * if {@code mc.precision > 0} and {@code mc.roundingMode == 1845 * UNNECESSARY} and this cannot be represented within the given 1846 * precision. 1847 */ round(MathContext mc)1848 public BigDecimal round(MathContext mc) { 1849 BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scale); 1850 1851 thisBD.inplaceRound(mc); 1852 return thisBD; 1853 } 1854 1855 /** 1856 * Returns a new {@code BigDecimal} instance with the specified scale. 1857 * <p> 1858 * If the new scale is greater than the old scale, then additional zeros are 1859 * added to the unscaled value. In this case no rounding is necessary. 1860 * <p> 1861 * If the new scale is smaller than the old scale, then trailing digits are 1862 * removed. If these trailing digits are not zero, then the remaining 1863 * unscaled value has to be rounded. For this rounding operation the 1864 * specified rounding mode is used. 1865 * 1866 * @param newScale 1867 * scale of the result returned. 1868 * @param roundingMode 1869 * rounding mode to be used to round the result. 1870 * @return a new {@code BigDecimal} instance with the specified scale. 1871 * @throws NullPointerException 1872 * if {@code roundingMode == null}. 1873 * @throws ArithmeticException 1874 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1875 * necessary according to the given scale. 1876 */ setScale(int newScale, RoundingMode roundingMode)1877 public BigDecimal setScale(int newScale, RoundingMode roundingMode) { 1878 if (roundingMode == null) { 1879 throw new NullPointerException("roundingMode == null"); 1880 } 1881 long diffScale = newScale - (long)scale; 1882 // Let be: 'this' = [u,s] 1883 if(diffScale == 0) { 1884 return this; 1885 } 1886 if(diffScale > 0) { 1887 // return [u * 10^(s2 - s), newScale] 1888 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1889 (this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale]) < 64 ) { 1890 return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],newScale); 1891 } 1892 return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale); 1893 } 1894 // diffScale < 0 1895 // return [u,s] / [1,newScale] with the appropriate scale and rounding 1896 if(this.bitLength < 64 && -diffScale < MathUtils.LONG_POWERS_OF_TEN.length) { 1897 return dividePrimitiveLongs(this.smallValue, MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], newScale,roundingMode); 1898 } 1899 return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode); 1900 } 1901 1902 /** 1903 * Returns a new {@code BigDecimal} instance with the specified scale. 1904 * <p> 1905 * If the new scale is greater than the old scale, then additional zeros are 1906 * added to the unscaled value. In this case no rounding is necessary. 1907 * <p> 1908 * If the new scale is smaller than the old scale, then trailing digits are 1909 * removed. If these trailing digits are not zero, then the remaining 1910 * unscaled value has to be rounded. For this rounding operation the 1911 * specified rounding mode is used. 1912 * 1913 * @param newScale 1914 * scale of the result returned. 1915 * @param roundingMode 1916 * rounding mode to be used to round the result. 1917 * @return a new {@code BigDecimal} instance with the specified scale. 1918 * @throws IllegalArgumentException 1919 * if {@code roundingMode} is not a valid rounding mode. 1920 * @throws ArithmeticException 1921 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1922 * necessary according to the given scale. 1923 */ setScale(int newScale, int roundingMode)1924 public BigDecimal setScale(int newScale, int roundingMode) { 1925 return setScale(newScale, RoundingMode.valueOf(roundingMode)); 1926 } 1927 1928 /** 1929 * Returns a new {@code BigDecimal} instance with the specified scale. If 1930 * the new scale is greater than the old scale, then additional zeros are 1931 * added to the unscaled value. If the new scale is smaller than the old 1932 * scale, then trailing zeros are removed. If the trailing digits are not 1933 * zeros then an ArithmeticException is thrown. 1934 * <p> 1935 * If no exception is thrown, then the following equation holds: {@code 1936 * x.setScale(s).compareTo(x) == 0}. 1937 * 1938 * @param newScale 1939 * scale of the result returned. 1940 * @return a new {@code BigDecimal} instance with the specified scale. 1941 * @throws ArithmeticException 1942 * if rounding would be necessary. 1943 */ setScale(int newScale)1944 public BigDecimal setScale(int newScale) { 1945 return setScale(newScale, RoundingMode.UNNECESSARY); 1946 } 1947 1948 /** 1949 * Returns a new {@code BigDecimal} instance where the decimal point has 1950 * been moved {@code n} places to the left. If {@code n < 0} then the 1951 * decimal point is moved {@code -n} places to the right. 1952 * 1953 * <p>The result is obtained by changing its scale. If the scale of the result 1954 * becomes negative, then its precision is increased such that the scale is 1955 * zero. 1956 * 1957 * <p>Note, that {@code movePointLeft(0)} returns a result which is 1958 * mathematically equivalent, but which has {@code scale >= 0}. 1959 */ movePointLeft(int n)1960 public BigDecimal movePointLeft(int n) { 1961 return movePoint(scale + (long)n); 1962 } 1963 movePoint(long newScale)1964 private BigDecimal movePoint(long newScale) { 1965 if (isZero()) { 1966 return zeroScaledBy(Math.max(newScale, 0)); 1967 } 1968 /* 1969 * When: 'n'== Integer.MIN_VALUE isn't possible to call to 1970 * movePointRight(-n) since -Integer.MIN_VALUE == Integer.MIN_VALUE 1971 */ 1972 if(newScale >= 0) { 1973 if(bitLength < 64) { 1974 return valueOf(smallValue, safeLongToInt(newScale)); 1975 } 1976 return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale)); 1977 } 1978 if(-newScale < MathUtils.LONG_POWERS_OF_TEN.length && 1979 bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-newScale] < 64 ) { 1980 return valueOf(smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-newScale],0); 1981 } 1982 return new BigDecimal(Multiplication.multiplyByTenPow( 1983 getUnscaledValue(), safeLongToInt(-newScale)), 0); 1984 } 1985 1986 /** 1987 * Returns a new {@code BigDecimal} instance where the decimal point has 1988 * been moved {@code n} places to the right. If {@code n < 0} then the 1989 * decimal point is moved {@code -n} places to the left. 1990 * 1991 * <p>The result is obtained by changing its scale. If the scale of the result 1992 * becomes negative, then its precision is increased such that the scale is 1993 * zero. 1994 * 1995 * <p>Note, that {@code movePointRight(0)} returns a result which is 1996 * mathematically equivalent, but which has scale >= 0. 1997 */ movePointRight(int n)1998 public BigDecimal movePointRight(int n) { 1999 return movePoint(scale - (long)n); 2000 } 2001 2002 /** 2003 * Returns a new {@code BigDecimal} whose value is {@code this * 10<sup>n</sup>}. 2004 * The scale of the result is {@code this.scale()} - {@code n}. 2005 * The precision of the result is the precision of {@code this}. 2006 * 2007 * <p>This method has the same effect as {@link #movePointRight}, except that 2008 * the precision is not changed. 2009 */ scaleByPowerOfTen(int n)2010 public BigDecimal scaleByPowerOfTen(int n) { 2011 long newScale = scale - (long)n; 2012 if(bitLength < 64) { 2013 //Taking care when a 0 is to be scaled 2014 if( smallValue==0 ){ 2015 return zeroScaledBy( newScale ); 2016 } 2017 return valueOf(smallValue, safeLongToInt(newScale)); 2018 } 2019 return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale)); 2020 } 2021 2022 /** 2023 * Returns a new {@code BigDecimal} instance with the same value as {@code 2024 * this} but with a unscaled value where the trailing zeros have been 2025 * removed. If the unscaled value of {@code this} has n trailing zeros, then 2026 * the scale and the precision of the result has been reduced by n. 2027 * 2028 * @return a new {@code BigDecimal} instance equivalent to this where the 2029 * trailing zeros of the unscaled value have been removed. 2030 */ stripTrailingZeros()2031 public BigDecimal stripTrailingZeros() { 2032 int i = 1; // 1 <= i <= 18 2033 int lastPow = TEN_POW.length - 1; 2034 long newScale = scale; 2035 2036 if (isZero()) { 2037 // Preserve RI compatibility, so BigDecimal.equals (which checks 2038 // value *and* scale) continues to work. 2039 return this; 2040 } 2041 BigInteger strippedBI = getUnscaledValue(); 2042 BigInteger[] quotAndRem; 2043 2044 // while the number is even... 2045 while (!strippedBI.testBit(0)) { 2046 // To divide by 10^i 2047 quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]); 2048 // To look the remainder 2049 if (quotAndRem[1].signum() == 0) { 2050 // To adjust the scale 2051 newScale -= i; 2052 if (i < lastPow) { 2053 // To set to the next power 2054 i++; 2055 } 2056 strippedBI = quotAndRem[0]; 2057 } else { 2058 if (i == 1) { 2059 // 'this' has no more trailing zeros 2060 break; 2061 } 2062 // To set to the smallest power of ten 2063 i = 1; 2064 } 2065 } 2066 return new BigDecimal(strippedBI, safeLongToInt(newScale)); 2067 } 2068 2069 /** 2070 * Compares this {@code BigDecimal} with {@code val}. Returns one of the 2071 * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as 2072 * if {@code this.subtract(val)} is computed. If this difference is > 0 then 2073 * 1 is returned, if the difference is < 0 then -1 is returned, and if the 2074 * difference is 0 then 0 is returned. This means, that if two decimal 2075 * instances are compared which are equal in value but differ in scale, then 2076 * these two instances are considered as equal. 2077 * 2078 * @param val 2079 * value to be compared with {@code this}. 2080 * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val}, 2081 * {@code 0} if {@code this == val}. 2082 * @throws NullPointerException 2083 * if {@code val == null}. 2084 */ compareTo(BigDecimal val)2085 public int compareTo(BigDecimal val) { 2086 int thisSign = signum(); 2087 int valueSign = val.signum(); 2088 2089 if( thisSign == valueSign) { 2090 if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) { 2091 return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0; 2092 } 2093 long diffScale = (long)this.scale - val.scale; 2094 int diffPrecision = this.approxPrecision() - val.approxPrecision(); 2095 if (diffPrecision > diffScale + 1) { 2096 return thisSign; 2097 } else if (diffPrecision < diffScale - 1) { 2098 return -thisSign; 2099 } else {// thisSign == val.signum() and diffPrecision is aprox. diffScale 2100 BigInteger thisUnscaled = this.getUnscaledValue(); 2101 BigInteger valUnscaled = val.getUnscaledValue(); 2102 // If any of both precision is bigger, append zeros to the shorter one 2103 if (diffScale < 0) { 2104 thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale)); 2105 } else if (diffScale > 0) { 2106 valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale)); 2107 } 2108 return thisUnscaled.compareTo(valUnscaled); 2109 } 2110 } else if (thisSign < valueSign) { 2111 return -1; 2112 } else { 2113 return 1; 2114 } 2115 } 2116 2117 /** 2118 * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if 2119 * this instance is equal to this big decimal. Two big decimals are equal if 2120 * their unscaled value and their scale is equal. For example, 1.0 2121 * (10*10<sup>-1</sup>) is not equal to 1.00 (100*10<sup>-2</sup>). Similarly, zero 2122 * instances are not equal if their scale differs. 2123 */ 2124 @Override equals(Object x)2125 public boolean equals(Object x) { 2126 if (this == x) { 2127 return true; 2128 } 2129 if (x instanceof BigDecimal) { 2130 BigDecimal x1 = (BigDecimal) x; 2131 return x1.scale == scale 2132 && x1.bitLength == bitLength 2133 && (bitLength < 64 ? (x1.smallValue == smallValue) : x1.intVal.equals(intVal)); 2134 } 2135 return false; 2136 } 2137 2138 /** 2139 * Returns the minimum of this {@code BigDecimal} and {@code val}. 2140 * 2141 * @param val 2142 * value to be used to compute the minimum with this. 2143 * @return {@code min(this, val}. 2144 * @throws NullPointerException 2145 * if {@code val == null}. 2146 */ min(BigDecimal val)2147 public BigDecimal min(BigDecimal val) { 2148 return ((compareTo(val) <= 0) ? this : val); 2149 } 2150 2151 /** 2152 * Returns the maximum of this {@code BigDecimal} and {@code val}. 2153 * 2154 * @param val 2155 * value to be used to compute the maximum with this. 2156 * @return {@code max(this, val}. 2157 * @throws NullPointerException 2158 * if {@code val == null}. 2159 */ max(BigDecimal val)2160 public BigDecimal max(BigDecimal val) { 2161 return ((compareTo(val) >= 0) ? this : val); 2162 } 2163 2164 /** 2165 * Returns a hash code for this {@code BigDecimal}. 2166 * 2167 * @return hash code for {@code this}. 2168 */ 2169 @Override hashCode()2170 public int hashCode() { 2171 if (hashCode != 0) { 2172 return hashCode; 2173 } 2174 if (bitLength < 64) { 2175 hashCode = (int)(smallValue & 0xffffffff); 2176 hashCode = 33 * hashCode + (int)((smallValue >> 32) & 0xffffffff); 2177 hashCode = 17 * hashCode + scale; 2178 return hashCode; 2179 } 2180 hashCode = 17 * intVal.hashCode() + scale; 2181 return hashCode; 2182 } 2183 2184 /** 2185 * Returns a canonical string representation of this {@code BigDecimal}. If 2186 * necessary, scientific notation is used. This representation always prints 2187 * all significant digits of this value. 2188 * <p> 2189 * If the scale is negative or if {@code scale - precision >= 6} then 2190 * scientific notation is used. 2191 * 2192 * @return a string representation of {@code this} in scientific notation if 2193 * necessary. 2194 */ 2195 @Override toString()2196 public String toString() { 2197 if (toStringImage != null) { 2198 return toStringImage; 2199 } 2200 if(bitLength < 32) { 2201 toStringImage = Conversion.toDecimalScaledString(smallValue,scale); 2202 return toStringImage; 2203 } 2204 String intString = getUnscaledValue().toString(); 2205 if (scale == 0) { 2206 return intString; 2207 } 2208 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2209 int end = intString.length(); 2210 long exponent = -(long)scale + end - begin; 2211 StringBuilder result = new StringBuilder(); 2212 2213 result.append(intString); 2214 if ((scale > 0) && (exponent >= -6)) { 2215 if (exponent >= 0) { 2216 result.insert(end - scale, '.'); 2217 } else { 2218 result.insert(begin - 1, "0."); 2219 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2220 } 2221 } else { 2222 if (end - begin >= 1) { 2223 result.insert(begin, '.'); 2224 end++; 2225 } 2226 result.insert(end, 'E'); 2227 if (exponent > 0) { 2228 result.insert(++end, '+'); 2229 } 2230 result.insert(++end, Long.toString(exponent)); 2231 } 2232 toStringImage = result.toString(); 2233 return toStringImage; 2234 } 2235 2236 /** 2237 * Returns a string representation of this {@code BigDecimal}. This 2238 * representation always prints all significant digits of this value. 2239 * <p> 2240 * If the scale is negative or if {@code scale - precision >= 6} then 2241 * engineering notation is used. Engineering notation is similar to the 2242 * scientific notation except that the exponent is made to be a multiple of 2243 * 3 such that the integer part is >= 1 and < 1000. 2244 * 2245 * @return a string representation of {@code this} in engineering notation 2246 * if necessary. 2247 */ toEngineeringString()2248 public String toEngineeringString() { 2249 String intString = getUnscaledValue().toString(); 2250 if (scale == 0) { 2251 return intString; 2252 } 2253 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2254 int end = intString.length(); 2255 long exponent = -(long)scale + end - begin; 2256 StringBuilder result = new StringBuilder(intString); 2257 2258 if ((scale > 0) && (exponent >= -6)) { 2259 if (exponent >= 0) { 2260 result.insert(end - scale, '.'); 2261 } else { 2262 result.insert(begin - 1, "0."); 2263 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2264 } 2265 } else { 2266 int delta = end - begin; 2267 int rem = (int)(exponent % 3); 2268 2269 if (rem != 0) { 2270 // adjust exponent so it is a multiple of three 2271 if (getUnscaledValue().signum() == 0) { 2272 // zero value 2273 rem = (rem < 0) ? -rem : 3 - rem; 2274 exponent += rem; 2275 } else { 2276 // nonzero value 2277 rem = (rem < 0) ? rem + 3 : rem; 2278 exponent -= rem; 2279 begin += rem; 2280 } 2281 if (delta < 3) { 2282 for (int i = rem - delta; i > 0; i--) { 2283 result.insert(end++, '0'); 2284 } 2285 } 2286 } 2287 if (end - begin >= 1) { 2288 result.insert(begin, '.'); 2289 end++; 2290 } 2291 if (exponent != 0) { 2292 result.insert(end, 'E'); 2293 if (exponent > 0) { 2294 result.insert(++end, '+'); 2295 } 2296 result.insert(++end, Long.toString(exponent)); 2297 } 2298 } 2299 return result.toString(); 2300 } 2301 2302 /** 2303 * Returns a string representation of this {@code BigDecimal}. No scientific 2304 * notation is used. This methods adds zeros where necessary. 2305 * <p> 2306 * If this string representation is used to create a new instance, this 2307 * instance is generally not identical to {@code this} as the precision 2308 * changes. 2309 * <p> 2310 * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns 2311 * {@code false}. 2312 * <p> 2313 * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}. 2314 * 2315 * @return a string representation of {@code this} without exponent part. 2316 */ toPlainString()2317 public String toPlainString() { 2318 String intStr = getUnscaledValue().toString(); 2319 if ((scale == 0) || ((isZero()) && (scale < 0))) { 2320 return intStr; 2321 } 2322 int begin = (signum() < 0) ? 1 : 0; 2323 int delta = scale; 2324 // We take space for all digits, plus a possible decimal point, plus 'scale' 2325 StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale)); 2326 2327 if (begin == 1) { 2328 // If the number is negative, we insert a '-' character at front 2329 result.append('-'); 2330 } 2331 if (scale > 0) { 2332 delta -= (intStr.length() - begin); 2333 if (delta >= 0) { 2334 result.append("0."); 2335 // To append zeros after the decimal point 2336 for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) { 2337 result.append(CH_ZEROS); 2338 } 2339 result.append(CH_ZEROS, 0, delta); 2340 result.append(intStr.substring(begin)); 2341 } else { 2342 delta = begin - delta; 2343 result.append(intStr.substring(begin, delta)); 2344 result.append('.'); 2345 result.append(intStr.substring(delta)); 2346 } 2347 } else {// (scale <= 0) 2348 result.append(intStr.substring(begin)); 2349 // To append trailing zeros 2350 for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) { 2351 result.append(CH_ZEROS); 2352 } 2353 result.append(CH_ZEROS, 0, -delta); 2354 } 2355 return result.toString(); 2356 } 2357 2358 /** 2359 * Returns this {@code BigDecimal} as a big integer instance. A fractional 2360 * part is discarded. 2361 * 2362 * @return this {@code BigDecimal} as a big integer instance. 2363 */ toBigInteger()2364 public BigInteger toBigInteger() { 2365 if ((scale == 0) || (isZero())) { 2366 return getUnscaledValue(); 2367 } else if (scale < 0) { 2368 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2369 } else {// (scale > 0) 2370 return getUnscaledValue().divide(Multiplication.powerOf10(scale)); 2371 } 2372 } 2373 2374 /** 2375 * Returns this {@code BigDecimal} as a big integer instance if it has no 2376 * fractional part. If this {@code BigDecimal} has a fractional part, i.e. 2377 * if rounding would be necessary, an {@code ArithmeticException} is thrown. 2378 * 2379 * @return this {@code BigDecimal} as a big integer value. 2380 * @throws ArithmeticException 2381 * if rounding is necessary. 2382 */ toBigIntegerExact()2383 public BigInteger toBigIntegerExact() { 2384 if ((scale == 0) || (isZero())) { 2385 return getUnscaledValue(); 2386 } else if (scale < 0) { 2387 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2388 } else {// (scale > 0) 2389 BigInteger[] integerAndFraction; 2390 // An optimization before do a heavy division 2391 if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) { 2392 throw new ArithmeticException("Rounding necessary"); 2393 } 2394 integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale)); 2395 if (integerAndFraction[1].signum() != 0) { 2396 // It exists a non-zero fractional part 2397 throw new ArithmeticException("Rounding necessary"); 2398 } 2399 return integerAndFraction[0]; 2400 } 2401 } 2402 2403 /** 2404 * Returns this {@code BigDecimal} as an long value. Any fractional part is 2405 * discarded. If the integral part of {@code this} is too big to be 2406 * represented as an long, then {@code this % 2<sup>64</sup>} is returned. 2407 */ 2408 @Override longValue()2409 public long longValue() { 2410 /* 2411 * If scale <= -64 there are at least 64 trailing bits zero in 2412 * 10^(-scale). If the scale is positive and very large the long value 2413 * could be zero. 2414 */ 2415 return ((scale <= -64) || (scale > approxPrecision()) ? 0L : toBigInteger().longValue()); 2416 } 2417 2418 /** 2419 * Returns this {@code BigDecimal} as a long value if it has no fractional 2420 * part and if its value fits to the int range ([-2<sup>63</sup>..2<sup>63</sup>-1]). If 2421 * these conditions are not met, an {@code ArithmeticException} is thrown. 2422 * 2423 * @throws ArithmeticException 2424 * if rounding is necessary or the number doesn't fit in a long. 2425 */ longValueExact()2426 public long longValueExact() { 2427 return valueExact(64); 2428 } 2429 2430 /** 2431 * Returns this {@code BigDecimal} as an int value. Any fractional part is 2432 * discarded. If the integral part of {@code this} is too big to be 2433 * represented as an int, then {@code this % 2<sup>32</sup>} is returned. 2434 */ 2435 @Override intValue()2436 public int intValue() { 2437 /* 2438 * If scale <= -32 there are at least 32 trailing bits zero in 2439 * 10^(-scale). If the scale is positive and very large the long value 2440 * could be zero. 2441 */ 2442 return ((scale <= -32) || (scale > approxPrecision()) ? 0 : toBigInteger().intValue()); 2443 } 2444 2445 /** 2446 * Returns this {@code BigDecimal} as a int value if it has no fractional 2447 * part and if its value fits to the int range ([-2<sup>31</sup>..2<sup>31</sup>-1]). If 2448 * these conditions are not met, an {@code ArithmeticException} is thrown. 2449 * 2450 * @throws ArithmeticException 2451 * if rounding is necessary or the number doesn't fit in an int. 2452 */ intValueExact()2453 public int intValueExact() { 2454 return (int) valueExact(32); 2455 } 2456 2457 /** 2458 * Returns this {@code BigDecimal} as a short value if it has no fractional 2459 * part and if its value fits to the short range ([-2<sup>15</sup>..2<sup>15</sup>-1]). If 2460 * these conditions are not met, an {@code ArithmeticException} is thrown. 2461 * 2462 * @throws ArithmeticException 2463 * if rounding is necessary of the number doesn't fit in a short. 2464 */ shortValueExact()2465 public short shortValueExact() { 2466 return (short) valueExact(16); 2467 } 2468 2469 /** 2470 * Returns this {@code BigDecimal} as a byte value if it has no fractional 2471 * part and if its value fits to the byte range ([-128..127]). If these 2472 * conditions are not met, an {@code ArithmeticException} is thrown. 2473 * 2474 * @throws ArithmeticException 2475 * if rounding is necessary or the number doesn't fit in a byte. 2476 */ byteValueExact()2477 public byte byteValueExact() { 2478 return (byte) valueExact(8); 2479 } 2480 2481 /** 2482 * Returns this {@code BigDecimal} as a float value. If {@code this} is too 2483 * big to be represented as an float, then {@code Float.POSITIVE_INFINITY} 2484 * or {@code Float.NEGATIVE_INFINITY} is returned. 2485 * <p> 2486 * Note, that if the unscaled value has more than 24 significant digits, 2487 * then this decimal cannot be represented exactly in a float variable. In 2488 * this case the result is rounded. 2489 * <p> 2490 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2491 * represented exactly as a float, and thus {@code x1.equals(new 2492 * BigDecimal(x1.floatValue())} returns {@code false} for this case. 2493 * <p> 2494 * Similarly, if the instance {@code new BigDecimal(16777217)} is converted 2495 * to a float, the result is {@code 1.6777216E}7. 2496 * 2497 * @return this {@code BigDecimal} as a float value. 2498 */ 2499 @Override floatValue()2500 public float floatValue() { 2501 /* A similar code like in doubleValue() could be repeated here, 2502 * but this simple implementation is quite efficient. */ 2503 float floatResult = signum(); 2504 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2505 if ((powerOfTwo < -149) || (floatResult == 0.0f)) { 2506 // Cases which 'this' is very small 2507 floatResult *= 0.0f; 2508 } else if (powerOfTwo > 129) { 2509 // Cases which 'this' is very large 2510 floatResult *= Float.POSITIVE_INFINITY; 2511 } else { 2512 floatResult = (float)doubleValue(); 2513 } 2514 return floatResult; 2515 } 2516 2517 /** 2518 * Returns this {@code BigDecimal} as a double value. If {@code this} is too 2519 * big to be represented as an float, then {@code Double.POSITIVE_INFINITY} 2520 * or {@code Double.NEGATIVE_INFINITY} is returned. 2521 * <p> 2522 * Note, that if the unscaled value has more than 53 significant digits, 2523 * then this decimal cannot be represented exactly in a double variable. In 2524 * this case the result is rounded. 2525 * <p> 2526 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2527 * represented exactly as a double, and thus {@code x1.equals(new 2528 * BigDecimal(x1.doubleValue())} returns {@code false} for this case. 2529 * <p> 2530 * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is 2531 * converted to a double, the result is {@code 9.007199254740992E15}. 2532 * <p> 2533 * 2534 * @return this {@code BigDecimal} as a double value. 2535 */ 2536 @Override doubleValue()2537 public double doubleValue() { 2538 int sign = signum(); 2539 int exponent = 1076; // bias + 53 2540 int lowestSetBit; 2541 int discardedSize; 2542 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2543 long bits; // IEEE-754 Standard 2544 long tempBits; // for temporal calculations 2545 BigInteger mantissa; 2546 2547 if ((powerOfTwo < -1074) || (sign == 0)) { 2548 // Cases which 'this' is very small 2549 return (sign * 0.0d); 2550 } else if (powerOfTwo > 1025) { 2551 // Cases which 'this' is very large 2552 return (sign * Double.POSITIVE_INFINITY); 2553 } 2554 mantissa = getUnscaledValue().abs(); 2555 // Let be: this = [u,s], with s > 0 2556 if (scale <= 0) { 2557 // mantissa = abs(u) * 10^s 2558 mantissa = mantissa.multiply(Multiplication.powerOf10(-scale)); 2559 } else {// (scale > 0) 2560 BigInteger quotAndRem[]; 2561 BigInteger powerOfTen = Multiplication.powerOf10(scale); 2562 int k = 100 - (int)powerOfTwo; 2563 int compRem; 2564 2565 if (k > 0) { 2566 /* Computing (mantissa * 2^k) , where 'k' is a enough big 2567 * power of '2' to can divide by 10^s */ 2568 mantissa = mantissa.shiftLeft(k); 2569 exponent -= k; 2570 } 2571 // Computing (mantissa * 2^k) / 10^s 2572 quotAndRem = mantissa.divideAndRemainder(powerOfTen); 2573 // To check if the fractional part >= 0.5 2574 compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen); 2575 // To add two rounded bits at end of mantissa 2576 mantissa = quotAndRem[0].shiftLeft(2).add( 2577 BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1)); 2578 exponent -= 2; 2579 } 2580 lowestSetBit = mantissa.getLowestSetBit(); 2581 discardedSize = mantissa.bitLength() - 54; 2582 if (discardedSize > 0) {// (n > 54) 2583 // mantissa = (abs(u) * 10^s) >> (n - 54) 2584 bits = mantissa.shiftRight(discardedSize).longValue(); 2585 tempBits = bits; 2586 // #bits = 54, to check if the discarded fraction produces a carry 2587 if ((((bits & 1) == 1) && (lowestSetBit < discardedSize)) 2588 || ((bits & 3) == 3)) { 2589 bits += 2; 2590 } 2591 } else {// (n <= 54) 2592 // mantissa = (abs(u) * 10^s) << (54 - n) 2593 bits = mantissa.longValue() << -discardedSize; 2594 tempBits = bits; 2595 // #bits = 54, to check if the discarded fraction produces a carry: 2596 if ((bits & 3) == 3) { 2597 bits += 2; 2598 } 2599 } 2600 // Testing bit 54 to check if the carry creates a new binary digit 2601 if ((bits & 0x40000000000000L) == 0) { 2602 // To drop the last bit of mantissa (first discarded) 2603 bits >>= 1; 2604 // exponent = 2^(s-n+53+bias) 2605 exponent += discardedSize; 2606 } else {// #bits = 54 2607 bits >>= 2; 2608 exponent += discardedSize + 1; 2609 } 2610 // To test if the 53-bits number fits in 'double' 2611 if (exponent > 2046) {// (exponent - bias > 1023) 2612 return (sign * Double.POSITIVE_INFINITY); 2613 } else if (exponent <= 0) {// (exponent - bias <= -1023) 2614 // Denormalized numbers (having exponent == 0) 2615 if (exponent < -53) {// exponent - bias < -1076 2616 return (sign * 0.0d); 2617 } 2618 // -1076 <= exponent - bias <= -1023 2619 // To discard '- exponent + 1' bits 2620 bits = tempBits >> 1; 2621 tempBits = bits & (-1L >>> (63 + exponent)); 2622 bits >>= (-exponent ); 2623 // To test if after discard bits, a new carry is generated 2624 if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0) 2625 && (lowestSetBit < discardedSize))) { 2626 bits += 1; 2627 } 2628 exponent = 0; 2629 bits >>= 1; 2630 } 2631 // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)] 2632 bits = (sign & 0x8000000000000000L) | ((long)exponent << 52) 2633 | (bits & 0xFFFFFFFFFFFFFL); 2634 return Double.longBitsToDouble(bits); 2635 } 2636 2637 /** 2638 * Returns the unit in the last place (ULP) of this {@code BigDecimal} 2639 * instance. An ULP is the distance to the nearest big decimal with the same 2640 * precision. 2641 * 2642 * <p>The amount of a rounding error in the evaluation of a floating-point 2643 * operation is often expressed in ULPs. An error of 1 ULP is often seen as 2644 * a tolerable error. 2645 * 2646 * <p>For class {@code BigDecimal}, the ULP of a number is simply 10<sup>-scale</sup>. 2647 * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}. 2648 * 2649 * @return unit in the last place (ULP) of this {@code BigDecimal} instance. 2650 */ ulp()2651 public BigDecimal ulp() { 2652 return valueOf(1, scale); 2653 } 2654 2655 /* Private Methods */ 2656 2657 /** 2658 * It does all rounding work of the public method 2659 * {@code round(MathContext)}, performing an inplace rounding 2660 * without creating a new object. 2661 * 2662 * @param mc 2663 * the {@code MathContext} for perform the rounding. 2664 * @see #round(MathContext) 2665 */ inplaceRound(MathContext mc)2666 private void inplaceRound(MathContext mc) { 2667 int mcPrecision = mc.getPrecision(); 2668 if (approxPrecision() < mcPrecision || mcPrecision == 0) { 2669 return; 2670 } 2671 int discardedPrecision = precision() - mcPrecision; 2672 // If no rounding is necessary it returns immediately 2673 if ((discardedPrecision <= 0)) { 2674 return; 2675 } 2676 // When the number is small perform an efficient rounding 2677 if (this.bitLength < 64) { 2678 smallRound(mc, discardedPrecision); 2679 return; 2680 } 2681 // Getting the integer part and the discarded fraction 2682 BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision); 2683 BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction); 2684 long newScale = (long)scale - discardedPrecision; 2685 int compRem; 2686 BigDecimal tempBD; 2687 // If the discarded fraction is non-zero, perform rounding 2688 if (integerAndFraction[1].signum() != 0) { 2689 // To check if the discarded fraction >= 0.5 2690 compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction)); 2691 // To look if there is a carry 2692 compRem = roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0, 2693 integerAndFraction[1].signum() * (5 + compRem), 2694 mc.getRoundingMode()); 2695 if (compRem != 0) { 2696 integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem)); 2697 } 2698 tempBD = new BigDecimal(integerAndFraction[0]); 2699 // If after to add the increment the precision changed, we normalize the size 2700 if (tempBD.precision() > mcPrecision) { 2701 integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN); 2702 newScale--; 2703 } 2704 } 2705 // To update all internal fields 2706 scale = safeLongToInt(newScale); 2707 precision = mcPrecision; 2708 setUnscaledValue(integerAndFraction[0]); 2709 } 2710 2711 /** 2712 * Returns -1, 0, and 1 if {@code value1 < value2}, {@code value1 == value2}, 2713 * and {@code value1 > value2}, respectively, when comparing without regard 2714 * to the values' sign. 2715 * 2716 * <p>Note that this implementation deals correctly with Long.MIN_VALUE, 2717 * whose absolute magnitude is larger than any other {@code long} value. 2718 */ compareAbsoluteValues(long value1, long value2)2719 private static int compareAbsoluteValues(long value1, long value2) { 2720 // Map long values to the range -1 .. Long.MAX_VALUE so that comparison 2721 // of absolute magnitude can be done using regular long arithmetics. 2722 // This deals correctly with Long.MIN_VALUE, whose absolute magnitude 2723 // is larger than any other long value, and which is mapped to 2724 // Long.MAX_VALUE here. 2725 // Values that only differ by sign get mapped to the same value, for 2726 // example both +3 and -3 get mapped to +2. 2727 value1 = Math.abs(value1) - 1; 2728 value2 = Math.abs(value2) - 1; 2729 // Unlike Long.compare(), we guarantee to return specifically -1 and +1 2730 return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0); 2731 } 2732 2733 /** 2734 * Compares {@code n} against {@code 0.5 * d} in absolute terms (ignoring sign) 2735 * and with arithmetics that are safe against overflow or loss of precision. 2736 * Returns -1 if {@code n} is less than {@code 0.5 * d}, 0 if {@code n == 0.5 * d}, 2737 * or +1 if {@code n > 0.5 * d} when comparing the absolute values under such 2738 * arithmetics. 2739 */ compareForRounding(long n, long d)2740 private static int compareForRounding(long n, long d) { 2741 long halfD = d / 2; // rounds towards 0 2742 if (n == halfD || n == -halfD) { 2743 // In absolute terms: Because n == halfD, we know that 2 * n + lsb == d 2744 // for some lsb value 0 or 1. This means that n == d/2 (result 0) if 2745 // lsb is 0, or n < d/2 (result -1) if lsb is 1. In either case, the 2746 // result is -lsb. 2747 // Since we're calculating in absolute terms, we need the absolute lsb 2748 // (d & 1) as opposed to the signed lsb (d % 2) which would be -1 for 2749 // negative odd values of d. 2750 int lsb = (int) d & 1; 2751 return -lsb; // returns 0 or -1 2752 } else { 2753 // In absolute terms, either 2 * n + 1 < d (in the case of n < halfD), 2754 // or 2 * n > d (in the case of n > halfD). 2755 // In either case, comparing n against halfD gets the right result 2756 // -1 or +1, respectively. 2757 return compareAbsoluteValues(n, halfD); 2758 } 2759 } 2760 2761 /** 2762 * This method implements an efficient rounding for numbers which unscaled 2763 * value fits in the type {@code long}. 2764 * 2765 * @param mc 2766 * the context to use 2767 * @param discardedPrecision 2768 * the number of decimal digits that are discarded 2769 * @see #round(MathContext) 2770 */ smallRound(MathContext mc, int discardedPrecision)2771 private void smallRound(MathContext mc, int discardedPrecision) { 2772 long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision]; 2773 long newScale = (long)scale - discardedPrecision; 2774 long unscaledVal = smallValue; 2775 // Getting the integer part and the discarded fraction 2776 long integer = unscaledVal / sizeOfFraction; 2777 long fraction = unscaledVal % sizeOfFraction; 2778 int compRem; 2779 // If the discarded fraction is non-zero perform rounding 2780 if (fraction != 0) { 2781 // To check if the discarded fraction >= 0.5 2782 compRem = compareForRounding(fraction, sizeOfFraction); 2783 // To look if there is a carry 2784 integer += roundingBehavior( ((int)integer) & 1, 2785 Long.signum(fraction) * (5 + compRem), 2786 mc.getRoundingMode()); 2787 // If after to add the increment the precision changed, we normalize the size 2788 if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) { 2789 integer /= 10; 2790 newScale--; 2791 } 2792 } 2793 // To update all internal fields 2794 scale = safeLongToInt(newScale); 2795 precision = mc.getPrecision(); 2796 smallValue = integer; 2797 bitLength = bitLength(integer); 2798 intVal = null; 2799 } 2800 2801 /** 2802 * Return an increment that can be -1,0 or 1, depending of 2803 * {@code roundingMode}. 2804 * 2805 * @param parityBit 2806 * can be 0 or 1, it's only used in the case 2807 * {@code HALF_EVEN} 2808 * @param fraction 2809 * the mantissa to be analyzed 2810 * @param roundingMode 2811 * the type of rounding 2812 * @return the carry propagated after rounding 2813 */ roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode)2814 private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) { 2815 int increment = 0; // the carry after rounding 2816 2817 switch (roundingMode) { 2818 case UNNECESSARY: 2819 if (fraction != 0) { 2820 throw new ArithmeticException("Rounding necessary"); 2821 } 2822 break; 2823 case UP: 2824 increment = Integer.signum(fraction); 2825 break; 2826 case DOWN: 2827 break; 2828 case CEILING: 2829 increment = Math.max(Integer.signum(fraction), 0); 2830 break; 2831 case FLOOR: 2832 increment = Math.min(Integer.signum(fraction), 0); 2833 break; 2834 case HALF_UP: 2835 if (Math.abs(fraction) >= 5) { 2836 increment = Integer.signum(fraction); 2837 } 2838 break; 2839 case HALF_DOWN: 2840 if (Math.abs(fraction) > 5) { 2841 increment = Integer.signum(fraction); 2842 } 2843 break; 2844 case HALF_EVEN: 2845 if (Math.abs(fraction) + parityBit > 5) { 2846 increment = Integer.signum(fraction); 2847 } 2848 break; 2849 } 2850 return increment; 2851 } 2852 2853 /** 2854 * If {@code intVal} has a fractional part throws an exception, 2855 * otherwise it counts the number of bits of value and checks if it's out of 2856 * the range of the primitive type. If the number fits in the primitive type 2857 * returns this number as {@code long}, otherwise throws an 2858 * exception. 2859 * 2860 * @param bitLengthOfType 2861 * number of bits of the type whose value will be calculated 2862 * exactly 2863 * @return the exact value of the integer part of {@code BigDecimal} 2864 * when is possible 2865 * @throws ArithmeticException when rounding is necessary or the 2866 * number don't fit in the primitive type 2867 */ valueExact(int bitLengthOfType)2868 private long valueExact(int bitLengthOfType) { 2869 BigInteger bigInteger = toBigIntegerExact(); 2870 2871 if (bigInteger.bitLength() < bitLengthOfType) { 2872 // It fits in the primitive type 2873 return bigInteger.longValue(); 2874 } 2875 throw new ArithmeticException("Rounding necessary"); 2876 } 2877 2878 /** 2879 * If the precision already was calculated it returns that value, otherwise 2880 * it calculates a very good approximation efficiently . Note that this 2881 * value will be {@code precision()} or {@code precision()-1} 2882 * in the worst case. 2883 * 2884 * @return an approximation of {@code precision()} value 2885 */ approxPrecision()2886 private int approxPrecision() { 2887 return precision > 0 2888 ? precision 2889 : (int) ((this.bitLength - 1) * LOG10_2) + 1; 2890 } 2891 safeLongToInt(long longValue)2892 private static int safeLongToInt(long longValue) { 2893 if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) { 2894 throw new ArithmeticException("Out of int range: " + longValue); 2895 } 2896 return (int) longValue; 2897 } 2898 2899 /** 2900 * It returns the value 0 with the most approximated scale of type 2901 * {@code int}. if {@code longScale > Integer.MAX_VALUE} the 2902 * scale will be {@code Integer.MAX_VALUE}; if 2903 * {@code longScale < Integer.MIN_VALUE} the scale will be 2904 * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is 2905 * casted to the type {@code int}. 2906 * 2907 * @param longScale 2908 * the scale to which the value 0 will be scaled. 2909 * @return the value 0 scaled by the closer scale of type {@code int}. 2910 * @see #scale 2911 */ zeroScaledBy(long longScale)2912 private static BigDecimal zeroScaledBy(long longScale) { 2913 if (longScale == (int) longScale) { 2914 return valueOf(0,(int)longScale); 2915 } 2916 if (longScale >= 0) { 2917 return new BigDecimal( 0, Integer.MAX_VALUE); 2918 } 2919 return new BigDecimal( 0, Integer.MIN_VALUE); 2920 } 2921 2922 /** 2923 * Assigns all transient fields upon deserialization of a 2924 * {@code BigDecimal} instance (bitLength and smallValue). The transient 2925 * field precision is assigned lazily. 2926 */ readObject(ObjectInputStream in)2927 private void readObject(ObjectInputStream in) throws IOException, 2928 ClassNotFoundException { 2929 in.defaultReadObject(); 2930 2931 this.bitLength = intVal.bitLength(); 2932 if (this.bitLength < 64) { 2933 this.smallValue = intVal.longValue(); 2934 } 2935 } 2936 2937 /** 2938 * Prepares this {@code BigDecimal} for serialization, i.e. the 2939 * non-transient field {@code intVal} is assigned. 2940 */ writeObject(ObjectOutputStream out)2941 private void writeObject(ObjectOutputStream out) throws IOException { 2942 getUnscaledValue(); 2943 out.defaultWriteObject(); 2944 } 2945 getUnscaledValue()2946 private BigInteger getUnscaledValue() { 2947 if(intVal == null) { 2948 intVal = BigInteger.valueOf(smallValue); 2949 } 2950 return intVal; 2951 } 2952 setUnscaledValue(BigInteger unscaledValue)2953 private void setUnscaledValue(BigInteger unscaledValue) { 2954 this.intVal = unscaledValue; 2955 this.bitLength = unscaledValue.bitLength(); 2956 if(this.bitLength < 64) { 2957 this.smallValue = unscaledValue.longValue(); 2958 } 2959 } 2960 bitLength(long smallValue)2961 private static int bitLength(long smallValue) { 2962 if(smallValue < 0) { 2963 smallValue = ~smallValue; 2964 } 2965 return 64 - Long.numberOfLeadingZeros(smallValue); 2966 } 2967 bitLength(int smallValue)2968 private static int bitLength(int smallValue) { 2969 if(smallValue < 0) { 2970 smallValue = ~smallValue; 2971 } 2972 return 32 - Integer.numberOfLeadingZeros(smallValue); 2973 } 2974 2975 } 2976