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