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 return new BigDecimal(BigInteger.ZERO, 0); 2038 } 2039 BigInteger strippedBI = getUnscaledValue(); 2040 BigInteger[] quotAndRem; 2041 2042 // while the number is even... 2043 while (!strippedBI.testBit(0)) { 2044 // To divide by 10^i 2045 quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]); 2046 // To look the remainder 2047 if (quotAndRem[1].signum() == 0) { 2048 // To adjust the scale 2049 newScale -= i; 2050 if (i < lastPow) { 2051 // To set to the next power 2052 i++; 2053 } 2054 strippedBI = quotAndRem[0]; 2055 } else { 2056 if (i == 1) { 2057 // 'this' has no more trailing zeros 2058 break; 2059 } 2060 // To set to the smallest power of ten 2061 i = 1; 2062 } 2063 } 2064 return new BigDecimal(strippedBI, safeLongToInt(newScale)); 2065 } 2066 2067 /** 2068 * Compares this {@code BigDecimal} with {@code val}. Returns one of the 2069 * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as 2070 * if {@code this.subtract(val)} is computed. If this difference is > 0 then 2071 * 1 is returned, if the difference is < 0 then -1 is returned, and if the 2072 * difference is 0 then 0 is returned. This means, that if two decimal 2073 * instances are compared which are equal in value but differ in scale, then 2074 * these two instances are considered as equal. 2075 * 2076 * @param val 2077 * value to be compared with {@code this}. 2078 * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val}, 2079 * {@code 0} if {@code this == val}. 2080 * @throws NullPointerException 2081 * if {@code val == null}. 2082 */ compareTo(BigDecimal val)2083 public int compareTo(BigDecimal val) { 2084 int thisSign = signum(); 2085 int valueSign = val.signum(); 2086 2087 if( thisSign == valueSign) { 2088 if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) { 2089 return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0; 2090 } 2091 long diffScale = (long)this.scale - val.scale; 2092 int diffPrecision = this.approxPrecision() - val.approxPrecision(); 2093 if (diffPrecision > diffScale + 1) { 2094 return thisSign; 2095 } else if (diffPrecision < diffScale - 1) { 2096 return -thisSign; 2097 } else {// thisSign == val.signum() and diffPrecision is aprox. diffScale 2098 BigInteger thisUnscaled = this.getUnscaledValue(); 2099 BigInteger valUnscaled = val.getUnscaledValue(); 2100 // If any of both precision is bigger, append zeros to the shorter one 2101 if (diffScale < 0) { 2102 thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale)); 2103 } else if (diffScale > 0) { 2104 valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale)); 2105 } 2106 return thisUnscaled.compareTo(valUnscaled); 2107 } 2108 } else if (thisSign < valueSign) { 2109 return -1; 2110 } else { 2111 return 1; 2112 } 2113 } 2114 2115 /** 2116 * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if 2117 * this instance is equal to this big decimal. Two big decimals are equal if 2118 * their unscaled value and their scale is equal. For example, 1.0 2119 * (10*10<sup>-1</sup>) is not equal to 1.00 (100*10<sup>-2</sup>). Similarly, zero 2120 * instances are not equal if their scale differs. 2121 */ 2122 @Override equals(Object x)2123 public boolean equals(Object x) { 2124 if (this == x) { 2125 return true; 2126 } 2127 if (x instanceof BigDecimal) { 2128 BigDecimal x1 = (BigDecimal) x; 2129 return x1.scale == scale 2130 && x1.bitLength == bitLength 2131 && (bitLength < 64 ? (x1.smallValue == smallValue) : x1.intVal.equals(intVal)); 2132 } 2133 return false; 2134 } 2135 2136 /** 2137 * Returns the minimum of this {@code BigDecimal} and {@code val}. 2138 * 2139 * @param val 2140 * value to be used to compute the minimum with this. 2141 * @return {@code min(this, val}. 2142 * @throws NullPointerException 2143 * if {@code val == null}. 2144 */ min(BigDecimal val)2145 public BigDecimal min(BigDecimal val) { 2146 return ((compareTo(val) <= 0) ? this : val); 2147 } 2148 2149 /** 2150 * Returns the maximum of this {@code BigDecimal} and {@code val}. 2151 * 2152 * @param val 2153 * value to be used to compute the maximum with this. 2154 * @return {@code max(this, val}. 2155 * @throws NullPointerException 2156 * if {@code val == null}. 2157 */ max(BigDecimal val)2158 public BigDecimal max(BigDecimal val) { 2159 return ((compareTo(val) >= 0) ? this : val); 2160 } 2161 2162 /** 2163 * Returns a hash code for this {@code BigDecimal}. 2164 * 2165 * @return hash code for {@code this}. 2166 */ 2167 @Override hashCode()2168 public int hashCode() { 2169 if (hashCode != 0) { 2170 return hashCode; 2171 } 2172 if (bitLength < 64) { 2173 hashCode = (int)(smallValue & 0xffffffff); 2174 hashCode = 33 * hashCode + (int)((smallValue >> 32) & 0xffffffff); 2175 hashCode = 17 * hashCode + scale; 2176 return hashCode; 2177 } 2178 hashCode = 17 * intVal.hashCode() + scale; 2179 return hashCode; 2180 } 2181 2182 /** 2183 * Returns a canonical string representation of this {@code BigDecimal}. If 2184 * necessary, scientific notation is used. This representation always prints 2185 * all significant digits of this value. 2186 * <p> 2187 * If the scale is negative or if {@code scale - precision >= 6} then 2188 * scientific notation is used. 2189 * 2190 * @return a string representation of {@code this} in scientific notation if 2191 * necessary. 2192 */ 2193 @Override toString()2194 public String toString() { 2195 if (toStringImage != null) { 2196 return toStringImage; 2197 } 2198 if(bitLength < 32) { 2199 toStringImage = Conversion.toDecimalScaledString(smallValue,scale); 2200 return toStringImage; 2201 } 2202 String intString = getUnscaledValue().toString(); 2203 if (scale == 0) { 2204 return intString; 2205 } 2206 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2207 int end = intString.length(); 2208 long exponent = -(long)scale + end - begin; 2209 StringBuilder result = new StringBuilder(); 2210 2211 result.append(intString); 2212 if ((scale > 0) && (exponent >= -6)) { 2213 if (exponent >= 0) { 2214 result.insert(end - scale, '.'); 2215 } else { 2216 result.insert(begin - 1, "0."); 2217 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2218 } 2219 } else { 2220 if (end - begin >= 1) { 2221 result.insert(begin, '.'); 2222 end++; 2223 } 2224 result.insert(end, 'E'); 2225 if (exponent > 0) { 2226 result.insert(++end, '+'); 2227 } 2228 result.insert(++end, Long.toString(exponent)); 2229 } 2230 toStringImage = result.toString(); 2231 return toStringImage; 2232 } 2233 2234 /** 2235 * Returns a string representation of this {@code BigDecimal}. This 2236 * representation always prints all significant digits of this value. 2237 * <p> 2238 * If the scale is negative or if {@code scale - precision >= 6} then 2239 * engineering notation is used. Engineering notation is similar to the 2240 * scientific notation except that the exponent is made to be a multiple of 2241 * 3 such that the integer part is >= 1 and < 1000. 2242 * 2243 * @return a string representation of {@code this} in engineering notation 2244 * if necessary. 2245 */ toEngineeringString()2246 public String toEngineeringString() { 2247 String intString = getUnscaledValue().toString(); 2248 if (scale == 0) { 2249 return intString; 2250 } 2251 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2252 int end = intString.length(); 2253 long exponent = -(long)scale + end - begin; 2254 StringBuilder result = new StringBuilder(intString); 2255 2256 if ((scale > 0) && (exponent >= -6)) { 2257 if (exponent >= 0) { 2258 result.insert(end - scale, '.'); 2259 } else { 2260 result.insert(begin - 1, "0."); 2261 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2262 } 2263 } else { 2264 int delta = end - begin; 2265 int rem = (int)(exponent % 3); 2266 2267 if (rem != 0) { 2268 // adjust exponent so it is a multiple of three 2269 if (getUnscaledValue().signum() == 0) { 2270 // zero value 2271 rem = (rem < 0) ? -rem : 3 - rem; 2272 exponent += rem; 2273 } else { 2274 // nonzero value 2275 rem = (rem < 0) ? rem + 3 : rem; 2276 exponent -= rem; 2277 begin += rem; 2278 } 2279 if (delta < 3) { 2280 for (int i = rem - delta; i > 0; i--) { 2281 result.insert(end++, '0'); 2282 } 2283 } 2284 } 2285 if (end - begin >= 1) { 2286 result.insert(begin, '.'); 2287 end++; 2288 } 2289 if (exponent != 0) { 2290 result.insert(end, 'E'); 2291 if (exponent > 0) { 2292 result.insert(++end, '+'); 2293 } 2294 result.insert(++end, Long.toString(exponent)); 2295 } 2296 } 2297 return result.toString(); 2298 } 2299 2300 /** 2301 * Returns a string representation of this {@code BigDecimal}. No scientific 2302 * notation is used. This methods adds zeros where necessary. 2303 * <p> 2304 * If this string representation is used to create a new instance, this 2305 * instance is generally not identical to {@code this} as the precision 2306 * changes. 2307 * <p> 2308 * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns 2309 * {@code false}. 2310 * <p> 2311 * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}. 2312 * 2313 * @return a string representation of {@code this} without exponent part. 2314 */ toPlainString()2315 public String toPlainString() { 2316 String intStr = getUnscaledValue().toString(); 2317 if ((scale == 0) || ((isZero()) && (scale < 0))) { 2318 return intStr; 2319 } 2320 int begin = (signum() < 0) ? 1 : 0; 2321 int delta = scale; 2322 // We take space for all digits, plus a possible decimal point, plus 'scale' 2323 StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale)); 2324 2325 if (begin == 1) { 2326 // If the number is negative, we insert a '-' character at front 2327 result.append('-'); 2328 } 2329 if (scale > 0) { 2330 delta -= (intStr.length() - begin); 2331 if (delta >= 0) { 2332 result.append("0."); 2333 // To append zeros after the decimal point 2334 for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) { 2335 result.append(CH_ZEROS); 2336 } 2337 result.append(CH_ZEROS, 0, delta); 2338 result.append(intStr.substring(begin)); 2339 } else { 2340 delta = begin - delta; 2341 result.append(intStr.substring(begin, delta)); 2342 result.append('.'); 2343 result.append(intStr.substring(delta)); 2344 } 2345 } else {// (scale <= 0) 2346 result.append(intStr.substring(begin)); 2347 // To append trailing zeros 2348 for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) { 2349 result.append(CH_ZEROS); 2350 } 2351 result.append(CH_ZEROS, 0, -delta); 2352 } 2353 return result.toString(); 2354 } 2355 2356 /** 2357 * Returns this {@code BigDecimal} as a big integer instance. A fractional 2358 * part is discarded. 2359 * 2360 * @return this {@code BigDecimal} as a big integer instance. 2361 */ toBigInteger()2362 public BigInteger toBigInteger() { 2363 if ((scale == 0) || (isZero())) { 2364 return getUnscaledValue(); 2365 } else if (scale < 0) { 2366 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2367 } else {// (scale > 0) 2368 return getUnscaledValue().divide(Multiplication.powerOf10(scale)); 2369 } 2370 } 2371 2372 /** 2373 * Returns this {@code BigDecimal} as a big integer instance if it has no 2374 * fractional part. If this {@code BigDecimal} has a fractional part, i.e. 2375 * if rounding would be necessary, an {@code ArithmeticException} is thrown. 2376 * 2377 * @return this {@code BigDecimal} as a big integer value. 2378 * @throws ArithmeticException 2379 * if rounding is necessary. 2380 */ toBigIntegerExact()2381 public BigInteger toBigIntegerExact() { 2382 if ((scale == 0) || (isZero())) { 2383 return getUnscaledValue(); 2384 } else if (scale < 0) { 2385 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2386 } else {// (scale > 0) 2387 BigInteger[] integerAndFraction; 2388 // An optimization before do a heavy division 2389 if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) { 2390 throw new ArithmeticException("Rounding necessary"); 2391 } 2392 integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale)); 2393 if (integerAndFraction[1].signum() != 0) { 2394 // It exists a non-zero fractional part 2395 throw new ArithmeticException("Rounding necessary"); 2396 } 2397 return integerAndFraction[0]; 2398 } 2399 } 2400 2401 /** 2402 * Returns this {@code BigDecimal} as an long value. Any fractional part is 2403 * discarded. If the integral part of {@code this} is too big to be 2404 * represented as an long, then {@code this % 2<sup>64</sup>} is returned. 2405 */ 2406 @Override longValue()2407 public long longValue() { 2408 /* 2409 * If scale <= -64 there are at least 64 trailing bits zero in 2410 * 10^(-scale). If the scale is positive and very large the long value 2411 * could be zero. 2412 */ 2413 return ((scale <= -64) || (scale > approxPrecision()) ? 0L : toBigInteger().longValue()); 2414 } 2415 2416 /** 2417 * Returns this {@code BigDecimal} as a long value if it has no fractional 2418 * part and if its value fits to the int range ([-2<sup>63</sup>..2<sup>63</sup>-1]). If 2419 * these conditions are not met, an {@code ArithmeticException} is thrown. 2420 * 2421 * @throws ArithmeticException 2422 * if rounding is necessary or the number doesn't fit in a long. 2423 */ longValueExact()2424 public long longValueExact() { 2425 return valueExact(64); 2426 } 2427 2428 /** 2429 * Returns this {@code BigDecimal} as an int value. Any fractional part is 2430 * discarded. If the integral part of {@code this} is too big to be 2431 * represented as an int, then {@code this % 2<sup>32</sup>} is returned. 2432 */ 2433 @Override intValue()2434 public int intValue() { 2435 /* 2436 * If scale <= -32 there are at least 32 trailing bits zero in 2437 * 10^(-scale). If the scale is positive and very large the long value 2438 * could be zero. 2439 */ 2440 return ((scale <= -32) || (scale > approxPrecision()) ? 0 : toBigInteger().intValue()); 2441 } 2442 2443 /** 2444 * Returns this {@code BigDecimal} as a int value if it has no fractional 2445 * part and if its value fits to the int range ([-2<sup>31</sup>..2<sup>31</sup>-1]). If 2446 * these conditions are not met, an {@code ArithmeticException} is thrown. 2447 * 2448 * @throws ArithmeticException 2449 * if rounding is necessary or the number doesn't fit in an int. 2450 */ intValueExact()2451 public int intValueExact() { 2452 return (int) valueExact(32); 2453 } 2454 2455 /** 2456 * Returns this {@code BigDecimal} as a short value if it has no fractional 2457 * part and if its value fits to the short range ([-2<sup>15</sup>..2<sup>15</sup>-1]). If 2458 * these conditions are not met, an {@code ArithmeticException} is thrown. 2459 * 2460 * @throws ArithmeticException 2461 * if rounding is necessary of the number doesn't fit in a short. 2462 */ shortValueExact()2463 public short shortValueExact() { 2464 return (short) valueExact(16); 2465 } 2466 2467 /** 2468 * Returns this {@code BigDecimal} as a byte value if it has no fractional 2469 * part and if its value fits to the byte range ([-128..127]). If these 2470 * conditions are not met, an {@code ArithmeticException} is thrown. 2471 * 2472 * @throws ArithmeticException 2473 * if rounding is necessary or the number doesn't fit in a byte. 2474 */ byteValueExact()2475 public byte byteValueExact() { 2476 return (byte) valueExact(8); 2477 } 2478 2479 /** 2480 * Returns this {@code BigDecimal} as a float value. If {@code this} is too 2481 * big to be represented as an float, then {@code Float.POSITIVE_INFINITY} 2482 * or {@code Float.NEGATIVE_INFINITY} is returned. 2483 * <p> 2484 * Note, that if the unscaled value has more than 24 significant digits, 2485 * then this decimal cannot be represented exactly in a float variable. In 2486 * this case the result is rounded. 2487 * <p> 2488 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2489 * represented exactly as a float, and thus {@code x1.equals(new 2490 * BigDecimal(x1.floatValue())} returns {@code false} for this case. 2491 * <p> 2492 * Similarly, if the instance {@code new BigDecimal(16777217)} is converted 2493 * to a float, the result is {@code 1.6777216E}7. 2494 * 2495 * @return this {@code BigDecimal} as a float value. 2496 */ 2497 @Override floatValue()2498 public float floatValue() { 2499 /* A similar code like in doubleValue() could be repeated here, 2500 * but this simple implementation is quite efficient. */ 2501 float floatResult = signum(); 2502 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2503 if ((powerOfTwo < -149) || (floatResult == 0.0f)) { 2504 // Cases which 'this' is very small 2505 floatResult *= 0.0f; 2506 } else if (powerOfTwo > 129) { 2507 // Cases which 'this' is very large 2508 floatResult *= Float.POSITIVE_INFINITY; 2509 } else { 2510 floatResult = (float)doubleValue(); 2511 } 2512 return floatResult; 2513 } 2514 2515 /** 2516 * Returns this {@code BigDecimal} as a double value. If {@code this} is too 2517 * big to be represented as an float, then {@code Double.POSITIVE_INFINITY} 2518 * or {@code Double.NEGATIVE_INFINITY} is returned. 2519 * <p> 2520 * Note, that if the unscaled value has more than 53 significant digits, 2521 * then this decimal cannot be represented exactly in a double variable. In 2522 * this case the result is rounded. 2523 * <p> 2524 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2525 * represented exactly as a double, and thus {@code x1.equals(new 2526 * BigDecimal(x1.doubleValue())} returns {@code false} for this case. 2527 * <p> 2528 * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is 2529 * converted to a double, the result is {@code 9.007199254740992E15}. 2530 * <p> 2531 * 2532 * @return this {@code BigDecimal} as a double value. 2533 */ 2534 @Override doubleValue()2535 public double doubleValue() { 2536 int sign = signum(); 2537 int exponent = 1076; // bias + 53 2538 int lowestSetBit; 2539 int discardedSize; 2540 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2541 long bits; // IEEE-754 Standard 2542 long tempBits; // for temporal calculations 2543 BigInteger mantissa; 2544 2545 if ((powerOfTwo < -1074) || (sign == 0)) { 2546 // Cases which 'this' is very small 2547 return (sign * 0.0d); 2548 } else if (powerOfTwo > 1025) { 2549 // Cases which 'this' is very large 2550 return (sign * Double.POSITIVE_INFINITY); 2551 } 2552 mantissa = getUnscaledValue().abs(); 2553 // Let be: this = [u,s], with s > 0 2554 if (scale <= 0) { 2555 // mantissa = abs(u) * 10^s 2556 mantissa = mantissa.multiply(Multiplication.powerOf10(-scale)); 2557 } else {// (scale > 0) 2558 BigInteger quotAndRem[]; 2559 BigInteger powerOfTen = Multiplication.powerOf10(scale); 2560 int k = 100 - (int)powerOfTwo; 2561 int compRem; 2562 2563 if (k > 0) { 2564 /* Computing (mantissa * 2^k) , where 'k' is a enough big 2565 * power of '2' to can divide by 10^s */ 2566 mantissa = mantissa.shiftLeft(k); 2567 exponent -= k; 2568 } 2569 // Computing (mantissa * 2^k) / 10^s 2570 quotAndRem = mantissa.divideAndRemainder(powerOfTen); 2571 // To check if the fractional part >= 0.5 2572 compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen); 2573 // To add two rounded bits at end of mantissa 2574 mantissa = quotAndRem[0].shiftLeft(2).add( 2575 BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1)); 2576 exponent -= 2; 2577 } 2578 lowestSetBit = mantissa.getLowestSetBit(); 2579 discardedSize = mantissa.bitLength() - 54; 2580 if (discardedSize > 0) {// (n > 54) 2581 // mantissa = (abs(u) * 10^s) >> (n - 54) 2582 bits = mantissa.shiftRight(discardedSize).longValue(); 2583 tempBits = bits; 2584 // #bits = 54, to check if the discarded fraction produces a carry 2585 if ((((bits & 1) == 1) && (lowestSetBit < discardedSize)) 2586 || ((bits & 3) == 3)) { 2587 bits += 2; 2588 } 2589 } else {// (n <= 54) 2590 // mantissa = (abs(u) * 10^s) << (54 - n) 2591 bits = mantissa.longValue() << -discardedSize; 2592 tempBits = bits; 2593 // #bits = 54, to check if the discarded fraction produces a carry: 2594 if ((bits & 3) == 3) { 2595 bits += 2; 2596 } 2597 } 2598 // Testing bit 54 to check if the carry creates a new binary digit 2599 if ((bits & 0x40000000000000L) == 0) { 2600 // To drop the last bit of mantissa (first discarded) 2601 bits >>= 1; 2602 // exponent = 2^(s-n+53+bias) 2603 exponent += discardedSize; 2604 } else {// #bits = 54 2605 bits >>= 2; 2606 exponent += discardedSize + 1; 2607 } 2608 // To test if the 53-bits number fits in 'double' 2609 if (exponent > 2046) {// (exponent - bias > 1023) 2610 return (sign * Double.POSITIVE_INFINITY); 2611 } else if (exponent <= 0) {// (exponent - bias <= -1023) 2612 // Denormalized numbers (having exponent == 0) 2613 if (exponent < -53) {// exponent - bias < -1076 2614 return (sign * 0.0d); 2615 } 2616 // -1076 <= exponent - bias <= -1023 2617 // To discard '- exponent + 1' bits 2618 bits = tempBits >> 1; 2619 tempBits = bits & (-1L >>> (63 + exponent)); 2620 bits >>= (-exponent ); 2621 // To test if after discard bits, a new carry is generated 2622 if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0) 2623 && (lowestSetBit < discardedSize))) { 2624 bits += 1; 2625 } 2626 exponent = 0; 2627 bits >>= 1; 2628 } 2629 // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)] 2630 bits = (sign & 0x8000000000000000L) | ((long)exponent << 52) 2631 | (bits & 0xFFFFFFFFFFFFFL); 2632 return Double.longBitsToDouble(bits); 2633 } 2634 2635 /** 2636 * Returns the unit in the last place (ULP) of this {@code BigDecimal} 2637 * instance. An ULP is the distance to the nearest big decimal with the same 2638 * precision. 2639 * 2640 * <p>The amount of a rounding error in the evaluation of a floating-point 2641 * operation is often expressed in ULPs. An error of 1 ULP is often seen as 2642 * a tolerable error. 2643 * 2644 * <p>For class {@code BigDecimal}, the ULP of a number is simply 10<sup>-scale</sup>. 2645 * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}. 2646 * 2647 * @return unit in the last place (ULP) of this {@code BigDecimal} instance. 2648 */ ulp()2649 public BigDecimal ulp() { 2650 return valueOf(1, scale); 2651 } 2652 2653 /* Private Methods */ 2654 2655 /** 2656 * It does all rounding work of the public method 2657 * {@code round(MathContext)}, performing an inplace rounding 2658 * without creating a new object. 2659 * 2660 * @param mc 2661 * the {@code MathContext} for perform the rounding. 2662 * @see #round(MathContext) 2663 */ inplaceRound(MathContext mc)2664 private void inplaceRound(MathContext mc) { 2665 int mcPrecision = mc.getPrecision(); 2666 if (approxPrecision() < mcPrecision || mcPrecision == 0) { 2667 return; 2668 } 2669 int discardedPrecision = precision() - mcPrecision; 2670 // If no rounding is necessary it returns immediately 2671 if ((discardedPrecision <= 0)) { 2672 return; 2673 } 2674 // When the number is small perform an efficient rounding 2675 if (this.bitLength < 64) { 2676 smallRound(mc, discardedPrecision); 2677 return; 2678 } 2679 // Getting the integer part and the discarded fraction 2680 BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision); 2681 BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction); 2682 long newScale = (long)scale - discardedPrecision; 2683 int compRem; 2684 BigDecimal tempBD; 2685 // If the discarded fraction is non-zero, perform rounding 2686 if (integerAndFraction[1].signum() != 0) { 2687 // To check if the discarded fraction >= 0.5 2688 compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction)); 2689 // To look if there is a carry 2690 compRem = roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0, 2691 integerAndFraction[1].signum() * (5 + compRem), 2692 mc.getRoundingMode()); 2693 if (compRem != 0) { 2694 integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem)); 2695 } 2696 tempBD = new BigDecimal(integerAndFraction[0]); 2697 // If after to add the increment the precision changed, we normalize the size 2698 if (tempBD.precision() > mcPrecision) { 2699 integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN); 2700 newScale--; 2701 } 2702 } 2703 // To update all internal fields 2704 scale = safeLongToInt(newScale); 2705 precision = mcPrecision; 2706 setUnscaledValue(integerAndFraction[0]); 2707 } 2708 2709 /** 2710 * Returns -1, 0, and 1 if {@code value1 < value2}, {@code value1 == value2}, 2711 * and {@code value1 > value2}, respectively, when comparing without regard 2712 * to the values' sign. 2713 * 2714 * <p>Note that this implementation deals correctly with Long.MIN_VALUE, 2715 * whose absolute magnitude is larger than any other {@code long} value. 2716 */ compareAbsoluteValues(long value1, long value2)2717 private static int compareAbsoluteValues(long value1, long value2) { 2718 // Map long values to the range -1 .. Long.MAX_VALUE so that comparison 2719 // of absolute magnitude can be done using regular long arithmetics. 2720 // This deals correctly with Long.MIN_VALUE, whose absolute magnitude 2721 // is larger than any other long value, and which is mapped to 2722 // Long.MAX_VALUE here. 2723 // Values that only differ by sign get mapped to the same value, for 2724 // example both +3 and -3 get mapped to +2. 2725 value1 = Math.abs(value1) - 1; 2726 value2 = Math.abs(value2) - 1; 2727 // Unlike Long.compare(), we guarantee to return specifically -1 and +1 2728 return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0); 2729 } 2730 2731 /** 2732 * Compares {@code n} against {@code 0.5 * d} in absolute terms (ignoring sign) 2733 * and with arithmetics that are safe against overflow or loss of precision. 2734 * Returns -1 if {@code n} is less than {@code 0.5 * d}, 0 if {@code n == 0.5 * d}, 2735 * or +1 if {@code n > 0.5 * d} when comparing the absolute values under such 2736 * arithmetics. 2737 */ compareForRounding(long n, long d)2738 private static int compareForRounding(long n, long d) { 2739 long halfD = d / 2; // rounds towards 0 2740 if (n == halfD || n == -halfD) { 2741 // In absolute terms: Because n == halfD, we know that 2 * n + lsb == d 2742 // for some lsb value 0 or 1. This means that n == d/2 (result 0) if 2743 // lsb is 0, or n < d/2 (result -1) if lsb is 1. In either case, the 2744 // result is -lsb. 2745 // Since we're calculating in absolute terms, we need the absolute lsb 2746 // (d & 1) as opposed to the signed lsb (d % 2) which would be -1 for 2747 // negative odd values of d. 2748 int lsb = (int) d & 1; 2749 return -lsb; // returns 0 or -1 2750 } else { 2751 // In absolute terms, either 2 * n + 1 < d (in the case of n < halfD), 2752 // or 2 * n > d (in the case of n > halfD). 2753 // In either case, comparing n against halfD gets the right result 2754 // -1 or +1, respectively. 2755 return compareAbsoluteValues(n, halfD); 2756 } 2757 } 2758 2759 /** 2760 * This method implements an efficient rounding for numbers which unscaled 2761 * value fits in the type {@code long}. 2762 * 2763 * @param mc 2764 * the context to use 2765 * @param discardedPrecision 2766 * the number of decimal digits that are discarded 2767 * @see #round(MathContext) 2768 */ smallRound(MathContext mc, int discardedPrecision)2769 private void smallRound(MathContext mc, int discardedPrecision) { 2770 long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision]; 2771 long newScale = (long)scale - discardedPrecision; 2772 long unscaledVal = smallValue; 2773 // Getting the integer part and the discarded fraction 2774 long integer = unscaledVal / sizeOfFraction; 2775 long fraction = unscaledVal % sizeOfFraction; 2776 int compRem; 2777 // If the discarded fraction is non-zero perform rounding 2778 if (fraction != 0) { 2779 // To check if the discarded fraction >= 0.5 2780 compRem = compareForRounding(fraction, sizeOfFraction); 2781 // To look if there is a carry 2782 integer += roundingBehavior( ((int)integer) & 1, 2783 Long.signum(fraction) * (5 + compRem), 2784 mc.getRoundingMode()); 2785 // If after to add the increment the precision changed, we normalize the size 2786 if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) { 2787 integer /= 10; 2788 newScale--; 2789 } 2790 } 2791 // To update all internal fields 2792 scale = safeLongToInt(newScale); 2793 precision = mc.getPrecision(); 2794 smallValue = integer; 2795 bitLength = bitLength(integer); 2796 intVal = null; 2797 } 2798 2799 /** 2800 * Return an increment that can be -1,0 or 1, depending of 2801 * {@code roundingMode}. 2802 * 2803 * @param parityBit 2804 * can be 0 or 1, it's only used in the case 2805 * {@code HALF_EVEN} 2806 * @param fraction 2807 * the mantissa to be analyzed 2808 * @param roundingMode 2809 * the type of rounding 2810 * @return the carry propagated after rounding 2811 */ roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode)2812 private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) { 2813 int increment = 0; // the carry after rounding 2814 2815 switch (roundingMode) { 2816 case UNNECESSARY: 2817 if (fraction != 0) { 2818 throw new ArithmeticException("Rounding necessary"); 2819 } 2820 break; 2821 case UP: 2822 increment = Integer.signum(fraction); 2823 break; 2824 case DOWN: 2825 break; 2826 case CEILING: 2827 increment = Math.max(Integer.signum(fraction), 0); 2828 break; 2829 case FLOOR: 2830 increment = Math.min(Integer.signum(fraction), 0); 2831 break; 2832 case HALF_UP: 2833 if (Math.abs(fraction) >= 5) { 2834 increment = Integer.signum(fraction); 2835 } 2836 break; 2837 case HALF_DOWN: 2838 if (Math.abs(fraction) > 5) { 2839 increment = Integer.signum(fraction); 2840 } 2841 break; 2842 case HALF_EVEN: 2843 if (Math.abs(fraction) + parityBit > 5) { 2844 increment = Integer.signum(fraction); 2845 } 2846 break; 2847 } 2848 return increment; 2849 } 2850 2851 /** 2852 * If {@code intVal} has a fractional part throws an exception, 2853 * otherwise it counts the number of bits of value and checks if it's out of 2854 * the range of the primitive type. If the number fits in the primitive type 2855 * returns this number as {@code long}, otherwise throws an 2856 * exception. 2857 * 2858 * @param bitLengthOfType 2859 * number of bits of the type whose value will be calculated 2860 * exactly 2861 * @return the exact value of the integer part of {@code BigDecimal} 2862 * when is possible 2863 * @throws ArithmeticException when rounding is necessary or the 2864 * number don't fit in the primitive type 2865 */ valueExact(int bitLengthOfType)2866 private long valueExact(int bitLengthOfType) { 2867 BigInteger bigInteger = toBigIntegerExact(); 2868 2869 if (bigInteger.bitLength() < bitLengthOfType) { 2870 // It fits in the primitive type 2871 return bigInteger.longValue(); 2872 } 2873 throw new ArithmeticException("Rounding necessary"); 2874 } 2875 2876 /** 2877 * If the precision already was calculated it returns that value, otherwise 2878 * it calculates a very good approximation efficiently . Note that this 2879 * value will be {@code precision()} or {@code precision()-1} 2880 * in the worst case. 2881 * 2882 * @return an approximation of {@code precision()} value 2883 */ approxPrecision()2884 private int approxPrecision() { 2885 return precision > 0 2886 ? precision 2887 : (int) ((this.bitLength - 1) * LOG10_2) + 1; 2888 } 2889 safeLongToInt(long longValue)2890 private static int safeLongToInt(long longValue) { 2891 if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) { 2892 throw new ArithmeticException("Out of int range: " + longValue); 2893 } 2894 return (int) longValue; 2895 } 2896 2897 /** 2898 * It returns the value 0 with the most approximated scale of type 2899 * {@code int}. if {@code longScale > Integer.MAX_VALUE} the 2900 * scale will be {@code Integer.MAX_VALUE}; if 2901 * {@code longScale < Integer.MIN_VALUE} the scale will be 2902 * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is 2903 * casted to the type {@code int}. 2904 * 2905 * @param longScale 2906 * the scale to which the value 0 will be scaled. 2907 * @return the value 0 scaled by the closer scale of type {@code int}. 2908 * @see #scale 2909 */ zeroScaledBy(long longScale)2910 private static BigDecimal zeroScaledBy(long longScale) { 2911 if (longScale == (int) longScale) { 2912 return valueOf(0,(int)longScale); 2913 } 2914 if (longScale >= 0) { 2915 return new BigDecimal( 0, Integer.MAX_VALUE); 2916 } 2917 return new BigDecimal( 0, Integer.MIN_VALUE); 2918 } 2919 2920 /** 2921 * Assigns all transient fields upon deserialization of a 2922 * {@code BigDecimal} instance (bitLength and smallValue). The transient 2923 * field precision is assigned lazily. 2924 */ readObject(ObjectInputStream in)2925 private void readObject(ObjectInputStream in) throws IOException, 2926 ClassNotFoundException { 2927 in.defaultReadObject(); 2928 2929 this.bitLength = intVal.bitLength(); 2930 if (this.bitLength < 64) { 2931 this.smallValue = intVal.longValue(); 2932 } 2933 } 2934 2935 /** 2936 * Prepares this {@code BigDecimal} for serialization, i.e. the 2937 * non-transient field {@code intVal} is assigned. 2938 */ writeObject(ObjectOutputStream out)2939 private void writeObject(ObjectOutputStream out) throws IOException { 2940 getUnscaledValue(); 2941 out.defaultWriteObject(); 2942 } 2943 getUnscaledValue()2944 private BigInteger getUnscaledValue() { 2945 if(intVal == null) { 2946 intVal = BigInteger.valueOf(smallValue); 2947 } 2948 return intVal; 2949 } 2950 setUnscaledValue(BigInteger unscaledValue)2951 private void setUnscaledValue(BigInteger unscaledValue) { 2952 this.intVal = unscaledValue; 2953 this.bitLength = unscaledValue.bitLength(); 2954 if(this.bitLength < 64) { 2955 this.smallValue = unscaledValue.longValue(); 2956 } 2957 } 2958 bitLength(long smallValue)2959 private static int bitLength(long smallValue) { 2960 if(smallValue < 0) { 2961 smallValue = ~smallValue; 2962 } 2963 return 64 - Long.numberOfLeadingZeros(smallValue); 2964 } 2965 bitLength(int smallValue)2966 private static int bitLength(int smallValue) { 2967 if(smallValue < 0) { 2968 smallValue = ~smallValue; 2969 } 2970 return 32 - Integer.numberOfLeadingZeros(smallValue); 2971 } 2972 2973 } 2974