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 { 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 237 private BigDecimal(long smallValue, int scale){ 238 this.smallValue = smallValue; 239 this.scale = scale; 240 this.bitLength = bitLength(smallValue); 241 } 242 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 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 */ 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 */ 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 */ 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 */ 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 return valueOf(this.smallValue*multiplicand.smallValue, safeLongToInt(newScale)); 942 } 943 return new BigDecimal(this.getUnscaledValue().multiply( 944 multiplicand.getUnscaledValue()), safeLongToInt(newScale)); 945 } 946 947 /** 948 * Returns a new {@code BigDecimal} whose value is {@code this * 949 * multiplicand}. The result is rounded according to the passed context 950 * {@code mc}. 951 * 952 * @param multiplicand 953 * value to be multiplied with {@code this}. 954 * @param mc 955 * rounding mode and precision for the result of this operation. 956 * @return {@code this * multiplicand}. 957 * @throws NullPointerException 958 * if {@code multiplicand == null} or {@code mc == null}. 959 */ 960 public BigDecimal multiply(BigDecimal multiplicand, MathContext mc) { 961 BigDecimal result = multiply(multiplicand); 962 963 result.inplaceRound(mc); 964 return result; 965 } 966 967 /** 968 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 969 * As scale of the result the parameter {@code scale} is used. If rounding 970 * is required to meet the specified scale, then the specified rounding mode 971 * {@code roundingMode} is applied. 972 * 973 * @param divisor 974 * value by which {@code this} is divided. 975 * @param scale 976 * the scale of the result returned. 977 * @param roundingMode 978 * rounding mode to be used to round the result. 979 * @return {@code this / divisor} rounded according to the given rounding 980 * mode. 981 * @throws NullPointerException 982 * if {@code divisor == null}. 983 * @throws IllegalArgumentException 984 * if {@code roundingMode} is not a valid rounding mode. 985 * @throws ArithmeticException 986 * if {@code divisor == 0}. 987 * @throws ArithmeticException 988 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 989 * necessary according to the given scale. 990 */ 991 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { 992 return divide(divisor, scale, RoundingMode.valueOf(roundingMode)); 993 } 994 995 /** 996 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 997 * As scale of the result the parameter {@code scale} is used. If rounding 998 * is required to meet the specified scale, then the specified rounding mode 999 * {@code roundingMode} is applied. 1000 * 1001 * @param divisor 1002 * value by which {@code this} is divided. 1003 * @param scale 1004 * the scale of the result returned. 1005 * @param roundingMode 1006 * rounding mode to be used to round the result. 1007 * @return {@code this / divisor} rounded according to the given rounding 1008 * mode. 1009 * @throws NullPointerException 1010 * if {@code divisor == null} or {@code roundingMode == null}. 1011 * @throws ArithmeticException 1012 * if {@code divisor == 0}. 1013 * @throws ArithmeticException 1014 * if {@code roundingMode == RoundingMode.UNNECESSAR}Y and 1015 * rounding is necessary according to the given scale and given 1016 * precision. 1017 */ 1018 public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) { 1019 // Let be: this = [u1,s1] and divisor = [u2,s2] 1020 if (roundingMode == null) { 1021 throw new NullPointerException("roundingMode == null"); 1022 } 1023 if (divisor.isZero()) { 1024 throw new ArithmeticException("Division by zero"); 1025 } 1026 1027 long diffScale = ((long)this.scale - divisor.scale) - scale; 1028 if(this.bitLength < 64 && divisor.bitLength < 64 ) { 1029 if(diffScale == 0) { 1030 return dividePrimitiveLongs(this.smallValue, 1031 divisor.smallValue, 1032 scale, 1033 roundingMode ); 1034 } else if(diffScale > 0) { 1035 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1036 divisor.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale] < 64) { 1037 return dividePrimitiveLongs(this.smallValue, 1038 divisor.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale], 1039 scale, 1040 roundingMode); 1041 } 1042 } else { // diffScale < 0 1043 if(-diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1044 this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-diffScale] < 64) { 1045 return dividePrimitiveLongs(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], 1046 divisor.smallValue, 1047 scale, 1048 roundingMode); 1049 } 1050 1051 } 1052 } 1053 BigInteger scaledDividend = this.getUnscaledValue(); 1054 BigInteger scaledDivisor = divisor.getUnscaledValue(); // for scaling of 'u2' 1055 1056 if (diffScale > 0) { 1057 // Multiply 'u2' by: 10^((s1 - s2) - scale) 1058 scaledDivisor = Multiplication.multiplyByTenPow(scaledDivisor, (int)diffScale); 1059 } else if (diffScale < 0) { 1060 // Multiply 'u1' by: 10^(scale - (s1 - s2)) 1061 scaledDividend = Multiplication.multiplyByTenPow(scaledDividend, (int)-diffScale); 1062 } 1063 return divideBigIntegers(scaledDividend, scaledDivisor, scale, roundingMode); 1064 } 1065 1066 private static BigDecimal divideBigIntegers(BigInteger scaledDividend, BigInteger scaledDivisor, int scale, RoundingMode roundingMode) { 1067 1068 BigInteger[] quotAndRem = scaledDividend.divideAndRemainder(scaledDivisor); // quotient and remainder 1069 // If after division there is a remainder... 1070 BigInteger quotient = quotAndRem[0]; 1071 BigInteger remainder = quotAndRem[1]; 1072 if (remainder.signum() == 0) { 1073 return new BigDecimal(quotient, scale); 1074 } 1075 int sign = scaledDividend.signum() * scaledDivisor.signum(); 1076 int compRem; // 'compare to remainder' 1077 if(scaledDivisor.bitLength() < 63) { // 63 in order to avoid out of long after *2 1078 long rem = remainder.longValue(); 1079 long divisor = scaledDivisor.longValue(); 1080 compRem = longCompareTo(Math.abs(rem) * 2,Math.abs(divisor)); 1081 // To look if there is a carry 1082 compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0, 1083 sign * (5 + compRem), roundingMode); 1084 1085 } else { 1086 // Checking if: remainder * 2 >= scaledDivisor 1087 compRem = remainder.abs().shiftLeftOneBit().compareTo(scaledDivisor.abs()); 1088 compRem = roundingBehavior(quotient.testBit(0) ? 1 : 0, 1089 sign * (5 + compRem), roundingMode); 1090 } 1091 if (compRem != 0) { 1092 if(quotient.bitLength() < 63) { 1093 return valueOf(quotient.longValue() + compRem,scale); 1094 } 1095 quotient = quotient.add(BigInteger.valueOf(compRem)); 1096 return new BigDecimal(quotient, scale); 1097 } 1098 // Constructing the result with the appropriate unscaled value 1099 return new BigDecimal(quotient, scale); 1100 } 1101 1102 private static BigDecimal dividePrimitiveLongs(long scaledDividend, long scaledDivisor, int scale, RoundingMode roundingMode) { 1103 long quotient = scaledDividend / scaledDivisor; 1104 long remainder = scaledDividend % scaledDivisor; 1105 int sign = Long.signum( scaledDividend ) * Long.signum( scaledDivisor ); 1106 if (remainder != 0) { 1107 // Checking if: remainder * 2 >= scaledDivisor 1108 int compRem; // 'compare to remainder' 1109 compRem = longCompareTo(Math.abs(remainder) * 2,Math.abs(scaledDivisor)); 1110 // To look if there is a carry 1111 quotient += roundingBehavior(((int)quotient) & 1, 1112 sign * (5 + compRem), 1113 roundingMode); 1114 } 1115 // Constructing the result with the appropriate unscaled value 1116 return valueOf(quotient, scale); 1117 } 1118 1119 /** 1120 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1121 * The scale of the result is the scale of {@code this}. If rounding is 1122 * required to meet the specified scale, then the specified rounding mode 1123 * {@code roundingMode} is applied. 1124 * 1125 * @param divisor 1126 * value by which {@code this} is divided. 1127 * @param roundingMode 1128 * rounding mode to be used to round the result. 1129 * @return {@code this / divisor} rounded according to the given rounding 1130 * mode. 1131 * @throws NullPointerException 1132 * if {@code divisor == null}. 1133 * @throws IllegalArgumentException 1134 * if {@code roundingMode} is not a valid rounding mode. 1135 * @throws ArithmeticException 1136 * if {@code divisor == 0}. 1137 * @throws ArithmeticException 1138 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1139 * necessary according to the scale of this. 1140 */ 1141 public BigDecimal divide(BigDecimal divisor, int roundingMode) { 1142 return divide(divisor, scale, RoundingMode.valueOf(roundingMode)); 1143 } 1144 1145 /** 1146 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1147 * The scale of the result is the scale of {@code this}. If rounding is 1148 * required to meet the specified scale, then the specified rounding mode 1149 * {@code roundingMode} is applied. 1150 * 1151 * @param divisor 1152 * value by which {@code this} is divided. 1153 * @param roundingMode 1154 * rounding mode to be used to round the result. 1155 * @return {@code this / divisor} rounded according to the given rounding 1156 * mode. 1157 * @throws NullPointerException 1158 * if {@code divisor == null} or {@code roundingMode == null}. 1159 * @throws ArithmeticException 1160 * if {@code divisor == 0}. 1161 * @throws ArithmeticException 1162 * if {@code roundingMode == RoundingMode.UNNECESSARY} and 1163 * rounding is necessary according to the scale of this. 1164 */ 1165 public BigDecimal divide(BigDecimal divisor, RoundingMode roundingMode) { 1166 return divide(divisor, scale, roundingMode); 1167 } 1168 1169 /** 1170 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1171 * The scale of the result is the difference of the scales of {@code this} 1172 * and {@code divisor}. If the exact result requires more digits, then the 1173 * scale is adjusted accordingly. For example, {@code 1/128 = 0.0078125} 1174 * which has a scale of {@code 7} and precision {@code 5}. 1175 * 1176 * @param divisor 1177 * value by which {@code this} is divided. 1178 * @return {@code this / divisor}. 1179 * @throws NullPointerException 1180 * if {@code divisor == null}. 1181 * @throws ArithmeticException 1182 * if {@code divisor == 0}. 1183 * @throws ArithmeticException 1184 * if the result cannot be represented exactly. 1185 */ 1186 public BigDecimal divide(BigDecimal divisor) { 1187 BigInteger p = this.getUnscaledValue(); 1188 BigInteger q = divisor.getUnscaledValue(); 1189 BigInteger gcd; // greatest common divisor between 'p' and 'q' 1190 BigInteger quotAndRem[]; 1191 long diffScale = (long)scale - divisor.scale; 1192 int newScale; // the new scale for final quotient 1193 int k; // number of factors "2" in 'q' 1194 int l = 0; // number of factors "5" in 'q' 1195 int i = 1; 1196 int lastPow = FIVE_POW.length - 1; 1197 1198 if (divisor.isZero()) { 1199 throw new ArithmeticException("Division by zero"); 1200 } 1201 if (p.signum() == 0) { 1202 return zeroScaledBy(diffScale); 1203 } 1204 // To divide both by the GCD 1205 gcd = p.gcd(q); 1206 p = p.divide(gcd); 1207 q = q.divide(gcd); 1208 // To simplify all "2" factors of q, dividing by 2^k 1209 k = q.getLowestSetBit(); 1210 q = q.shiftRight(k); 1211 // To simplify all "5" factors of q, dividing by 5^l 1212 do { 1213 quotAndRem = q.divideAndRemainder(FIVE_POW[i]); 1214 if (quotAndRem[1].signum() == 0) { 1215 l += i; 1216 if (i < lastPow) { 1217 i++; 1218 } 1219 q = quotAndRem[0]; 1220 } else { 1221 if (i == 1) { 1222 break; 1223 } 1224 i = 1; 1225 } 1226 } while (true); 1227 // If abs(q) != 1 then the quotient is periodic 1228 if (!q.abs().equals(BigInteger.ONE)) { 1229 throw new ArithmeticException("Non-terminating decimal expansion; no exact representable decimal result"); 1230 } 1231 // The sign of the is fixed and the quotient will be saved in 'p' 1232 if (q.signum() < 0) { 1233 p = p.negate(); 1234 } 1235 // Checking if the new scale is out of range 1236 newScale = safeLongToInt(diffScale + Math.max(k, l)); 1237 // k >= 0 and l >= 0 implies that k - l is in the 32-bit range 1238 i = k - l; 1239 1240 p = (i > 0) ? Multiplication.multiplyByFivePow(p, i) 1241 : p.shiftLeft(-i); 1242 return new BigDecimal(p, newScale); 1243 } 1244 1245 /** 1246 * Returns a new {@code BigDecimal} whose value is {@code this / divisor}. 1247 * The result is rounded according to the passed context {@code mc}. If the 1248 * passed math context specifies precision {@code 0}, then this call is 1249 * equivalent to {@code this.divide(divisor)}. 1250 * 1251 * @param divisor 1252 * value by which {@code this} is divided. 1253 * @param mc 1254 * rounding mode and precision for the result of this operation. 1255 * @return {@code this / divisor}. 1256 * @throws NullPointerException 1257 * if {@code divisor == null} or {@code mc == null}. 1258 * @throws ArithmeticException 1259 * if {@code divisor == 0}. 1260 * @throws ArithmeticException 1261 * if {@code mc.getRoundingMode() == UNNECESSARY} and rounding 1262 * is necessary according {@code mc.getPrecision()}. 1263 */ 1264 public BigDecimal divide(BigDecimal divisor, MathContext mc) { 1265 /* Calculating how many zeros must be append to 'dividend' 1266 * to obtain a quotient with at least 'mc.precision()' digits */ 1267 long trailingZeros = mc.getPrecision() + 2L 1268 + divisor.approxPrecision() - approxPrecision(); 1269 long diffScale = (long)scale - divisor.scale; 1270 long newScale = diffScale; // scale of the final quotient 1271 int compRem; // to compare the remainder 1272 int i = 1; // index 1273 int lastPow = TEN_POW.length - 1; // last power of ten 1274 BigInteger integerQuot; // for temporal results 1275 BigInteger quotAndRem[] = {getUnscaledValue()}; 1276 // In special cases it reduces the problem to call the dual method 1277 if ((mc.getPrecision() == 0) || (this.isZero()) 1278 || (divisor.isZero())) { 1279 return this.divide(divisor); 1280 } 1281 if (trailingZeros > 0) { 1282 // To append trailing zeros at end of dividend 1283 quotAndRem[0] = getUnscaledValue().multiply( Multiplication.powerOf10(trailingZeros) ); 1284 newScale += trailingZeros; 1285 } 1286 quotAndRem = quotAndRem[0].divideAndRemainder( divisor.getUnscaledValue() ); 1287 integerQuot = quotAndRem[0]; 1288 // Calculating the exact quotient with at least 'mc.precision()' digits 1289 if (quotAndRem[1].signum() != 0) { 1290 // Checking if: 2 * remainder >= divisor ? 1291 compRem = quotAndRem[1].shiftLeftOneBit().compareTo( divisor.getUnscaledValue() ); 1292 // quot := quot * 10 + r; with 'r' in {-6,-5,-4, 0,+4,+5,+6} 1293 integerQuot = integerQuot.multiply(BigInteger.TEN) 1294 .add(BigInteger.valueOf(quotAndRem[0].signum() * (5 + compRem))); 1295 newScale++; 1296 } else { 1297 // To strip trailing zeros until the preferred scale is reached 1298 while (!integerQuot.testBit(0)) { 1299 quotAndRem = integerQuot.divideAndRemainder(TEN_POW[i]); 1300 if ((quotAndRem[1].signum() == 0) 1301 && (newScale - i >= diffScale)) { 1302 newScale -= i; 1303 if (i < lastPow) { 1304 i++; 1305 } 1306 integerQuot = quotAndRem[0]; 1307 } else { 1308 if (i == 1) { 1309 break; 1310 } 1311 i = 1; 1312 } 1313 } 1314 } 1315 // To perform rounding 1316 return new BigDecimal(integerQuot, safeLongToInt(newScale), mc); 1317 } 1318 1319 /** 1320 * Returns a new {@code BigDecimal} whose value is the integral part of 1321 * {@code this / divisor}. The quotient is rounded down towards zero to the 1322 * next integer. For example, {@code 0.5/0.2 = 2}. 1323 * 1324 * @param divisor 1325 * value by which {@code this} is divided. 1326 * @return integral part of {@code this / divisor}. 1327 * @throws NullPointerException 1328 * if {@code divisor == null}. 1329 * @throws ArithmeticException 1330 * if {@code divisor == 0}. 1331 */ 1332 public BigDecimal divideToIntegralValue(BigDecimal divisor) { 1333 BigInteger integralValue; // the integer of result 1334 BigInteger powerOfTen; // some power of ten 1335 BigInteger quotAndRem[] = {getUnscaledValue()}; 1336 long newScale = (long)this.scale - divisor.scale; 1337 long tempScale = 0; 1338 int i = 1; 1339 int lastPow = TEN_POW.length - 1; 1340 1341 if (divisor.isZero()) { 1342 throw new ArithmeticException("Division by zero"); 1343 } 1344 if ((divisor.approxPrecision() + newScale > this.approxPrecision() + 1L) 1345 || (this.isZero())) { 1346 /* If the divisor's integer part is greater than this's integer part, 1347 * the result must be zero with the appropriate scale */ 1348 integralValue = BigInteger.ZERO; 1349 } else if (newScale == 0) { 1350 integralValue = getUnscaledValue().divide( divisor.getUnscaledValue() ); 1351 } else if (newScale > 0) { 1352 powerOfTen = Multiplication.powerOf10(newScale); 1353 integralValue = getUnscaledValue().divide( divisor.getUnscaledValue().multiply(powerOfTen) ); 1354 integralValue = integralValue.multiply(powerOfTen); 1355 } else {// (newScale < 0) 1356 powerOfTen = Multiplication.powerOf10(-newScale); 1357 integralValue = getUnscaledValue().multiply(powerOfTen).divide( divisor.getUnscaledValue() ); 1358 // To strip trailing zeros approximating to the preferred scale 1359 while (!integralValue.testBit(0)) { 1360 quotAndRem = integralValue.divideAndRemainder(TEN_POW[i]); 1361 if ((quotAndRem[1].signum() == 0) 1362 && (tempScale - i >= newScale)) { 1363 tempScale -= i; 1364 if (i < lastPow) { 1365 i++; 1366 } 1367 integralValue = quotAndRem[0]; 1368 } else { 1369 if (i == 1) { 1370 break; 1371 } 1372 i = 1; 1373 } 1374 } 1375 newScale = tempScale; 1376 } 1377 return ((integralValue.signum() == 0) 1378 ? zeroScaledBy(newScale) 1379 : new BigDecimal(integralValue, safeLongToInt(newScale))); 1380 } 1381 1382 /** 1383 * Returns a new {@code BigDecimal} whose value is the integral part of 1384 * {@code this / divisor}. The quotient is rounded down towards zero to the 1385 * next integer. The rounding mode passed with the parameter {@code mc} is 1386 * not considered. But if the precision of {@code mc > 0} and the integral 1387 * part requires more digits, then an {@code ArithmeticException} is thrown. 1388 * 1389 * @param divisor 1390 * value by which {@code this} is divided. 1391 * @param mc 1392 * math context which determines the maximal precision of the 1393 * result. 1394 * @return integral part of {@code this / divisor}. 1395 * @throws NullPointerException 1396 * if {@code divisor == null} or {@code mc == null}. 1397 * @throws ArithmeticException 1398 * if {@code divisor == 0}. 1399 * @throws ArithmeticException 1400 * if {@code mc.getPrecision() > 0} and the result requires more 1401 * digits to be represented. 1402 */ 1403 public BigDecimal divideToIntegralValue(BigDecimal divisor, MathContext mc) { 1404 int mcPrecision = mc.getPrecision(); 1405 int diffPrecision = this.precision() - divisor.precision(); 1406 int lastPow = TEN_POW.length - 1; 1407 long diffScale = (long)this.scale - divisor.scale; 1408 long newScale = diffScale; 1409 long quotPrecision = diffPrecision - diffScale + 1; 1410 BigInteger quotAndRem[] = new BigInteger[2]; 1411 // In special cases it call the dual method 1412 if ((mcPrecision == 0) || (this.isZero()) || (divisor.isZero())) { 1413 return this.divideToIntegralValue(divisor); 1414 } 1415 // Let be: this = [u1,s1] and divisor = [u2,s2] 1416 if (quotPrecision <= 0) { 1417 quotAndRem[0] = BigInteger.ZERO; 1418 } else if (diffScale == 0) { 1419 // CASE s1 == s2: to calculate u1 / u2 1420 quotAndRem[0] = this.getUnscaledValue().divide( divisor.getUnscaledValue() ); 1421 } else if (diffScale > 0) { 1422 // CASE s1 >= s2: to calculate u1 / (u2 * 10^(s1-s2) 1423 quotAndRem[0] = this.getUnscaledValue().divide( 1424 divisor.getUnscaledValue().multiply(Multiplication.powerOf10(diffScale)) ); 1425 // To chose 10^newScale to get a quotient with at least 'mc.precision()' digits 1426 newScale = Math.min(diffScale, Math.max(mcPrecision - quotPrecision + 1, 0)); 1427 // To calculate: (u1 / (u2 * 10^(s1-s2)) * 10^newScale 1428 quotAndRem[0] = quotAndRem[0].multiply(Multiplication.powerOf10(newScale)); 1429 } else {// CASE s2 > s1: 1430 /* To calculate the minimum power of ten, such that the quotient 1431 * (u1 * 10^exp) / u2 has at least 'mc.precision()' digits. */ 1432 long exp = Math.min(-diffScale, Math.max((long)mcPrecision - diffPrecision, 0)); 1433 long compRemDiv; 1434 // Let be: (u1 * 10^exp) / u2 = [q,r] 1435 quotAndRem = this.getUnscaledValue().multiply(Multiplication.powerOf10(exp)). 1436 divideAndRemainder(divisor.getUnscaledValue()); 1437 newScale += exp; // To fix the scale 1438 exp = -newScale; // The remaining power of ten 1439 // If after division there is a remainder... 1440 if ((quotAndRem[1].signum() != 0) && (exp > 0)) { 1441 // Log10(r) + ((s2 - s1) - exp) > mc.precision ? 1442 compRemDiv = (new BigDecimal(quotAndRem[1])).precision() 1443 + exp - divisor.precision(); 1444 if (compRemDiv == 0) { 1445 // To calculate: (r * 10^exp2) / u2 1446 quotAndRem[1] = quotAndRem[1].multiply(Multiplication.powerOf10(exp)). 1447 divide(divisor.getUnscaledValue()); 1448 compRemDiv = Math.abs(quotAndRem[1].signum()); 1449 } 1450 if (compRemDiv > 0) { 1451 throw new ArithmeticException("Division impossible"); 1452 } 1453 } 1454 } 1455 // Fast return if the quotient is zero 1456 if (quotAndRem[0].signum() == 0) { 1457 return zeroScaledBy(diffScale); 1458 } 1459 BigInteger strippedBI = quotAndRem[0]; 1460 BigDecimal integralValue = new BigDecimal(quotAndRem[0]); 1461 long resultPrecision = integralValue.precision(); 1462 int i = 1; 1463 // To strip trailing zeros until the specified precision is reached 1464 while (!strippedBI.testBit(0)) { 1465 quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]); 1466 if ((quotAndRem[1].signum() == 0) && 1467 ((resultPrecision - i >= mcPrecision) 1468 || (newScale - i >= diffScale)) ) { 1469 resultPrecision -= i; 1470 newScale -= i; 1471 if (i < lastPow) { 1472 i++; 1473 } 1474 strippedBI = quotAndRem[0]; 1475 } else { 1476 if (i == 1) { 1477 break; 1478 } 1479 i = 1; 1480 } 1481 } 1482 // To check if the result fit in 'mc.precision()' digits 1483 if (resultPrecision > mcPrecision) { 1484 throw new ArithmeticException("Division impossible"); 1485 } 1486 integralValue.scale = safeLongToInt(newScale); 1487 integralValue.setUnscaledValue(strippedBI); 1488 return integralValue; 1489 } 1490 1491 /** 1492 * Returns a new {@code BigDecimal} whose value is {@code this % divisor}. 1493 * <p> 1494 * The remainder is defined as {@code this - 1495 * this.divideToIntegralValue(divisor) * divisor}. 1496 * 1497 * @param divisor 1498 * value by which {@code this} is divided. 1499 * @return {@code this % divisor}. 1500 * @throws NullPointerException 1501 * if {@code divisor == null}. 1502 * @throws ArithmeticException 1503 * if {@code divisor == 0}. 1504 */ 1505 public BigDecimal remainder(BigDecimal divisor) { 1506 return divideAndRemainder(divisor)[1]; 1507 } 1508 1509 /** 1510 * Returns a new {@code BigDecimal} whose value is {@code this % divisor}. 1511 * <p> 1512 * The remainder is defined as {@code this - 1513 * this.divideToIntegralValue(divisor) * divisor}. 1514 * <p> 1515 * The specified rounding mode {@code mc} is used for the division only. 1516 * 1517 * @param divisor 1518 * value by which {@code this} is divided. 1519 * @param mc 1520 * rounding mode and precision to be used. 1521 * @return {@code this % divisor}. 1522 * @throws NullPointerException 1523 * if {@code divisor == null}. 1524 * @throws ArithmeticException 1525 * if {@code divisor == 0}. 1526 * @throws ArithmeticException 1527 * if {@code mc.getPrecision() > 0} and the result of {@code 1528 * this.divideToIntegralValue(divisor, mc)} requires more digits 1529 * to be represented. 1530 */ 1531 public BigDecimal remainder(BigDecimal divisor, MathContext mc) { 1532 return divideAndRemainder(divisor, mc)[1]; 1533 } 1534 1535 /** 1536 * Returns a {@code BigDecimal} array which contains the integral part of 1537 * {@code this / divisor} at index 0 and the remainder {@code this % 1538 * divisor} at index 1. The quotient is rounded down towards zero to the 1539 * next integer. 1540 * 1541 * @param divisor 1542 * value by which {@code this} is divided. 1543 * @return {@code [this.divideToIntegralValue(divisor), 1544 * this.remainder(divisor)]}. 1545 * @throws NullPointerException 1546 * if {@code divisor == null}. 1547 * @throws ArithmeticException 1548 * if {@code divisor == 0}. 1549 * @see #divideToIntegralValue 1550 * @see #remainder 1551 */ 1552 public BigDecimal[] divideAndRemainder(BigDecimal divisor) { 1553 BigDecimal quotAndRem[] = new BigDecimal[2]; 1554 1555 quotAndRem[0] = this.divideToIntegralValue(divisor); 1556 quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) ); 1557 return quotAndRem; 1558 } 1559 1560 /** 1561 * Returns a {@code BigDecimal} array which contains the integral part of 1562 * {@code this / divisor} at index 0 and the remainder {@code this % 1563 * divisor} at index 1. The quotient is rounded down towards zero to the 1564 * next integer. The rounding mode passed with the parameter {@code mc} is 1565 * not considered. But if the precision of {@code mc > 0} and the integral 1566 * part requires more digits, then an {@code ArithmeticException} is thrown. 1567 * 1568 * @param divisor 1569 * value by which {@code this} is divided. 1570 * @param mc 1571 * math context which determines the maximal precision of the 1572 * result. 1573 * @return {@code [this.divideToIntegralValue(divisor), 1574 * this.remainder(divisor)]}. 1575 * @throws NullPointerException 1576 * if {@code divisor == null}. 1577 * @throws ArithmeticException 1578 * if {@code divisor == 0}. 1579 * @see #divideToIntegralValue 1580 * @see #remainder 1581 */ 1582 public BigDecimal[] divideAndRemainder(BigDecimal divisor, MathContext mc) { 1583 BigDecimal quotAndRem[] = new BigDecimal[2]; 1584 1585 quotAndRem[0] = this.divideToIntegralValue(divisor, mc); 1586 quotAndRem[1] = this.subtract( quotAndRem[0].multiply(divisor) ); 1587 return quotAndRem; 1588 } 1589 1590 /** 1591 * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The 1592 * scale of the result is {@code n * this.scale()}. 1593 * 1594 * <p>{@code x.pow(0)} returns {@code 1}, even if {@code x == 0}. 1595 * 1596 * <p>Implementation Note: The implementation is based on the ANSI standard 1597 * X3.274-1996 algorithm. 1598 * 1599 * @throws ArithmeticException 1600 * if {@code n < 0} or {@code n > 999999999}. 1601 */ 1602 public BigDecimal pow(int n) { 1603 if (n == 0) { 1604 return ONE; 1605 } 1606 if ((n < 0) || (n > 999999999)) { 1607 throw new ArithmeticException("Invalid operation"); 1608 } 1609 long newScale = scale * (long)n; 1610 // Let be: this = [u,s] so: this^n = [u^n, s*n] 1611 return isZero() ? zeroScaledBy(newScale) 1612 : new BigDecimal(getUnscaledValue().pow(n), safeLongToInt(newScale)); 1613 } 1614 1615 /** 1616 * Returns a new {@code BigDecimal} whose value is {@code this<sup>n</sup>}. The 1617 * result is rounded according to the passed context {@code mc}. 1618 * 1619 * <p>Implementation Note: The implementation is based on the ANSI standard 1620 * X3.274-1996 algorithm. 1621 * 1622 * @param mc 1623 * rounding mode and precision for the result of this operation. 1624 * @throws ArithmeticException 1625 * if {@code n < 0} or {@code n > 999999999}. 1626 */ 1627 public BigDecimal pow(int n, MathContext mc) { 1628 // The ANSI standard X3.274-1996 algorithm 1629 int m = Math.abs(n); 1630 int mcPrecision = mc.getPrecision(); 1631 int elength = (int)Math.log10(m) + 1; // decimal digits in 'n' 1632 int oneBitMask; // mask of bits 1633 BigDecimal accum; // the single accumulator 1634 MathContext newPrecision = mc; // MathContext by default 1635 1636 // In particular cases, it reduces the problem to call the other 'pow()' 1637 if ((n == 0) || ((isZero()) && (n > 0))) { 1638 return pow(n); 1639 } 1640 if ((m > 999999999) || ((mcPrecision == 0) && (n < 0)) 1641 || ((mcPrecision > 0) && (elength > mcPrecision))) { 1642 throw new ArithmeticException("Invalid operation"); 1643 } 1644 if (mcPrecision > 0) { 1645 newPrecision = new MathContext( mcPrecision + elength + 1, 1646 mc.getRoundingMode()); 1647 } 1648 // The result is calculated as if 'n' were positive 1649 accum = round(newPrecision); 1650 oneBitMask = Integer.highestOneBit(m) >> 1; 1651 1652 while (oneBitMask > 0) { 1653 accum = accum.multiply(accum, newPrecision); 1654 if ((m & oneBitMask) == oneBitMask) { 1655 accum = accum.multiply(this, newPrecision); 1656 } 1657 oneBitMask >>= 1; 1658 } 1659 // If 'n' is negative, the value is divided into 'ONE' 1660 if (n < 0) { 1661 accum = ONE.divide(accum, newPrecision); 1662 } 1663 // The final value is rounded to the destination precision 1664 accum.inplaceRound(mc); 1665 return accum; 1666 } 1667 1668 /** 1669 * Returns a {@code BigDecimal} whose value is the absolute value of 1670 * {@code this}. The scale of the result is the same as the scale of this. 1671 */ 1672 public BigDecimal abs() { 1673 return ((signum() < 0) ? negate() : this); 1674 } 1675 1676 /** 1677 * Returns a {@code BigDecimal} whose value is the absolute value of 1678 * {@code this}. The result is rounded according to the passed context 1679 * {@code mc}. 1680 */ 1681 public BigDecimal abs(MathContext mc) { 1682 BigDecimal result = (signum() < 0) ? negate() : new BigDecimal(getUnscaledValue(), scale); 1683 result.inplaceRound(mc); 1684 return result; 1685 } 1686 1687 /** 1688 * Returns a new {@code BigDecimal} whose value is the {@code -this}. The 1689 * scale of the result is the same as the scale of this. 1690 * 1691 * @return {@code -this} 1692 */ 1693 public BigDecimal negate() { 1694 if(bitLength < 63 || (bitLength == 63 && smallValue!=Long.MIN_VALUE)) { 1695 return valueOf(-smallValue,scale); 1696 } 1697 return new BigDecimal(getUnscaledValue().negate(), scale); 1698 } 1699 1700 /** 1701 * Returns a new {@code BigDecimal} whose value is the {@code -this}. The 1702 * result is rounded according to the passed context {@code mc}. 1703 * 1704 * @param mc 1705 * rounding mode and precision for the result of this operation. 1706 * @return {@code -this} 1707 */ 1708 public BigDecimal negate(MathContext mc) { 1709 BigDecimal result = negate(); 1710 result.inplaceRound(mc); 1711 return result; 1712 } 1713 1714 /** 1715 * Returns a new {@code BigDecimal} whose value is {@code +this}. The scale 1716 * of the result is the same as the scale of this. 1717 * 1718 * @return {@code this} 1719 */ 1720 public BigDecimal plus() { 1721 return this; 1722 } 1723 1724 /** 1725 * Returns a new {@code BigDecimal} whose value is {@code +this}. The result 1726 * is rounded according to the passed context {@code mc}. 1727 * 1728 * @param mc 1729 * rounding mode and precision for the result of this operation. 1730 * @return {@code this}, rounded 1731 */ 1732 public BigDecimal plus(MathContext mc) { 1733 return round(mc); 1734 } 1735 1736 /** 1737 * Returns the sign of this {@code BigDecimal}. 1738 * 1739 * @return {@code -1} if {@code this < 0}, 1740 * {@code 0} if {@code this == 0}, 1741 * {@code 1} if {@code this > 0}. 1742 */ 1743 public int signum() { 1744 if( bitLength < 64) { 1745 return Long.signum( this.smallValue ); 1746 } 1747 return getUnscaledValue().signum(); 1748 } 1749 1750 private boolean isZero() { 1751 //Watch out: -1 has a bitLength=0 1752 return bitLength == 0 && this.smallValue != -1; 1753 } 1754 1755 /** 1756 * Returns the scale of this {@code BigDecimal}. The scale is the number of 1757 * digits behind the decimal point. The value of this {@code BigDecimal} is 1758 * the {@code unsignedValue * 10<sup>-scale</sup>}. If the scale is negative, 1759 * then this {@code BigDecimal} represents a big integer. 1760 * 1761 * @return the scale of this {@code BigDecimal}. 1762 */ 1763 public int scale() { 1764 return scale; 1765 } 1766 1767 /** 1768 * Returns the precision of this {@code BigDecimal}. The precision is the 1769 * number of decimal digits used to represent this decimal. It is equivalent 1770 * to the number of digits of the unscaled value. The precision of {@code 0} 1771 * is {@code 1} (independent of the scale). 1772 * 1773 * @return the precision of this {@code BigDecimal}. 1774 */ 1775 public int precision() { 1776 // Return the cached value if we have one. 1777 if (precision != 0) { 1778 return precision; 1779 } 1780 1781 if (bitLength == 0) { 1782 precision = 1; 1783 } else if (bitLength < 64) { 1784 precision = decimalDigitsInLong(smallValue); 1785 } else { 1786 int decimalDigits = 1 + (int) ((bitLength - 1) * LOG10_2); 1787 // If after division the number isn't zero, there exists an additional digit 1788 if (getUnscaledValue().divide(Multiplication.powerOf10(decimalDigits)).signum() != 0) { 1789 decimalDigits++; 1790 } 1791 precision = decimalDigits; 1792 } 1793 return precision; 1794 } 1795 1796 private int decimalDigitsInLong(long value) { 1797 if (value == Long.MIN_VALUE) { 1798 return 19; // special case required because abs(MIN_VALUE) == MIN_VALUE 1799 } else { 1800 int index = Arrays.binarySearch(MathUtils.LONG_POWERS_OF_TEN, Math.abs(value)); 1801 return (index < 0) ? (-index - 1) : (index + 1); 1802 } 1803 } 1804 1805 /** 1806 * Returns the unscaled value (mantissa) of this {@code BigDecimal} instance 1807 * as a {@code BigInteger}. The unscaled value can be computed as 1808 * {@code this * 10<sup>scale</sup>}. 1809 */ 1810 public BigInteger unscaledValue() { 1811 return getUnscaledValue(); 1812 } 1813 1814 /** 1815 * Returns a new {@code BigDecimal} whose value is {@code this}, rounded 1816 * according to the passed context {@code mc}. 1817 * <p> 1818 * If {@code mc.precision = 0}, then no rounding is performed. 1819 * <p> 1820 * If {@code mc.precision > 0} and {@code mc.roundingMode == UNNECESSARY}, 1821 * then an {@code ArithmeticException} is thrown if the result cannot be 1822 * represented exactly within the given precision. 1823 * 1824 * @param mc 1825 * rounding mode and precision for the result of this operation. 1826 * @return {@code this} rounded according to the passed context. 1827 * @throws ArithmeticException 1828 * if {@code mc.precision > 0} and {@code mc.roundingMode == 1829 * UNNECESSARY} and this cannot be represented within the given 1830 * precision. 1831 */ 1832 public BigDecimal round(MathContext mc) { 1833 BigDecimal thisBD = new BigDecimal(getUnscaledValue(), scale); 1834 1835 thisBD.inplaceRound(mc); 1836 return thisBD; 1837 } 1838 1839 /** 1840 * Returns a new {@code BigDecimal} instance with the specified scale. 1841 * <p> 1842 * If the new scale is greater than the old scale, then additional zeros are 1843 * added to the unscaled value. In this case no rounding is necessary. 1844 * <p> 1845 * If the new scale is smaller than the old scale, then trailing digits are 1846 * removed. If these trailing digits are not zero, then the remaining 1847 * unscaled value has to be rounded. For this rounding operation the 1848 * specified rounding mode is used. 1849 * 1850 * @param newScale 1851 * scale of the result returned. 1852 * @param roundingMode 1853 * rounding mode to be used to round the result. 1854 * @return a new {@code BigDecimal} instance with the specified scale. 1855 * @throws NullPointerException 1856 * if {@code roundingMode == null}. 1857 * @throws ArithmeticException 1858 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1859 * necessary according to the given scale. 1860 */ 1861 public BigDecimal setScale(int newScale, RoundingMode roundingMode) { 1862 if (roundingMode == null) { 1863 throw new NullPointerException("roundingMode == null"); 1864 } 1865 long diffScale = newScale - (long)scale; 1866 // Let be: 'this' = [u,s] 1867 if(diffScale == 0) { 1868 return this; 1869 } 1870 if(diffScale > 0) { 1871 // return [u * 10^(s2 - s), newScale] 1872 if(diffScale < MathUtils.LONG_POWERS_OF_TEN.length && 1873 (this.bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)diffScale]) < 64 ) { 1874 return valueOf(this.smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)diffScale],newScale); 1875 } 1876 return new BigDecimal(Multiplication.multiplyByTenPow(getUnscaledValue(),(int)diffScale), newScale); 1877 } 1878 // diffScale < 0 1879 // return [u,s] / [1,newScale] with the appropriate scale and rounding 1880 if(this.bitLength < 64 && -diffScale < MathUtils.LONG_POWERS_OF_TEN.length) { 1881 return dividePrimitiveLongs(this.smallValue, MathUtils.LONG_POWERS_OF_TEN[(int)-diffScale], newScale,roundingMode); 1882 } 1883 return divideBigIntegers(this.getUnscaledValue(),Multiplication.powerOf10(-diffScale),newScale,roundingMode); 1884 } 1885 1886 /** 1887 * Returns a new {@code BigDecimal} instance with the specified scale. 1888 * <p> 1889 * If the new scale is greater than the old scale, then additional zeros are 1890 * added to the unscaled value. In this case no rounding is necessary. 1891 * <p> 1892 * If the new scale is smaller than the old scale, then trailing digits are 1893 * removed. If these trailing digits are not zero, then the remaining 1894 * unscaled value has to be rounded. For this rounding operation the 1895 * specified rounding mode is used. 1896 * 1897 * @param newScale 1898 * scale of the result returned. 1899 * @param roundingMode 1900 * rounding mode to be used to round the result. 1901 * @return a new {@code BigDecimal} instance with the specified scale. 1902 * @throws IllegalArgumentException 1903 * if {@code roundingMode} is not a valid rounding mode. 1904 * @throws ArithmeticException 1905 * if {@code roundingMode == ROUND_UNNECESSARY} and rounding is 1906 * necessary according to the given scale. 1907 */ 1908 public BigDecimal setScale(int newScale, int roundingMode) { 1909 return setScale(newScale, RoundingMode.valueOf(roundingMode)); 1910 } 1911 1912 /** 1913 * Returns a new {@code BigDecimal} instance with the specified scale. If 1914 * the new scale is greater than the old scale, then additional zeros are 1915 * added to the unscaled value. If the new scale is smaller than the old 1916 * scale, then trailing zeros are removed. If the trailing digits are not 1917 * zeros then an ArithmeticException is thrown. 1918 * <p> 1919 * If no exception is thrown, then the following equation holds: {@code 1920 * x.setScale(s).compareTo(x) == 0}. 1921 * 1922 * @param newScale 1923 * scale of the result returned. 1924 * @return a new {@code BigDecimal} instance with the specified scale. 1925 * @throws ArithmeticException 1926 * if rounding would be necessary. 1927 */ 1928 public BigDecimal setScale(int newScale) { 1929 return setScale(newScale, RoundingMode.UNNECESSARY); 1930 } 1931 1932 /** 1933 * Returns a new {@code BigDecimal} instance where the decimal point has 1934 * been moved {@code n} places to the left. If {@code n < 0} then the 1935 * decimal point is moved {@code -n} places to the right. 1936 * 1937 * <p>The result is obtained by changing its scale. If the scale of the result 1938 * becomes negative, then its precision is increased such that the scale is 1939 * zero. 1940 * 1941 * <p>Note, that {@code movePointLeft(0)} returns a result which is 1942 * mathematically equivalent, but which has {@code scale >= 0}. 1943 */ 1944 public BigDecimal movePointLeft(int n) { 1945 return movePoint(scale + (long)n); 1946 } 1947 1948 private BigDecimal movePoint(long newScale) { 1949 if (isZero()) { 1950 return zeroScaledBy(Math.max(newScale, 0)); 1951 } 1952 /* 1953 * When: 'n'== Integer.MIN_VALUE isn't possible to call to 1954 * movePointRight(-n) since -Integer.MIN_VALUE == Integer.MIN_VALUE 1955 */ 1956 if(newScale >= 0) { 1957 if(bitLength < 64) { 1958 return valueOf(smallValue, safeLongToInt(newScale)); 1959 } 1960 return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale)); 1961 } 1962 if(-newScale < MathUtils.LONG_POWERS_OF_TEN.length && 1963 bitLength + LONG_POWERS_OF_TEN_BIT_LENGTH[(int)-newScale] < 64 ) { 1964 return valueOf(smallValue*MathUtils.LONG_POWERS_OF_TEN[(int)-newScale],0); 1965 } 1966 return new BigDecimal(Multiplication.multiplyByTenPow( 1967 getUnscaledValue(), safeLongToInt(-newScale)), 0); 1968 } 1969 1970 /** 1971 * Returns a new {@code BigDecimal} instance where the decimal point has 1972 * been moved {@code n} places to the right. If {@code n < 0} then the 1973 * decimal point is moved {@code -n} places to the left. 1974 * 1975 * <p>The result is obtained by changing its scale. If the scale of the result 1976 * becomes negative, then its precision is increased such that the scale is 1977 * zero. 1978 * 1979 * <p>Note, that {@code movePointRight(0)} returns a result which is 1980 * mathematically equivalent, but which has scale >= 0. 1981 */ 1982 public BigDecimal movePointRight(int n) { 1983 return movePoint(scale - (long)n); 1984 } 1985 1986 /** 1987 * Returns a new {@code BigDecimal} whose value is {@code this * 10<sup>n</sup>}. 1988 * The scale of the result is {@code this.scale()} - {@code n}. 1989 * The precision of the result is the precision of {@code this}. 1990 * 1991 * <p>This method has the same effect as {@link #movePointRight}, except that 1992 * the precision is not changed. 1993 */ 1994 public BigDecimal scaleByPowerOfTen(int n) { 1995 long newScale = scale - (long)n; 1996 if(bitLength < 64) { 1997 //Taking care when a 0 is to be scaled 1998 if( smallValue==0 ){ 1999 return zeroScaledBy( newScale ); 2000 } 2001 return valueOf(smallValue, safeLongToInt(newScale)); 2002 } 2003 return new BigDecimal(getUnscaledValue(), safeLongToInt(newScale)); 2004 } 2005 2006 /** 2007 * Returns a new {@code BigDecimal} instance with the same value as {@code 2008 * this} but with a unscaled value where the trailing zeros have been 2009 * removed. If the unscaled value of {@code this} has n trailing zeros, then 2010 * the scale and the precision of the result has been reduced by n. 2011 * 2012 * @return a new {@code BigDecimal} instance equivalent to this where the 2013 * trailing zeros of the unscaled value have been removed. 2014 */ 2015 public BigDecimal stripTrailingZeros() { 2016 int i = 1; // 1 <= i <= 18 2017 int lastPow = TEN_POW.length - 1; 2018 long newScale = scale; 2019 2020 if (isZero()) { 2021 // Preserve RI compatibility, so BigDecimal.equals (which checks 2022 // value *and* scale) continues to work. 2023 return this; 2024 } 2025 BigInteger strippedBI = getUnscaledValue(); 2026 BigInteger[] quotAndRem; 2027 2028 // while the number is even... 2029 while (!strippedBI.testBit(0)) { 2030 // To divide by 10^i 2031 quotAndRem = strippedBI.divideAndRemainder(TEN_POW[i]); 2032 // To look the remainder 2033 if (quotAndRem[1].signum() == 0) { 2034 // To adjust the scale 2035 newScale -= i; 2036 if (i < lastPow) { 2037 // To set to the next power 2038 i++; 2039 } 2040 strippedBI = quotAndRem[0]; 2041 } else { 2042 if (i == 1) { 2043 // 'this' has no more trailing zeros 2044 break; 2045 } 2046 // To set to the smallest power of ten 2047 i = 1; 2048 } 2049 } 2050 return new BigDecimal(strippedBI, safeLongToInt(newScale)); 2051 } 2052 2053 /** 2054 * Compares this {@code BigDecimal} with {@code val}. Returns one of the 2055 * three values {@code 1}, {@code 0}, or {@code -1}. The method behaves as 2056 * if {@code this.subtract(val)} is computed. If this difference is > 0 then 2057 * 1 is returned, if the difference is < 0 then -1 is returned, and if the 2058 * difference is 0 then 0 is returned. This means, that if two decimal 2059 * instances are compared which are equal in value but differ in scale, then 2060 * these two instances are considered as equal. 2061 * 2062 * @param val 2063 * value to be compared with {@code this}. 2064 * @return {@code 1} if {@code this > val}, {@code -1} if {@code this < val}, 2065 * {@code 0} if {@code this == val}. 2066 * @throws NullPointerException 2067 * if {@code val == null}. 2068 */ 2069 public int compareTo(BigDecimal val) { 2070 int thisSign = signum(); 2071 int valueSign = val.signum(); 2072 2073 if( thisSign == valueSign) { 2074 if(this.scale == val.scale && this.bitLength<64 && val.bitLength<64 ) { 2075 return (smallValue < val.smallValue) ? -1 : (smallValue > val.smallValue) ? 1 : 0; 2076 } 2077 long diffScale = (long)this.scale - val.scale; 2078 int diffPrecision = this.approxPrecision() - val.approxPrecision(); 2079 if (diffPrecision > diffScale + 1) { 2080 return thisSign; 2081 } else if (diffPrecision < diffScale - 1) { 2082 return -thisSign; 2083 } else {// thisSign == val.signum() and diffPrecision is aprox. diffScale 2084 BigInteger thisUnscaled = this.getUnscaledValue(); 2085 BigInteger valUnscaled = val.getUnscaledValue(); 2086 // If any of both precision is bigger, append zeros to the shorter one 2087 if (diffScale < 0) { 2088 thisUnscaled = thisUnscaled.multiply(Multiplication.powerOf10(-diffScale)); 2089 } else if (diffScale > 0) { 2090 valUnscaled = valUnscaled.multiply(Multiplication.powerOf10(diffScale)); 2091 } 2092 return thisUnscaled.compareTo(valUnscaled); 2093 } 2094 } else if (thisSign < valueSign) { 2095 return -1; 2096 } else { 2097 return 1; 2098 } 2099 } 2100 2101 /** 2102 * Returns {@code true} if {@code x} is a {@code BigDecimal} instance and if 2103 * this instance is equal to this big decimal. Two big decimals are equal if 2104 * their unscaled value and their scale is equal. For example, 1.0 2105 * (10*10<sup>-1</sup>) is not equal to 1.00 (100*10<sup>-2</sup>). Similarly, zero 2106 * instances are not equal if their scale differs. 2107 */ 2108 @Override 2109 public boolean equals(Object x) { 2110 if (this == x) { 2111 return true; 2112 } 2113 if (x instanceof BigDecimal) { 2114 BigDecimal x1 = (BigDecimal) x; 2115 return x1.scale == scale 2116 && (bitLength < 64 ? (x1.smallValue == smallValue) 2117 : intVal.equals(x1.intVal)); 2118 } 2119 return false; 2120 } 2121 2122 /** 2123 * Returns the minimum of this {@code BigDecimal} and {@code val}. 2124 * 2125 * @param val 2126 * value to be used to compute the minimum with this. 2127 * @return {@code min(this, val}. 2128 * @throws NullPointerException 2129 * if {@code val == null}. 2130 */ 2131 public BigDecimal min(BigDecimal val) { 2132 return ((compareTo(val) <= 0) ? this : val); 2133 } 2134 2135 /** 2136 * Returns the maximum of this {@code BigDecimal} and {@code val}. 2137 * 2138 * @param val 2139 * value to be used to compute the maximum with this. 2140 * @return {@code max(this, val}. 2141 * @throws NullPointerException 2142 * if {@code val == null}. 2143 */ 2144 public BigDecimal max(BigDecimal val) { 2145 return ((compareTo(val) >= 0) ? this : val); 2146 } 2147 2148 /** 2149 * Returns a hash code for this {@code BigDecimal}. 2150 * 2151 * @return hash code for {@code this}. 2152 */ 2153 @Override 2154 public int hashCode() { 2155 if (hashCode != 0) { 2156 return hashCode; 2157 } 2158 if (bitLength < 64) { 2159 hashCode = (int)(smallValue & 0xffffffff); 2160 hashCode = 33 * hashCode + (int)((smallValue >> 32) & 0xffffffff); 2161 hashCode = 17 * hashCode + scale; 2162 return hashCode; 2163 } 2164 hashCode = 17 * intVal.hashCode() + scale; 2165 return hashCode; 2166 } 2167 2168 /** 2169 * Returns a canonical string representation of this {@code BigDecimal}. If 2170 * necessary, scientific notation is used. This representation always prints 2171 * all significant digits of this value. 2172 * <p> 2173 * If the scale is negative or if {@code scale - precision >= 6} then 2174 * scientific notation is used. 2175 * 2176 * @return a string representation of {@code this} in scientific notation if 2177 * necessary. 2178 */ 2179 @Override 2180 public String toString() { 2181 if (toStringImage != null) { 2182 return toStringImage; 2183 } 2184 if(bitLength < 32) { 2185 toStringImage = Conversion.toDecimalScaledString(smallValue,scale); 2186 return toStringImage; 2187 } 2188 String intString = getUnscaledValue().toString(); 2189 if (scale == 0) { 2190 return intString; 2191 } 2192 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2193 int end = intString.length(); 2194 long exponent = -(long)scale + end - begin; 2195 StringBuilder result = new StringBuilder(); 2196 2197 result.append(intString); 2198 if ((scale > 0) && (exponent >= -6)) { 2199 if (exponent >= 0) { 2200 result.insert(end - scale, '.'); 2201 } else { 2202 result.insert(begin - 1, "0."); 2203 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2204 } 2205 } else { 2206 if (end - begin >= 1) { 2207 result.insert(begin, '.'); 2208 end++; 2209 } 2210 result.insert(end, 'E'); 2211 if (exponent > 0) { 2212 result.insert(++end, '+'); 2213 } 2214 result.insert(++end, Long.toString(exponent)); 2215 } 2216 toStringImage = result.toString(); 2217 return toStringImage; 2218 } 2219 2220 /** 2221 * Returns a string representation of this {@code BigDecimal}. This 2222 * representation always prints all significant digits of this value. 2223 * <p> 2224 * If the scale is negative or if {@code scale - precision >= 6} then 2225 * engineering notation is used. Engineering notation is similar to the 2226 * scientific notation except that the exponent is made to be a multiple of 2227 * 3 such that the integer part is >= 1 and < 1000. 2228 * 2229 * @return a string representation of {@code this} in engineering notation 2230 * if necessary. 2231 */ 2232 public String toEngineeringString() { 2233 String intString = getUnscaledValue().toString(); 2234 if (scale == 0) { 2235 return intString; 2236 } 2237 int begin = (getUnscaledValue().signum() < 0) ? 2 : 1; 2238 int end = intString.length(); 2239 long exponent = -(long)scale + end - begin; 2240 StringBuilder result = new StringBuilder(intString); 2241 2242 if ((scale > 0) && (exponent >= -6)) { 2243 if (exponent >= 0) { 2244 result.insert(end - scale, '.'); 2245 } else { 2246 result.insert(begin - 1, "0."); 2247 result.insert(begin + 1, CH_ZEROS, 0, -(int)exponent - 1); 2248 } 2249 } else { 2250 int delta = end - begin; 2251 int rem = (int)(exponent % 3); 2252 2253 if (rem != 0) { 2254 // adjust exponent so it is a multiple of three 2255 if (getUnscaledValue().signum() == 0) { 2256 // zero value 2257 rem = (rem < 0) ? -rem : 3 - rem; 2258 exponent += rem; 2259 } else { 2260 // nonzero value 2261 rem = (rem < 0) ? rem + 3 : rem; 2262 exponent -= rem; 2263 begin += rem; 2264 } 2265 if (delta < 3) { 2266 for (int i = rem - delta; i > 0; i--) { 2267 result.insert(end++, '0'); 2268 } 2269 } 2270 } 2271 if (end - begin >= 1) { 2272 result.insert(begin, '.'); 2273 end++; 2274 } 2275 if (exponent != 0) { 2276 result.insert(end, 'E'); 2277 if (exponent > 0) { 2278 result.insert(++end, '+'); 2279 } 2280 result.insert(++end, Long.toString(exponent)); 2281 } 2282 } 2283 return result.toString(); 2284 } 2285 2286 /** 2287 * Returns a string representation of this {@code BigDecimal}. No scientific 2288 * notation is used. This methods adds zeros where necessary. 2289 * <p> 2290 * If this string representation is used to create a new instance, this 2291 * instance is generally not identical to {@code this} as the precision 2292 * changes. 2293 * <p> 2294 * {@code x.equals(new BigDecimal(x.toPlainString())} usually returns 2295 * {@code false}. 2296 * <p> 2297 * {@code x.compareTo(new BigDecimal(x.toPlainString())} returns {@code 0}. 2298 * 2299 * @return a string representation of {@code this} without exponent part. 2300 */ 2301 public String toPlainString() { 2302 String intStr = getUnscaledValue().toString(); 2303 if ((scale == 0) || ((isZero()) && (scale < 0))) { 2304 return intStr; 2305 } 2306 int begin = (signum() < 0) ? 1 : 0; 2307 int delta = scale; 2308 // We take space for all digits, plus a possible decimal point, plus 'scale' 2309 StringBuilder result = new StringBuilder(intStr.length() + 1 + Math.abs(scale)); 2310 2311 if (begin == 1) { 2312 // If the number is negative, we insert a '-' character at front 2313 result.append('-'); 2314 } 2315 if (scale > 0) { 2316 delta -= (intStr.length() - begin); 2317 if (delta >= 0) { 2318 result.append("0."); 2319 // To append zeros after the decimal point 2320 for (; delta > CH_ZEROS.length; delta -= CH_ZEROS.length) { 2321 result.append(CH_ZEROS); 2322 } 2323 result.append(CH_ZEROS, 0, delta); 2324 result.append(intStr.substring(begin)); 2325 } else { 2326 delta = begin - delta; 2327 result.append(intStr.substring(begin, delta)); 2328 result.append('.'); 2329 result.append(intStr.substring(delta)); 2330 } 2331 } else {// (scale <= 0) 2332 result.append(intStr.substring(begin)); 2333 // To append trailing zeros 2334 for (; delta < -CH_ZEROS.length; delta += CH_ZEROS.length) { 2335 result.append(CH_ZEROS); 2336 } 2337 result.append(CH_ZEROS, 0, -delta); 2338 } 2339 return result.toString(); 2340 } 2341 2342 /** 2343 * Returns this {@code BigDecimal} as a big integer instance. A fractional 2344 * part is discarded. 2345 * 2346 * @return this {@code BigDecimal} as a big integer instance. 2347 */ 2348 public BigInteger toBigInteger() { 2349 if ((scale == 0) || (isZero())) { 2350 return getUnscaledValue(); 2351 } else if (scale < 0) { 2352 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2353 } else {// (scale > 0) 2354 return getUnscaledValue().divide(Multiplication.powerOf10(scale)); 2355 } 2356 } 2357 2358 /** 2359 * Returns this {@code BigDecimal} as a big integer instance if it has no 2360 * fractional part. If this {@code BigDecimal} has a fractional part, i.e. 2361 * if rounding would be necessary, an {@code ArithmeticException} is thrown. 2362 * 2363 * @return this {@code BigDecimal} as a big integer value. 2364 * @throws ArithmeticException 2365 * if rounding is necessary. 2366 */ 2367 public BigInteger toBigIntegerExact() { 2368 if ((scale == 0) || (isZero())) { 2369 return getUnscaledValue(); 2370 } else if (scale < 0) { 2371 return getUnscaledValue().multiply(Multiplication.powerOf10(-(long)scale)); 2372 } else {// (scale > 0) 2373 BigInteger[] integerAndFraction; 2374 // An optimization before do a heavy division 2375 if ((scale > approxPrecision()) || (scale > getUnscaledValue().getLowestSetBit())) { 2376 throw new ArithmeticException("Rounding necessary"); 2377 } 2378 integerAndFraction = getUnscaledValue().divideAndRemainder(Multiplication.powerOf10(scale)); 2379 if (integerAndFraction[1].signum() != 0) { 2380 // It exists a non-zero fractional part 2381 throw new ArithmeticException("Rounding necessary"); 2382 } 2383 return integerAndFraction[0]; 2384 } 2385 } 2386 2387 /** 2388 * Returns this {@code BigDecimal} as an long value. Any fractional part is 2389 * discarded. If the integral part of {@code this} is too big to be 2390 * represented as an long, then {@code this % 2<sup>64</sup>} is returned. 2391 */ 2392 @Override 2393 public long longValue() { 2394 /* 2395 * If scale <= -64 there are at least 64 trailing bits zero in 2396 * 10^(-scale). If the scale is positive and very large the long value 2397 * could be zero. 2398 */ 2399 return ((scale <= -64) || (scale > approxPrecision()) ? 0L : toBigInteger().longValue()); 2400 } 2401 2402 /** 2403 * Returns this {@code BigDecimal} as a long value if it has no fractional 2404 * part and if its value fits to the int range ([-2<sup>63</sup>..2<sup>63</sup>-1]). If 2405 * these conditions are not met, an {@code ArithmeticException} is thrown. 2406 * 2407 * @throws ArithmeticException 2408 * if rounding is necessary or the number doesn't fit in a long. 2409 */ 2410 public long longValueExact() { 2411 return valueExact(64); 2412 } 2413 2414 /** 2415 * Returns this {@code BigDecimal} as an int value. Any fractional part is 2416 * discarded. If the integral part of {@code this} is too big to be 2417 * represented as an int, then {@code this % 2<sup>32</sup>} is returned. 2418 */ 2419 @Override 2420 public int intValue() { 2421 /* 2422 * If scale <= -32 there are at least 32 trailing bits zero in 2423 * 10^(-scale). If the scale is positive and very large the long value 2424 * could be zero. 2425 */ 2426 return ((scale <= -32) || (scale > approxPrecision()) ? 0 : toBigInteger().intValue()); 2427 } 2428 2429 /** 2430 * Returns this {@code BigDecimal} as a int value if it has no fractional 2431 * part and if its value fits to the int range ([-2<sup>31</sup>..2<sup>31</sup>-1]). If 2432 * these conditions are not met, an {@code ArithmeticException} is thrown. 2433 * 2434 * @throws ArithmeticException 2435 * if rounding is necessary or the number doesn't fit in an int. 2436 */ 2437 public int intValueExact() { 2438 return (int) valueExact(32); 2439 } 2440 2441 /** 2442 * Returns this {@code BigDecimal} as a short value if it has no fractional 2443 * part and if its value fits to the short range ([-2<sup>15</sup>..2<sup>15</sup>-1]). If 2444 * these conditions are not met, an {@code ArithmeticException} is thrown. 2445 * 2446 * @throws ArithmeticException 2447 * if rounding is necessary of the number doesn't fit in a short. 2448 */ 2449 public short shortValueExact() { 2450 return (short) valueExact(16); 2451 } 2452 2453 /** 2454 * Returns this {@code BigDecimal} as a byte value if it has no fractional 2455 * part and if its value fits to the byte range ([-128..127]). If these 2456 * conditions are not met, an {@code ArithmeticException} is thrown. 2457 * 2458 * @throws ArithmeticException 2459 * if rounding is necessary or the number doesn't fit in a byte. 2460 */ 2461 public byte byteValueExact() { 2462 return (byte) valueExact(8); 2463 } 2464 2465 /** 2466 * Returns this {@code BigDecimal} as a float value. If {@code this} is too 2467 * big to be represented as an float, then {@code Float.POSITIVE_INFINITY} 2468 * or {@code Float.NEGATIVE_INFINITY} is returned. 2469 * <p> 2470 * Note, that if the unscaled value has more than 24 significant digits, 2471 * then this decimal cannot be represented exactly in a float variable. In 2472 * this case the result is rounded. 2473 * <p> 2474 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2475 * represented exactly as a float, and thus {@code x1.equals(new 2476 * BigDecimal(x1.floatValue())} returns {@code false} for this case. 2477 * <p> 2478 * Similarly, if the instance {@code new BigDecimal(16777217)} is converted 2479 * to a float, the result is {@code 1.6777216E}7. 2480 * 2481 * @return this {@code BigDecimal} as a float value. 2482 */ 2483 @Override 2484 public float floatValue() { 2485 /* A similar code like in doubleValue() could be repeated here, 2486 * but this simple implementation is quite efficient. */ 2487 float floatResult = signum(); 2488 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2489 if ((powerOfTwo < -149) || (floatResult == 0.0f)) { 2490 // Cases which 'this' is very small 2491 floatResult *= 0.0f; 2492 } else if (powerOfTwo > 129) { 2493 // Cases which 'this' is very large 2494 floatResult *= Float.POSITIVE_INFINITY; 2495 } else { 2496 floatResult = (float)doubleValue(); 2497 } 2498 return floatResult; 2499 } 2500 2501 /** 2502 * Returns this {@code BigDecimal} as a double value. If {@code this} is too 2503 * big to be represented as an float, then {@code Double.POSITIVE_INFINITY} 2504 * or {@code Double.NEGATIVE_INFINITY} is returned. 2505 * <p> 2506 * Note, that if the unscaled value has more than 53 significant digits, 2507 * then this decimal cannot be represented exactly in a double variable. In 2508 * this case the result is rounded. 2509 * <p> 2510 * For example, if the instance {@code x1 = new BigDecimal("0.1")} cannot be 2511 * represented exactly as a double, and thus {@code x1.equals(new 2512 * BigDecimal(x1.doubleValue())} returns {@code false} for this case. 2513 * <p> 2514 * Similarly, if the instance {@code new BigDecimal(9007199254740993L)} is 2515 * converted to a double, the result is {@code 9.007199254740992E15}. 2516 * <p> 2517 * 2518 * @return this {@code BigDecimal} as a double value. 2519 */ 2520 @Override 2521 public double doubleValue() { 2522 int sign = signum(); 2523 int exponent = 1076; // bias + 53 2524 int lowestSetBit; 2525 int discardedSize; 2526 long powerOfTwo = this.bitLength - (long)(scale / LOG10_2); 2527 long bits; // IEEE-754 Standard 2528 long tempBits; // for temporal calculations 2529 BigInteger mantissa; 2530 2531 if ((powerOfTwo < -1074) || (sign == 0)) { 2532 // Cases which 'this' is very small 2533 return (sign * 0.0d); 2534 } else if (powerOfTwo > 1025) { 2535 // Cases which 'this' is very large 2536 return (sign * Double.POSITIVE_INFINITY); 2537 } 2538 mantissa = getUnscaledValue().abs(); 2539 // Let be: this = [u,s], with s > 0 2540 if (scale <= 0) { 2541 // mantissa = abs(u) * 10^s 2542 mantissa = mantissa.multiply(Multiplication.powerOf10(-scale)); 2543 } else {// (scale > 0) 2544 BigInteger quotAndRem[]; 2545 BigInteger powerOfTen = Multiplication.powerOf10(scale); 2546 int k = 100 - (int)powerOfTwo; 2547 int compRem; 2548 2549 if (k > 0) { 2550 /* Computing (mantissa * 2^k) , where 'k' is a enough big 2551 * power of '2' to can divide by 10^s */ 2552 mantissa = mantissa.shiftLeft(k); 2553 exponent -= k; 2554 } 2555 // Computing (mantissa * 2^k) / 10^s 2556 quotAndRem = mantissa.divideAndRemainder(powerOfTen); 2557 // To check if the fractional part >= 0.5 2558 compRem = quotAndRem[1].shiftLeftOneBit().compareTo(powerOfTen); 2559 // To add two rounded bits at end of mantissa 2560 mantissa = quotAndRem[0].shiftLeft(2).add( 2561 BigInteger.valueOf((compRem * (compRem + 3)) / 2 + 1)); 2562 exponent -= 2; 2563 } 2564 lowestSetBit = mantissa.getLowestSetBit(); 2565 discardedSize = mantissa.bitLength() - 54; 2566 if (discardedSize > 0) {// (n > 54) 2567 // mantissa = (abs(u) * 10^s) >> (n - 54) 2568 bits = mantissa.shiftRight(discardedSize).longValue(); 2569 tempBits = bits; 2570 // #bits = 54, to check if the discarded fraction produces a carry 2571 if ((((bits & 1) == 1) && (lowestSetBit < discardedSize)) 2572 || ((bits & 3) == 3)) { 2573 bits += 2; 2574 } 2575 } else {// (n <= 54) 2576 // mantissa = (abs(u) * 10^s) << (54 - n) 2577 bits = mantissa.longValue() << -discardedSize; 2578 tempBits = bits; 2579 // #bits = 54, to check if the discarded fraction produces a carry: 2580 if ((bits & 3) == 3) { 2581 bits += 2; 2582 } 2583 } 2584 // Testing bit 54 to check if the carry creates a new binary digit 2585 if ((bits & 0x40000000000000L) == 0) { 2586 // To drop the last bit of mantissa (first discarded) 2587 bits >>= 1; 2588 // exponent = 2^(s-n+53+bias) 2589 exponent += discardedSize; 2590 } else {// #bits = 54 2591 bits >>= 2; 2592 exponent += discardedSize + 1; 2593 } 2594 // To test if the 53-bits number fits in 'double' 2595 if (exponent > 2046) {// (exponent - bias > 1023) 2596 return (sign * Double.POSITIVE_INFINITY); 2597 } else if (exponent <= 0) {// (exponent - bias <= -1023) 2598 // Denormalized numbers (having exponent == 0) 2599 if (exponent < -53) {// exponent - bias < -1076 2600 return (sign * 0.0d); 2601 } 2602 // -1076 <= exponent - bias <= -1023 2603 // To discard '- exponent + 1' bits 2604 bits = tempBits >> 1; 2605 tempBits = bits & (-1L >>> (63 + exponent)); 2606 bits >>= (-exponent ); 2607 // To test if after discard bits, a new carry is generated 2608 if (((bits & 3) == 3) || (((bits & 1) == 1) && (tempBits != 0) 2609 && (lowestSetBit < discardedSize))) { 2610 bits += 1; 2611 } 2612 exponent = 0; 2613 bits >>= 1; 2614 } 2615 // Construct the 64 double bits: [sign(1), exponent(11), mantissa(52)] 2616 bits = (sign & 0x8000000000000000L) | ((long)exponent << 52) 2617 | (bits & 0xFFFFFFFFFFFFFL); 2618 return Double.longBitsToDouble(bits); 2619 } 2620 2621 /** 2622 * Returns the unit in the last place (ULP) of this {@code BigDecimal} 2623 * instance. An ULP is the distance to the nearest big decimal with the same 2624 * precision. 2625 * 2626 * <p>The amount of a rounding error in the evaluation of a floating-point 2627 * operation is often expressed in ULPs. An error of 1 ULP is often seen as 2628 * a tolerable error. 2629 * 2630 * <p>For class {@code BigDecimal}, the ULP of a number is simply 10<sup>-scale</sup>. 2631 * For example, {@code new BigDecimal(0.1).ulp()} returns {@code 1E-55}. 2632 * 2633 * @return unit in the last place (ULP) of this {@code BigDecimal} instance. 2634 */ 2635 public BigDecimal ulp() { 2636 return valueOf(1, scale); 2637 } 2638 2639 /* Private Methods */ 2640 2641 /** 2642 * It does all rounding work of the public method 2643 * {@code round(MathContext)}, performing an inplace rounding 2644 * without creating a new object. 2645 * 2646 * @param mc 2647 * the {@code MathContext} for perform the rounding. 2648 * @see #round(MathContext) 2649 */ 2650 private void inplaceRound(MathContext mc) { 2651 int mcPrecision = mc.getPrecision(); 2652 if (approxPrecision() < mcPrecision || mcPrecision == 0) { 2653 return; 2654 } 2655 int discardedPrecision = precision() - mcPrecision; 2656 // If no rounding is necessary it returns immediately 2657 if ((discardedPrecision <= 0)) { 2658 return; 2659 } 2660 // When the number is small perform an efficient rounding 2661 if (this.bitLength < 64) { 2662 smallRound(mc, discardedPrecision); 2663 return; 2664 } 2665 // Getting the integer part and the discarded fraction 2666 BigInteger sizeOfFraction = Multiplication.powerOf10(discardedPrecision); 2667 BigInteger[] integerAndFraction = getUnscaledValue().divideAndRemainder(sizeOfFraction); 2668 long newScale = (long)scale - discardedPrecision; 2669 int compRem; 2670 BigDecimal tempBD; 2671 // If the discarded fraction is non-zero, perform rounding 2672 if (integerAndFraction[1].signum() != 0) { 2673 // To check if the discarded fraction >= 0.5 2674 compRem = (integerAndFraction[1].abs().shiftLeftOneBit().compareTo(sizeOfFraction)); 2675 // To look if there is a carry 2676 compRem = roundingBehavior( integerAndFraction[0].testBit(0) ? 1 : 0, 2677 integerAndFraction[1].signum() * (5 + compRem), 2678 mc.getRoundingMode()); 2679 if (compRem != 0) { 2680 integerAndFraction[0] = integerAndFraction[0].add(BigInteger.valueOf(compRem)); 2681 } 2682 tempBD = new BigDecimal(integerAndFraction[0]); 2683 // If after to add the increment the precision changed, we normalize the size 2684 if (tempBD.precision() > mcPrecision) { 2685 integerAndFraction[0] = integerAndFraction[0].divide(BigInteger.TEN); 2686 newScale--; 2687 } 2688 } 2689 // To update all internal fields 2690 scale = safeLongToInt(newScale); 2691 precision = mcPrecision; 2692 setUnscaledValue(integerAndFraction[0]); 2693 } 2694 2695 private static int longCompareTo(long value1, long value2) { 2696 return value1 > value2 ? 1 : (value1 < value2 ? -1 : 0); 2697 } 2698 /** 2699 * This method implements an efficient rounding for numbers which unscaled 2700 * value fits in the type {@code long}. 2701 * 2702 * @param mc 2703 * the context to use 2704 * @param discardedPrecision 2705 * the number of decimal digits that are discarded 2706 * @see #round(MathContext) 2707 */ 2708 private void smallRound(MathContext mc, int discardedPrecision) { 2709 long sizeOfFraction = MathUtils.LONG_POWERS_OF_TEN[discardedPrecision]; 2710 long newScale = (long)scale - discardedPrecision; 2711 long unscaledVal = smallValue; 2712 // Getting the integer part and the discarded fraction 2713 long integer = unscaledVal / sizeOfFraction; 2714 long fraction = unscaledVal % sizeOfFraction; 2715 int compRem; 2716 // If the discarded fraction is non-zero perform rounding 2717 if (fraction != 0) { 2718 // To check if the discarded fraction >= 0.5 2719 compRem = longCompareTo(Math.abs(fraction) * 2, sizeOfFraction); 2720 // To look if there is a carry 2721 integer += roundingBehavior( ((int)integer) & 1, 2722 Long.signum(fraction) * (5 + compRem), 2723 mc.getRoundingMode()); 2724 // If after to add the increment the precision changed, we normalize the size 2725 if (Math.log10(Math.abs(integer)) >= mc.getPrecision()) { 2726 integer /= 10; 2727 newScale--; 2728 } 2729 } 2730 // To update all internal fields 2731 scale = safeLongToInt(newScale); 2732 precision = mc.getPrecision(); 2733 smallValue = integer; 2734 bitLength = bitLength(integer); 2735 intVal = null; 2736 } 2737 2738 /** 2739 * Return an increment that can be -1,0 or 1, depending of 2740 * {@code roundingMode}. 2741 * 2742 * @param parityBit 2743 * can be 0 or 1, it's only used in the case 2744 * {@code HALF_EVEN} 2745 * @param fraction 2746 * the mantissa to be analyzed 2747 * @param roundingMode 2748 * the type of rounding 2749 * @return the carry propagated after rounding 2750 */ 2751 private static int roundingBehavior(int parityBit, int fraction, RoundingMode roundingMode) { 2752 int increment = 0; // the carry after rounding 2753 2754 switch (roundingMode) { 2755 case UNNECESSARY: 2756 if (fraction != 0) { 2757 throw new ArithmeticException("Rounding necessary"); 2758 } 2759 break; 2760 case UP: 2761 increment = Integer.signum(fraction); 2762 break; 2763 case DOWN: 2764 break; 2765 case CEILING: 2766 increment = Math.max(Integer.signum(fraction), 0); 2767 break; 2768 case FLOOR: 2769 increment = Math.min(Integer.signum(fraction), 0); 2770 break; 2771 case HALF_UP: 2772 if (Math.abs(fraction) >= 5) { 2773 increment = Integer.signum(fraction); 2774 } 2775 break; 2776 case HALF_DOWN: 2777 if (Math.abs(fraction) > 5) { 2778 increment = Integer.signum(fraction); 2779 } 2780 break; 2781 case HALF_EVEN: 2782 if (Math.abs(fraction) + parityBit > 5) { 2783 increment = Integer.signum(fraction); 2784 } 2785 break; 2786 } 2787 return increment; 2788 } 2789 2790 /** 2791 * If {@code intVal} has a fractional part throws an exception, 2792 * otherwise it counts the number of bits of value and checks if it's out of 2793 * the range of the primitive type. If the number fits in the primitive type 2794 * returns this number as {@code long}, otherwise throws an 2795 * exception. 2796 * 2797 * @param bitLengthOfType 2798 * number of bits of the type whose value will be calculated 2799 * exactly 2800 * @return the exact value of the integer part of {@code BigDecimal} 2801 * when is possible 2802 * @throws ArithmeticException when rounding is necessary or the 2803 * number don't fit in the primitive type 2804 */ 2805 private long valueExact(int bitLengthOfType) { 2806 BigInteger bigInteger = toBigIntegerExact(); 2807 2808 if (bigInteger.bitLength() < bitLengthOfType) { 2809 // It fits in the primitive type 2810 return bigInteger.longValue(); 2811 } 2812 throw new ArithmeticException("Rounding necessary"); 2813 } 2814 2815 /** 2816 * If the precision already was calculated it returns that value, otherwise 2817 * it calculates a very good approximation efficiently . Note that this 2818 * value will be {@code precision()} or {@code precision()-1} 2819 * in the worst case. 2820 * 2821 * @return an approximation of {@code precision()} value 2822 */ 2823 private int approxPrecision() { 2824 return precision > 0 2825 ? precision 2826 : (int) ((this.bitLength - 1) * LOG10_2) + 1; 2827 } 2828 2829 private static int safeLongToInt(long longValue) { 2830 if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) { 2831 throw new ArithmeticException("Out of int range: " + longValue); 2832 } 2833 return (int) longValue; 2834 } 2835 2836 /** 2837 * It returns the value 0 with the most approximated scale of type 2838 * {@code int}. if {@code longScale > Integer.MAX_VALUE} the 2839 * scale will be {@code Integer.MAX_VALUE}; if 2840 * {@code longScale < Integer.MIN_VALUE} the scale will be 2841 * {@code Integer.MIN_VALUE}; otherwise {@code longScale} is 2842 * casted to the type {@code int}. 2843 * 2844 * @param longScale 2845 * the scale to which the value 0 will be scaled. 2846 * @return the value 0 scaled by the closer scale of type {@code int}. 2847 * @see #scale 2848 */ 2849 private static BigDecimal zeroScaledBy(long longScale) { 2850 if (longScale == (int) longScale) { 2851 return valueOf(0,(int)longScale); 2852 } 2853 if (longScale >= 0) { 2854 return new BigDecimal( 0, Integer.MAX_VALUE); 2855 } 2856 return new BigDecimal( 0, Integer.MIN_VALUE); 2857 } 2858 2859 /** 2860 * Assigns all transient fields upon deserialization of a 2861 * {@code BigDecimal} instance (bitLength and smallValue). The transient 2862 * field precision is assigned lazily. 2863 */ 2864 private void readObject(ObjectInputStream in) throws IOException, 2865 ClassNotFoundException { 2866 in.defaultReadObject(); 2867 2868 this.bitLength = intVal.bitLength(); 2869 if (this.bitLength < 64) { 2870 this.smallValue = intVal.longValue(); 2871 } 2872 } 2873 2874 /** 2875 * Prepares this {@code BigDecimal} for serialization, i.e. the 2876 * non-transient field {@code intVal} is assigned. 2877 */ 2878 private void writeObject(ObjectOutputStream out) throws IOException { 2879 getUnscaledValue(); 2880 out.defaultWriteObject(); 2881 } 2882 2883 private BigInteger getUnscaledValue() { 2884 if(intVal == null) { 2885 intVal = BigInteger.valueOf(smallValue); 2886 } 2887 return intVal; 2888 } 2889 2890 private void setUnscaledValue(BigInteger unscaledValue) { 2891 this.intVal = unscaledValue; 2892 this.bitLength = unscaledValue.bitLength(); 2893 if(this.bitLength < 64) { 2894 this.smallValue = unscaledValue.longValue(); 2895 } 2896 } 2897 2898 private static int bitLength(long smallValue) { 2899 if(smallValue < 0) { 2900 smallValue = ~smallValue; 2901 } 2902 return 64 - Long.numberOfLeadingZeros(smallValue); 2903 } 2904 2905 private static int bitLength(int smallValue) { 2906 if(smallValue < 0) { 2907 smallValue = ~smallValue; 2908 } 2909 return 32 - Integer.numberOfLeadingZeros(smallValue); 2910 } 2911 2912 } 2913