Source for java.math.BigDecimal

   1: /* java.math.BigDecimal -- Arbitrary precision decimals.
   2:    Copyright (C) 1999, 2000, 2001, 2003, 2005, 2006 Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10:  
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: package java.math;
  39: 
  40: public class BigDecimal extends Number implements Comparable
  41: {
  42:   private BigInteger intVal;
  43:   private int scale;
  44:   private int precision = 0;
  45:   private static final long serialVersionUID = 6108874887143696463L;
  46: 
  47:   /**
  48:    * The constant zero as a BigDecimal with scale zero.
  49:    * @since 1.5
  50:    */
  51:   public static final BigDecimal ZERO = 
  52:     new BigDecimal (BigInteger.ZERO, 0);
  53: 
  54:   /**
  55:    * The constant one as a BigDecimal with scale zero.
  56:    * @since 1.5
  57:    */
  58:   public static final BigDecimal ONE = 
  59:     new BigDecimal (BigInteger.ONE, 0);
  60: 
  61:   /**
  62:    * The constant ten as a BigDecimal with scale zero.
  63:    * @since 1.5
  64:    */
  65:   public static final BigDecimal TEN = 
  66:     new BigDecimal (BigInteger.TEN, 0);
  67: 
  68:   public static final int ROUND_UP = 0;
  69:   public static final int ROUND_DOWN = 1;
  70:   public static final int ROUND_CEILING = 2;
  71:   public static final int ROUND_FLOOR = 3;
  72:   public static final int ROUND_HALF_UP = 4;
  73:   public static final int ROUND_HALF_DOWN = 5;
  74:   public static final int ROUND_HALF_EVEN = 6;
  75:   public static final int ROUND_UNNECESSARY = 7;
  76: 
  77:   /**
  78:    * Constructs a new BigDecimal whose unscaled value is val and whose
  79:    * scale is zero.
  80:    * @param val the value of the new BigDecimal
  81:    * @since 1.5
  82:    */
  83:   public BigDecimal (int val)
  84:   {
  85:     this.intVal = BigInteger.valueOf(val);
  86:     this.scale = 0;
  87:   }
  88:   
  89:   /**
  90:    * Constructs a BigDecimal using the BigDecimal(int) constructor and then
  91:    * rounds according to the MathContext.
  92:    * @param val the value for the initial (unrounded) BigDecimal
  93:    * @param mc the MathContext specifying the rounding
  94:    * @throws ArithmeticException if the result is inexact but the rounding type
  95:    * is RoundingMode.UNNECESSARY
  96:    * @since 1.5
  97:    */
  98:   public BigDecimal (int val, MathContext mc)
  99:   {
 100:     this (val);
 101:     if (mc.getPrecision() != 0)
 102:       {
 103:         BigDecimal result = this.round(mc);
 104:         this.intVal = result.intVal;
 105:         this.scale = result.scale;
 106:         this.precision = result.precision;
 107:       }    
 108:   }
 109:   
 110:   /**
 111:    * Constructs a new BigDecimal whose unscaled value is val and whose
 112:    * scale is zero.
 113:    * @param val the value of the new BigDecimal
 114:    */
 115:   public BigDecimal (long val)
 116:   {
 117:     this.intVal = BigInteger.valueOf(val);
 118:     this.scale = 0;
 119:   }
 120:   
 121:   /**
 122:    * Constructs a BigDecimal from the long in the same way as BigDecimal(long)
 123:    * and then rounds according to the MathContext.
 124:    * @param val the long from which we create the initial BigDecimal
 125:    * @param mc the MathContext that specifies the rounding behaviour
 126:    * @throws ArithmeticException if the result is inexact but the rounding type
 127:    * is RoundingMode.UNNECESSARY
 128:    * @since 1.5
 129:    */
 130:   public BigDecimal (long val, MathContext mc)
 131:   {
 132:     this(val);
 133:     if (mc.getPrecision() != 0)
 134:       {
 135:         BigDecimal result = this.round(mc);
 136:         this.intVal = result.intVal;
 137:         this.scale = result.scale;
 138:         this.precision = result.precision;
 139:       }    
 140:   }
 141:   
 142:   /**
 143:    * Constructs a BigDecimal whose value is given by num rounded according to 
 144:    * mc.  Since num is already a BigInteger, the rounding refers only to the 
 145:    * precision setting in mc, if mc.getPrecision() returns an int lower than
 146:    * the number of digits in num, then rounding is necessary.
 147:    * @param num the unscaledValue, before rounding
 148:    * @param mc the MathContext that specifies the precision
 149:    * @throws ArithmeticException if the result is inexact but the rounding type
 150:    * is RoundingMode.UNNECESSARY
 151:    * * @since 1.5
 152:    */
 153:   public BigDecimal (BigInteger num, MathContext mc)
 154:   {
 155:     this (num, 0);
 156:     if (mc.getPrecision() != 0)
 157:       {
 158:         BigDecimal result = this.round(mc);
 159:         this.intVal = result.intVal;
 160:         this.scale = result.scale;
 161:         this.precision = result.precision;
 162:       }
 163:   }
 164:   
 165:   /**
 166:    * Constructs a BigDecimal from the String val according to the same
 167:    * rules as the BigDecimal(String) constructor and then rounds 
 168:    * according to the MathContext mc.
 169:    * @param val the String from which we construct the initial BigDecimal
 170:    * @param mc the MathContext that specifies the rounding
 171:    * @throws ArithmeticException if the result is inexact but the rounding type
 172:    * is RoundingMode.UNNECESSARY   
 173:    * @since 1.5
 174:    */
 175:   public BigDecimal (String val, MathContext mc)
 176:   {
 177:     this (val);
 178:     if (mc.getPrecision() != 0)
 179:       {
 180:         BigDecimal result = this.round(mc);
 181:         this.intVal = result.intVal;
 182:         this.scale = result.scale;
 183:         this.precision = result.precision;
 184:       }
 185:   }
 186:   
 187:   /**
 188:    * Constructs a BigDecimal whose unscaled value is num and whose
 189:    * scale is zero.
 190:    * @param num the value of the new BigDecimal
 191:    */
 192:   public BigDecimal (BigInteger num) 
 193:   {
 194:     this (num, 0);
 195:   }
 196: 
 197:   /**
 198:    * Constructs a BigDecimal whose unscaled value is num and whose
 199:    * scale is scale.
 200:    * @param num
 201:    * @param scale
 202:    */
 203:   public BigDecimal (BigInteger num, int scale)
 204:   {
 205:     this.intVal = num;
 206:     this.scale = scale;
 207:   }
 208:   
 209:   /**
 210:    * Constructs a BigDecimal using the BigDecimal(BigInteger, int) 
 211:    * constructor and then rounds according to the MathContext.
 212:    * @param num the unscaled value of the unrounded BigDecimal
 213:    * @param scale the scale of the unrounded BigDecimal
 214:    * @param mc the MathContext specifying the rounding
 215:    * @throws ArithmeticException if the result is inexact but the rounding type
 216:    * is RoundingMode.UNNECESSARY
 217:    * @since 1.5
 218:    */
 219:   public BigDecimal (BigInteger num, int scale, MathContext mc)
 220:   {
 221:     this (num, scale);
 222:     if (mc.getPrecision() != 0)
 223:       {
 224:         BigDecimal result = this.round(mc);
 225:         this.intVal = result.intVal;
 226:         this.scale = result.scale;
 227:         this.precision = result.precision;
 228:       }
 229:   }
 230: 
 231:   /**
 232:    * Constructs a BigDecimal in the same way as BigDecimal(double) and then
 233:    * rounds according to the MathContext.
 234:    * @param num the double from which the initial BigDecimal is created
 235:    * @param mc the MathContext that specifies the rounding behaviour
 236:    * @throws ArithmeticException if the result is inexact but the rounding type
 237:    * is RoundingMode.UNNECESSARY 
 238:    * @since 1.5
 239:    */
 240:   public BigDecimal (double num, MathContext mc)
 241:   {
 242:     this (num);
 243:     if (mc.getPrecision() != 0)
 244:       {
 245:         BigDecimal result = this.round(mc);
 246:         this.intVal = result.intVal;
 247:         this.scale = result.scale;
 248:         this.precision = result.precision;
 249:       }
 250:   }
 251:   
 252:   public BigDecimal (double num) throws NumberFormatException 
 253:   {
 254:     if (Double.isInfinite (num) || Double.isNaN (num))
 255:       throw new NumberFormatException ("invalid argument: " + num);
 256:     // Note we can't convert NUM to a String and then use the
 257:     // String-based constructor.  The BigDecimal documentation makes
 258:     // it clear that the two constructors work differently.
 259: 
 260:     final int mantissaBits = 52;
 261:     final int exponentBits = 11;
 262:     final long mantMask = (1L << mantissaBits) - 1;
 263:     final long expMask = (1L << exponentBits) - 1;
 264: 
 265:     long bits = Double.doubleToLongBits (num);
 266:     long mantissa = bits & mantMask;
 267:     long exponent = (bits >>> mantissaBits) & expMask;
 268:     boolean denormal = exponent == 0;
 269: 
 270:     // Correct the exponent for the bias.
 271:     exponent -= denormal ? 1022 : 1023;
 272: 
 273:     // Now correct the exponent to account for the bits to the right
 274:     // of the decimal.
 275:     exponent -= mantissaBits;
 276:     // Ordinary numbers have an implied leading `1' bit.
 277:     if (! denormal)
 278:       mantissa |= (1L << mantissaBits);
 279: 
 280:     // Shave off factors of 10.
 281:     while (exponent < 0 && (mantissa & 1) == 0)
 282:       {
 283:     ++exponent;
 284:     mantissa >>= 1;
 285:       }
 286: 
 287:     intVal = BigInteger.valueOf (bits < 0 ? - mantissa : mantissa);
 288:     if (exponent < 0)
 289:       {
 290:     // We have MANTISSA * 2 ^ (EXPONENT).
 291:     // Since (1/2)^N == 5^N * 10^-N we can easily convert this
 292:     // into a power of 10.
 293:     scale = (int) (- exponent);
 294:     BigInteger mult = BigInteger.valueOf (5).pow (scale);
 295:     intVal = intVal.multiply (mult);
 296:       }
 297:     else
 298:       {
 299:     intVal = intVal.shiftLeft ((int) exponent);
 300:     scale = 0;
 301:       }
 302:   }
 303: 
 304:   /**
 305:    * Constructs a BigDecimal from the char subarray and rounding 
 306:    * according to the MathContext.
 307:    * @param in the char array
 308:    * @param offset the start of the subarray
 309:    * @param len the length of the subarray
 310:    * @param mc the MathContext for rounding
 311:    * @throws NumberFormatException if the char subarray is not a valid 
 312:    * BigDecimal representation
 313:    * @throws ArithmeticException if the result is inexact but the rounding 
 314:    * mode is RoundingMode.UNNECESSARY
 315:    * @since 1.5
 316:    */
 317:   public BigDecimal(char[] in, int offset, int len, MathContext mc)
 318:   {
 319:     this(in, offset, len);
 320:     // If mc has precision other than zero then we must round.
 321:     if (mc.getPrecision() != 0)
 322:       {
 323:         BigDecimal temp = this.round(mc);
 324:         this.intVal = temp.intVal;
 325:         this.scale = temp.scale;
 326:         this.precision = temp.precision;
 327:       }
 328:   }
 329:   
 330:   /**
 331:    * Constructs a BigDecimal from the char array and rounding according
 332:    * to the MathContext. 
 333:    * @param in the char array
 334:    * @param mc the MathContext
 335:    * @throws NumberFormatException if <code>in</code> is not a valid BigDecimal
 336:    * representation
 337:    * @throws ArithmeticException if the result is inexact but the rounding mode
 338:    * is RoundingMode.UNNECESSARY
 339:    * @since 1.5
 340:    */
 341:   public BigDecimal(char[] in, MathContext mc)
 342:   {
 343:     this(in, 0, in.length);
 344:     // If mc has precision other than zero then we must round.
 345:     if (mc.getPrecision() != 0)
 346:       {
 347:         BigDecimal temp = this.round(mc);
 348:         this.intVal = temp.intVal;
 349:         this.scale = temp.scale;
 350:         this.precision = temp.precision;
 351:       } 
 352:   }
 353:   
 354:   /**
 355:    * Constructs a BigDecimal from the given char array, accepting the same
 356:    * sequence of characters as the BigDecimal(String) constructor.
 357:    * @param in the char array
 358:    * @throws NumberFormatException if <code>in</code> is not a valid BigDecimal
 359:    * representation
 360:    * @since 1.5
 361:    */
 362:   public BigDecimal(char[] in)
 363:   {
 364:     this(in, 0, in.length);
 365:   }
 366:   
 367:   /**
 368:    * Constructs a BigDecimal from a char subarray, accepting the same sequence
 369:    * of characters as the BigDecimal(String) constructor.  
 370:    * @param in the char array
 371:    * @param offset the start of the subarray
 372:    * @param len the length of the subarray
 373:    * @throws NumberFormatException if <code>in</code> is not a valid
 374:    * BigDecimal representation.
 375:    * @since 1.5
 376:    */
 377:   public BigDecimal(char[] in, int offset, int len)
 378:   {
 379:     //  start is the index into the char array where the significand starts
 380:     int start = offset;
 381:     //  end is one greater than the index of the last character used
 382:     int end = offset + len;
 383:     //  point is the index into the char array where the exponent starts
 384:     //  (or, if there is no exponent, this is equal to end)
 385:     int point = offset;
 386:     //  dot is the index into the char array where the decimal point is 
 387:     //  found, or -1 if there is no decimal point
 388:     int dot = -1;
 389:     
 390:     //  The following examples show what these variables mean.  Note that
 391:     //  point and dot don't yet have the correct values, they will be 
 392:     //  properly assigned in a loop later on in this method.
 393:     //
 394:     //  Example 1
 395:     //
 396:     //         +  1  0  2  .  4  6  9
 397:     //  __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
 398:     //
 399:     //  offset = 2, len = 8, start = 3, dot = 6, point = end = 10
 400:     //
 401:     //  Example 2
 402:     //
 403:     //         +  2  3  4  .  6  1  3  E  -  1
 404:     //  __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
 405:     //
 406:     //  offset = 2, len = 11, start = 3, dot = 6, point = 10, end = 13
 407:     //
 408:     //  Example 3
 409:     //
 410:     //         -  1  2  3  4  5  e  7  
 411:     //  __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __
 412:     //
 413:     //  offset = 2, len = 8, start = 3, dot = -1, point = 8, end = 10 
 414:     
 415:     //  Determine the sign of the number.
 416:     boolean negative = false;
 417:     if (in[offset] == '+')
 418:       {
 419:         ++start;
 420:         ++point;
 421:       }
 422:     else if (in[offset] == '-')
 423:       {
 424:         ++start;
 425:         ++point;
 426:         negative = true;
 427:       }
 428: 
 429:     //  Check each character looking for the decimal point and the 
 430:     //  start of the exponent.
 431:     while (point < end)
 432:       {
 433:         char c = in[point];
 434:         if (c == '.')
 435:           {
 436:             // If dot != -1 then we've seen more than one decimal point.
 437:             if (dot != -1)
 438:               throw new NumberFormatException("multiple `.'s in number");
 439:             dot = point;
 440:           }
 441:         // Break when we reach the start of the exponent.
 442:         else if (c == 'e' || c == 'E')
 443:           break;
 444:         // Throw an exception if the character was not a decimal or an 
 445:         // exponent and is not a digit.
 446:         else if (!Character.isDigit(c))
 447:           throw new NumberFormatException("unrecognized character at " + point
 448:                                           + ": " + c);
 449:         ++point;
 450:       }
 451: 
 452:     // val is a StringBuilder from which we'll create a BigInteger
 453:     // which will be the unscaled value for this BigDecimal
 454:     StringBuilder val = new StringBuilder(point - start - 1);
 455:     if (dot != -1)
 456:       {
 457:         // If there was a decimal we must combine the two parts that 
 458:         // contain only digits and we must set the scale properly.
 459:         val.append(in, start, dot - start);
 460:         val.append(in, dot + 1, point - dot - 1);
 461:         scale = point - 1 - dot;
 462:       }
 463:     else
 464:       {
 465:         // If there was no decimal then the unscaled value is just the number
 466:         // formed from all the digits and the scale is zero.
 467:         val.append(in, start, point - start);
 468:         scale = 0;
 469:       }
 470:     if (val.length() == 0)
 471:       throw new NumberFormatException("no digits seen");
 472: 
 473:     // Prepend a negative sign if necessary.
 474:     if (negative)
 475:       val.insert(0, '-');
 476:     intVal = new BigInteger(val.toString());
 477: 
 478:     // Now parse exponent.
 479:     // If point < end that means we broke out of the previous loop when we
 480:     // saw an 'e' or an 'E'.
 481:     if (point < end)
 482:       {
 483:         point++;
 484:         // Ignore a '+' sign.
 485:         if (in[point] == '+')
 486:           point++;
 487: 
 488:         // Throw an exception if there were no digits found after the 'e'
 489:         // or 'E'.
 490:         if (point >= end)
 491:           throw new NumberFormatException("no exponent following e or E");
 492: 
 493:         try
 494:           {
 495:             // Adjust the scale according to the exponent.  
 496:             // Remember that the value of a BigDecimal is
 497:             // unscaledValue x Math.pow(10, -scale)
 498:             scale -= Integer.parseInt(new String(in, point, end - point));
 499:           }
 500:         catch (NumberFormatException ex)
 501:           {
 502:             throw new NumberFormatException("malformed exponent");
 503:           }
 504:       }
 505:   }
 506:   
 507:   public BigDecimal (String num) throws NumberFormatException 
 508:   {
 509:     int len = num.length();
 510:     int start = 0, point = 0;
 511:     int dot = -1;
 512:     boolean negative = false;
 513:     if (num.charAt(0) == '+')
 514:       {
 515:     ++start;
 516:     ++point;
 517:       }
 518:     else if (num.charAt(0) == '-')
 519:       {
 520:     ++start;
 521:     ++point;
 522:     negative = true;
 523:       }
 524: 
 525:     while (point < len)
 526:       {
 527:     char c = num.charAt (point);
 528:     if (c == '.')
 529:       {
 530:         if (dot >= 0)
 531:           throw new NumberFormatException ("multiple `.'s in number");
 532:         dot = point;
 533:       }
 534:     else if (c == 'e' || c == 'E')
 535:       break;
 536:     else if (Character.digit (c, 10) < 0)
 537:       throw new NumberFormatException ("unrecognized character: " + c);
 538:     ++point;
 539:       }
 540: 
 541:     String val;
 542:     if (dot >= 0)
 543:       {
 544:     val = num.substring (start, dot) + num.substring (dot + 1, point);
 545:     scale = point - 1 - dot;
 546:       }
 547:     else
 548:       {
 549:     val = num.substring (start, point);
 550:     scale = 0;
 551:       }
 552:     if (val.length () == 0)
 553:       throw new NumberFormatException ("no digits seen");
 554: 
 555:     if (negative)
 556:       val = "-" + val;
 557:     intVal = new BigInteger (val);
 558: 
 559:     // Now parse exponent.
 560:     if (point < len)
 561:       {
 562:         point++;
 563:         if (num.charAt(point) == '+')
 564:           point++;
 565: 
 566:         if (point >= len )
 567:           throw new NumberFormatException ("no exponent following e or E");
 568:     
 569:         try 
 570:       {        
 571:         scale -= Integer.parseInt (num.substring (point));
 572:       }
 573:         catch (NumberFormatException ex) 
 574:       {
 575:         throw new NumberFormatException ("malformed exponent");
 576:       }
 577:       }
 578:   }
 579: 
 580:   public static BigDecimal valueOf (long val) 
 581:   {
 582:     return valueOf (val, 0);
 583:   }
 584: 
 585:   public static BigDecimal valueOf (long val, int scale) 
 586:     throws NumberFormatException 
 587:   {
 588:     if ((scale == 0) && ((int)val == val))
 589:       switch ((int) val)
 590:     {
 591:     case 0:
 592:       return ZERO;
 593:     case 1:
 594:       return ONE;
 595:     }
 596: 
 597:     return new BigDecimal (BigInteger.valueOf (val), scale);
 598:   }
 599: 
 600:   public BigDecimal add (BigDecimal val) 
 601:   {
 602:     // For addition, need to line up decimals.  Note that the movePointRight
 603:     // method cannot be used for this as it might return a BigDecimal with
 604:     // scale == 0 instead of the scale we need.
 605:     BigInteger op1 = intVal;
 606:     BigInteger op2 = val.intVal;
 607:     if (scale < val.scale)
 608:       op1 = op1.multiply (BigInteger.TEN.pow (val.scale - scale));
 609:     else if (scale > val.scale)
 610:       op2 = op2.multiply (BigInteger.TEN.pow (scale - val.scale));
 611: 
 612:     return new BigDecimal (op1.add (op2), Math.max (scale, val.scale));
 613:   }
 614:   
 615:   /**
 616:    * Returns a BigDecimal whose value is found first by calling the 
 617:    * method add(val) and then by rounding according to the MathContext mc.
 618:    * @param val the augend
 619:    * @param mc the MathContext for rounding
 620:    * @throws ArithmeticException if the value is inexact but the rounding is
 621:    * RoundingMode.UNNECESSARY
 622:    * @return <code>this</code> + <code>val</code>, rounded if need be
 623:    * @since 1.5
 624:    */
 625:   public BigDecimal add (BigDecimal val, MathContext mc)
 626:   {
 627:     return add(val).round(mc);
 628:   }
 629: 
 630:   public BigDecimal subtract (BigDecimal val) 
 631:   {
 632:     return this.add(val.negate());
 633:   }
 634: 
 635:   /**
 636:    * Returns a BigDecimal whose value is found first by calling the 
 637:    * method subtract(val) and then by rounding according to the MathContext mc.
 638:    * @param val the subtrahend
 639:    * @param mc the MathContext for rounding
 640:    * @throws ArithmeticException if the value is inexact but the rounding is
 641:    * RoundingMode.UNNECESSARY
 642:    * @return <code>this</code> - <code>val</code>, rounded if need be
 643:    * @since 1.5
 644:    */
 645:   public BigDecimal subtract (BigDecimal val, MathContext mc)
 646:   {
 647:     return subtract(val).round(mc);
 648:   }
 649: 
 650:   public BigDecimal multiply (BigDecimal val) 
 651:   {
 652:     return new BigDecimal (intVal.multiply (val.intVal), scale + val.scale);
 653:   }
 654:   
 655:   /**
 656:    * Returns a BigDecimal whose value is (this x val) before it is rounded
 657:    * according to the MathContext mc. 
 658:    * @param val the multiplicand
 659:    * @param mc the MathContext for rounding
 660:    * @return a new BigDecimal with value approximately (this x val)
 661:    * @throws ArithmeticException if the value is inexact but the rounding mode
 662:    * is RoundingMode.UNNECESSARY
 663:    * @since 1.5
 664:    */
 665:   public BigDecimal multiply (BigDecimal val, MathContext mc)
 666:   {
 667:     return multiply(val).round(mc);
 668:   }
 669: 
 670:   public BigDecimal divide (BigDecimal val, int roundingMode) 
 671:     throws ArithmeticException, IllegalArgumentException 
 672:   {
 673:     return divide (val, scale, roundingMode);
 674:   }
 675:    
 676:   public BigDecimal divide(BigDecimal val, int newScale, int roundingMode)
 677:     throws ArithmeticException, IllegalArgumentException 
 678:   {
 679:     if (roundingMode < 0 || roundingMode > 7)
 680:       throw 
 681:     new IllegalArgumentException("illegal rounding mode: " + roundingMode);
 682: 
 683:     if (intVal.signum () == 0)    // handle special case of 0.0/0.0
 684:       return newScale == 0 ? ZERO : new BigDecimal (ZERO.intVal, newScale);
 685:     
 686:     // Ensure that pow gets a non-negative value.
 687:     BigInteger valIntVal = val.intVal;
 688:     int power = newScale - (scale - val.scale);
 689:     if (power < 0)
 690:       {
 691:     // Effectively increase the scale of val to avoid an
 692:     // ArithmeticException for a negative power.
 693:         valIntVal = valIntVal.multiply (BigInteger.TEN.pow (-power));
 694:     power = 0;
 695:       }
 696: 
 697:     BigInteger dividend = intVal.multiply (BigInteger.TEN.pow (power));
 698:     
 699:     BigInteger parts[] = dividend.divideAndRemainder (valIntVal);
 700: 
 701:     BigInteger unrounded = parts[0];
 702:     if (parts[1].signum () == 0) // no remainder, no rounding necessary
 703:       return new BigDecimal (unrounded, newScale);
 704: 
 705:     if (roundingMode == ROUND_UNNECESSARY)
 706:       throw new ArithmeticException ("Rounding necessary");
 707: 
 708:     int sign = intVal.signum () * valIntVal.signum ();
 709: 
 710:     if (roundingMode == ROUND_CEILING)
 711:       roundingMode = (sign > 0) ? ROUND_UP : ROUND_DOWN;
 712:     else if (roundingMode == ROUND_FLOOR)
 713:       roundingMode = (sign < 0) ? ROUND_UP : ROUND_DOWN;
 714:     else
 715:       {
 716:     // half is -1 if remainder*2 < positive intValue (*power), 0 if equal,
 717:     // 1 if >. This implies that the remainder to round is less than,
 718:     // equal to, or greater than half way to the next digit.
 719:     BigInteger posRemainder
 720:       = parts[1].signum () < 0 ? parts[1].negate() : parts[1];
 721:     valIntVal = valIntVal.signum () < 0 ? valIntVal.negate () : valIntVal;
 722:     int half = posRemainder.shiftLeft(1).compareTo(valIntVal);
 723: 
 724:     switch(roundingMode)
 725:       {
 726:       case ROUND_HALF_UP:
 727:         roundingMode = (half < 0) ? ROUND_DOWN : ROUND_UP;
 728:         break;
 729:       case ROUND_HALF_DOWN:
 730:         roundingMode = (half > 0) ? ROUND_UP : ROUND_DOWN;
 731:         break;
 732:       case ROUND_HALF_EVEN:
 733:         if (half < 0)
 734:           roundingMode = ROUND_DOWN;
 735:         else if (half > 0)
 736:           roundingMode = ROUND_UP;
 737:         else if (unrounded.testBit(0)) // odd, then ROUND_HALF_UP
 738:           roundingMode = ROUND_UP;
 739:         else                           // even, ROUND_HALF_DOWN
 740:           roundingMode = ROUND_DOWN;
 741:         break;
 742:       }
 743:       }
 744: 
 745:     if (roundingMode == ROUND_UP)
 746:       unrounded = unrounded.add (BigInteger.valueOf (sign > 0 ? 1 : -1));
 747: 
 748:     // roundingMode == ROUND_DOWN
 749:     return new BigDecimal (unrounded, newScale);
 750:   }
 751:   
 752:   /**
 753:    * Performs division, if the resulting quotient requires rounding
 754:    * (has a nonterminating decimal expansion), 
 755:    * an ArithmeticException is thrown. 
 756:    * #see divide(BigDecimal, int, int)
 757:    * @since 1.5
 758:    */
 759:   public BigDecimal divide(BigDecimal divisor)
 760:     throws ArithmeticException, IllegalArgumentException 
 761:   {
 762:     return divide(divisor, scale, ROUND_UNNECESSARY);
 763:   }
 764: 
 765:   /**
 766:    * Returns a BigDecimal whose value is the remainder in the quotient
 767:    * this / val.  This is obtained by 
 768:    * subtract(divideToIntegralValue(val).multiply(val)).  
 769:    * @param val the divisor
 770:    * @return a BigDecimal whose value is the remainder
 771:    * @throws ArithmeticException if val == 0
 772:    * @since 1.5
 773:    */
 774:   public BigDecimal remainder(BigDecimal val)
 775:   {
 776:     return subtract(divideToIntegralValue(val).multiply(val));
 777:   }
 778: 
 779:   /**
 780:    * Returns a BigDecimal array, the first element of which is the integer part
 781:    * of this / val, and the second element of which is the remainder of 
 782:    * that quotient.
 783:    * @param val the divisor
 784:    * @return the above described BigDecimal array
 785:    * @throws ArithmeticException if val == 0
 786:    * @since 1.5
 787:    */
 788:   public BigDecimal[] divideAndRemainder(BigDecimal val)
 789:   {
 790:     BigDecimal[] result = new BigDecimal[2];
 791:     result[0] = divideToIntegralValue(val);
 792:     result[1] = subtract(result[0].multiply(val));
 793:     return result;
 794:   }
 795:   
 796:   /**
 797:    * Returns a BigDecimal whose value is the integer part of the quotient 
 798:    * this / val.  The preferred scale is this.scale - val.scale.
 799:    * @param val the divisor
 800:    * @return a BigDecimal whose value is the integer part of this / val.
 801:    * @throws ArithmeticException if val == 0
 802:    * @since 1.5
 803:    */
 804:   public BigDecimal divideToIntegralValue(BigDecimal val)
 805:   {
 806:     return divide(val, ROUND_DOWN).floor().setScale(scale - val.scale, ROUND_DOWN);
 807:   }
 808:   
 809:   /**
 810:    * Mutates this BigDecimal into one with no fractional part, whose value is 
 811:    * equal to the largest integer that is <= to this BigDecimal.  Note that
 812:    * since this method is private it is okay to mutate this BigDecimal.
 813:    * @return the BigDecimal obtained through the floor operation on this 
 814:    * BigDecimal.
 815:    */
 816:   private BigDecimal floor()
 817:   {
 818:     if (scale <= 0)
 819:       return this;
 820:     String intValStr = intVal.toString();
 821:     intValStr = intValStr.substring(0, intValStr.length() - scale);
 822:     intVal = new BigInteger(intValStr).multiply(BigInteger.TEN.pow(scale));
 823:     return this;
 824:   }
 825:     
 826:   public int compareTo (Object obj) 
 827:   {
 828:     return compareTo((BigDecimal) obj);
 829:   }
 830: 
 831:   public int compareTo (BigDecimal val)
 832:   {
 833:     if (scale == val.scale)
 834:       return intVal.compareTo (val.intVal);
 835: 
 836:     BigInteger thisParts[] = 
 837:       intVal.divideAndRemainder (BigInteger.TEN.pow (scale));
 838:     BigInteger valParts[] =
 839:       val.intVal.divideAndRemainder (BigInteger.TEN.pow (val.scale));
 840:     
 841:     int compare;
 842:     if ((compare = thisParts[0].compareTo (valParts[0])) != 0)
 843:       return compare;
 844: 
 845:     // quotients are the same, so compare remainders
 846: 
 847:     // Add some trailing zeros to the remainder with the smallest scale
 848:     if (scale < val.scale)
 849:       thisParts[1] = thisParts[1].multiply
 850:             (BigInteger.valueOf (10).pow (val.scale - scale));
 851:     else if (scale > val.scale)
 852:       valParts[1] = valParts[1].multiply
 853:             (BigInteger.valueOf (10).pow (scale - val.scale));
 854: 
 855:     // and compare them
 856:     return thisParts[1].compareTo (valParts[1]);
 857:   }
 858: 
 859:   public boolean equals (Object o) 
 860:   {
 861:     return (o instanceof BigDecimal 
 862:         && scale == ((BigDecimal) o).scale
 863:         && compareTo ((BigDecimal) o) == 0);
 864:   }
 865: 
 866:   public int hashCode() 
 867:   {
 868:     return intValue() ^ scale;
 869:   }
 870: 
 871:   public BigDecimal max (BigDecimal val)
 872:   {
 873:     switch (compareTo (val)) 
 874:       {
 875:       case 1:
 876:     return this;
 877:       default:
 878:     return val;
 879:       }
 880:   }
 881: 
 882:   public BigDecimal min (BigDecimal val) 
 883:   {
 884:     switch (compareTo (val)) 
 885:       {
 886:       case -1:
 887:     return this;
 888:       default:
 889:     return val;
 890:       }
 891:   }
 892: 
 893:   public BigDecimal movePointLeft (int n)
 894:   {
 895:     return (n < 0) ? movePointRight (-n) : new BigDecimal (intVal, scale + n);
 896:   }
 897: 
 898:   public BigDecimal movePointRight (int n)
 899:   {
 900:     if (n < 0)
 901:       return movePointLeft (-n);
 902: 
 903:     if (scale >= n)
 904:       return new BigDecimal (intVal, scale - n);
 905: 
 906:     return new BigDecimal (intVal.multiply 
 907:                (BigInteger.TEN.pow (n - scale)), 0);
 908:   }
 909: 
 910:   public int signum () 
 911:   {
 912:     return intVal.signum ();
 913:   }
 914: 
 915:   public int scale () 
 916:   {
 917:     return scale;
 918:   }
 919:   
 920:   public BigInteger unscaledValue()
 921:   {
 922:     return intVal;
 923:   }
 924: 
 925:   public BigDecimal abs () 
 926:   {
 927:     return new BigDecimal (intVal.abs (), scale);
 928:   }
 929: 
 930:   public BigDecimal negate () 
 931:   {
 932:     return new BigDecimal (intVal.negate (), scale);
 933:   }
 934:   
 935:   /**
 936:    * Returns a BigDecimal whose value is found first by negating this via
 937:    * the negate() method, then by rounding according to the MathContext mc.
 938:    * @param mc the MathContext for rounding
 939:    * @return a BigDecimal whose value is approximately (-this)
 940:    * @throws ArithmeticException if the value is inexact but the rounding mode
 941:    * is RoundingMode.UNNECESSARY
 942:    * @since 1.5
 943:    */
 944:   public BigDecimal negate(MathContext mc)
 945:   {
 946:     BigDecimal result = negate();
 947:     if (mc.getPrecision() != 0)
 948:       result = result.round(mc);
 949:     return result;
 950:   }
 951:   
 952:   /**
 953:    * Returns this BigDecimal.  This is included for symmetry with the 
 954:    * method negate().
 955:    * @return this
 956:    * @since 1.5
 957:    */
 958:   public BigDecimal plus()
 959:   {
 960:     return this;
 961:   }
 962:   
 963:   /**
 964:    * Returns a BigDecimal whose value is found by rounding <code>this</code> 
 965:    * according to the MathContext.  This is the same as round(MathContext).
 966:    * @param mc the MathContext for rounding
 967:    * @return a BigDecimal whose value is <code>this</code> before being rounded
 968:    * @throws ArithmeticException if the value is inexact but the rounding mode
 969:    * is RoundingMode.UNNECESSARY
 970:    * @since 1.5
 971:    */
 972:   public BigDecimal plus(MathContext mc)
 973:   {
 974:     return round(mc);
 975:   }
 976:    
 977:   /**
 978:    * Returns a BigDecimal which is this BigDecimal rounded according to the
 979:    * MathContext rounding settings.
 980:    * @param mc the MathContext that tells us how to round
 981:    * @return the rounded BigDecimal
 982:    */
 983:   public BigDecimal round(MathContext mc)
 984:   {
 985:     int mcPrecision = mc.getPrecision();
 986:     int numToChop = precision() - mcPrecision;
 987:     // If mc specifies not to chop any digits or if we've already chopped 
 988:     // enough digits (say by using a MathContext in the constructor for this
 989:     // BigDecimal) then just return this.
 990:     if (mcPrecision == 0 || numToChop <= 0)
 991:       return this;
 992:     
 993:     // Make a new BigDecimal which is the correct power of 10 to chop off
 994:     // the required number of digits and then call divide.
 995:     BigDecimal div = new BigDecimal(BigInteger.TEN.pow(numToChop));
 996:     BigDecimal rounded = divide(div, scale, 4);
 997:     rounded.scale -= numToChop;
 998:     rounded.precision = mcPrecision;
 999:     return rounded;
1000:   }
1001: 
1002:   /**
1003:    * Returns the precision of this BigDecimal (the number of digits in the
1004:    * unscaled value).  The precision of a zero value is 1.
1005:    * @return the number of digits in the unscaled value, or 1 if the value 
1006:    * is zero.
1007:    */
1008:   public int precision()
1009:   {
1010:     if (precision == 0)
1011:       {
1012:     String s = intVal.toString();
1013:     precision = s.length() - (( s.charAt(0) == '-' ) ? 1 : 0);
1014:       }
1015:     return precision;
1016:   }
1017:   
1018:   /**
1019:    * Returns the String representation of this BigDecimal, using scientific
1020:    * notation if necessary.  The following steps are taken to generate
1021:    * the result:
1022:    * 
1023:    * 1. the BigInteger unscaledValue's toString method is called and if
1024:    * <code>scale == 0<code> is returned.
1025:    * 2. an <code>int adjExp</code> is created which is equal to the negation
1026:    * of <code>scale</code> plus the number of digits in the unscaled value, 
1027:    * minus one.
1028:    * 3. if <code>scale >= 0 && adjExp >= -6</code> then we represent this 
1029:    * BigDecimal without scientific notation.  A decimal is added if the 
1030:    * scale is positive and zeros are prepended as necessary.
1031:    * 4. if scale is negative or adjExp is less than -6 we use scientific
1032:    * notation.  If the unscaled value has more than one digit, a decimal 
1033:    * as inserted after the first digit, the character 'E' is appended
1034:    * and adjExp is appended.
1035:    */
1036:   public String toString()
1037:   {
1038:     // bigStr is the String representation of the unscaled value.  If
1039:     // scale is zero we simply return this.
1040:     String bigStr = intVal.toString();
1041:     if (scale == 0)
1042:       return bigStr;
1043: 
1044:     boolean negative = (bigStr.charAt(0) == '-');
1045:     int point = bigStr.length() - scale - (negative ? 1 : 0);
1046: 
1047:     StringBuilder val = new StringBuilder();
1048: 
1049:     if (scale >= 0 && (point - 1) >= -6)
1050:       {
1051:     // Convert to character form without scientific notation.
1052:         if (point <= 0)
1053:           {
1054:             // Zeros need to be prepended to the StringBuilder.
1055:             if (negative)
1056:               val.append('-');
1057:             // Prepend a '0' and a '.' and then as many more '0's as necessary.
1058:             val.append('0').append('.');
1059:             while (point < 0)
1060:               {
1061:                 val.append('0');
1062:                 point++;
1063:               }
1064:             // Append the unscaled value.
1065:             val.append(bigStr.substring(negative ? 1 : 0));
1066:           }
1067:         else
1068:           {
1069:             // No zeros need to be prepended so the String is simply the 
1070:             // unscaled value with the decimal point inserted.
1071:             val.append(bigStr);
1072:             val.insert(point + (negative ? 1 : 0), '.');
1073:           }
1074:       }
1075:     else
1076:       {
1077:         // We must use scientific notation to represent this BigDecimal.
1078:         val.append(bigStr);
1079:         // If there is more than one digit in the unscaled value we put a 
1080:         // decimal after the first digit.
1081:         if (bigStr.length() > 1)
1082:           val.insert( ( negative ? 2 : 1 ), '.');
1083:         // And then append 'E' and the exponent = (point - 1).
1084:         val.append('E');
1085:         if (point - 1 >= 0)
1086:           val.append('+');
1087:         val.append( point - 1 );
1088:       }
1089:     return val.toString();
1090:   }
1091: 
1092:   /**
1093:    * Returns the String representation of this BigDecimal, using engineering
1094:    * notation if necessary.  This is similar to toString() but when exponents 
1095:    * are used the exponent is made to be a multiple of 3 such that the integer
1096:    * part is between 1 and 999.
1097:    * 
1098:    * @return a String representation of this BigDecimal in engineering notation
1099:    * @since 1.5
1100:    */
1101:   public String toEngineeringString()
1102:   {
1103:     // bigStr is the String representation of the unscaled value.  If
1104:     // scale is zero we simply return this.
1105:     String bigStr = intVal.toString();
1106:     if (scale == 0)
1107:       return bigStr;
1108: 
1109:     boolean negative = (bigStr.charAt(0) == '-');
1110:     int point = bigStr.length() - scale - (negative ? 1 : 0);
1111: 
1112:     // This is the adjusted exponent described above.
1113:     int adjExp = point - 1;
1114:     StringBuilder val = new StringBuilder();
1115: 
1116:     if (scale >= 0 && adjExp >= -6)
1117:       {
1118:         // Convert to character form without scientific notation.
1119:         if (point <= 0)
1120:           {
1121:             // Zeros need to be prepended to the StringBuilder.
1122:             if (negative)
1123:               val.append('-');
1124:             // Prepend a '0' and a '.' and then as many more '0's as necessary.
1125:             val.append('0').append('.');
1126:             while (point < 0)
1127:               {
1128:                 val.append('0');
1129:                 point++;
1130:               }
1131:             // Append the unscaled value.
1132:             val.append(bigStr.substring(negative ? 1 : 0));
1133:           }
1134:         else
1135:           {
1136:             // No zeros need to be prepended so the String is simply the 
1137:             // unscaled value with the decimal point inserted.
1138:             val.append(bigStr);
1139:             val.insert(point + (negative ? 1 : 0), '.');
1140:           }
1141:       }
1142:     else
1143:       {
1144:         // We must use scientific notation to represent this BigDecimal.
1145:         // The exponent must be a multiple of 3 and the integer part
1146:         // must be between 1 and 999.
1147:         val.append(bigStr);        
1148:         int zeros = adjExp % 3;
1149:         int dot = 1;
1150:         if (adjExp > 0)
1151:           {
1152:             // If the exponent is positive we just move the decimal to the
1153:             // right and decrease the exponent until it is a multiple of 3.
1154:             dot += zeros;
1155:             adjExp -= zeros;
1156:           }
1157:         else
1158:           {
1159:             // If the exponent is negative then we move the dot to the right
1160:             // and decrease the exponent (increase its magnitude) until 
1161:             // it is a multiple of 3.  Note that this is not adjExp -= zeros
1162:             // because the mod operator doesn't give us the distance to the 
1163:             // correct multiple of 3.  (-5 mod 3) is -2 but the distance from
1164:             // -5 to the correct multiple of 3 (-6) is 1, not 2.
1165:             if (zeros == -2)
1166:               {
1167:                 dot += 1;
1168:                 adjExp -= 1;
1169:               }
1170:             else if (zeros == -1)
1171:               {
1172:                 dot += 2;
1173:                 adjExp -= 2;
1174:               }
1175:           }
1176: 
1177:         // Either we have to append zeros because, for example, 1.1E+5 should
1178:         // be 110E+3, or we just have to put the decimal in the right place.
1179:         if (dot > val.length())
1180:           {
1181:             while (dot > val.length())
1182:               val.append('0');
1183:           }
1184:         else if (bigStr.length() > dot)
1185:           val.insert(dot + (negative ? 1 : 0), '.');
1186:         
1187:         // And then append 'E' and the exponent (adjExp).
1188:         val.append('E');
1189:         if (adjExp >= 0)
1190:           val.append('+');
1191:         val.append(adjExp);
1192:       }
1193:     return val.toString();
1194:   }
1195:   
1196:   /**
1197:    * Returns a String representation of this BigDecimal without using 
1198:    * scientific notation.  This is how toString() worked for releases 1.4
1199:    * and previous.  Zeros may be added to the end of the String.  For
1200:    * example, an unscaled value of 1234 and a scale of -3 would result in 
1201:    * the String 1234000, but the toString() method would return 
1202:    * 1.234E+6.
1203:    * @return a String representation of this BigDecimal
1204:    * @since 1.5
1205:    */
1206:   public String toPlainString()
1207:   {
1208:     // If the scale is zero we simply return the String representation of the 
1209:     // unscaled value.
1210:     String bigStr = intVal.toString();
1211:     if (scale == 0)
1212:       return bigStr;
1213: 
1214:     // Remember if we have to put a negative sign at the start.
1215:     boolean negative = (bigStr.charAt(0) == '-');
1216: 
1217:     int point = bigStr.length() - scale - (negative ? 1 : 0);
1218: 
1219:     StringBuffer sb = new StringBuffer(bigStr.length() + 2
1220:                                        + (point <= 0 ? (-point + 1) : 0));
1221:     if (point <= 0)
1222:       {
1223:         // We have to prepend zeros and a decimal point.
1224:         if (negative)
1225:           sb.append('-');
1226:         sb.append('0').append('.');
1227:         while (point < 0)
1228:           {
1229:             sb.append('0');
1230:             point++;
1231:           }
1232:         sb.append(bigStr.substring(negative ? 1 : 0));
1233:       }
1234:     else if (point < bigStr.length())
1235:       {
1236:         // No zeros need to be prepended or appended, just put the decimal
1237:         // in the right place.
1238:         sb.append(bigStr);
1239:         sb.insert(point + (negative ? 1 : 0), '.');
1240:       }
1241:     else
1242:       {
1243:         // We must append zeros instead of using scientific notation.
1244:         sb.append(bigStr);
1245:         for (int i = bigStr.length(); i < point; i++)
1246:           sb.append('0');
1247:       }
1248:     return sb.toString();
1249:   }
1250:   
1251:   /**
1252:    * Converts this BigDecimal to a BigInteger.  Any fractional part will
1253:    * be discarded.
1254:    * @return a BigDecimal whose value is equal to floor[this]
1255:    */
1256:   public BigInteger toBigInteger () 
1257:   {
1258:     // If scale > 0 then we must divide, if scale > 0 then we must multiply,
1259:     // and if scale is zero then we just return intVal;
1260:     if (scale > 0)
1261:       return intVal.divide (BigInteger.TEN.pow (scale));
1262:     else if (scale < 0)
1263:       return intVal.multiply(BigInteger.TEN.pow(-scale));
1264:     return intVal;
1265:   }
1266:   
1267:   /**
1268:    * Converts this BigDecimal into a BigInteger, throwing an 
1269:    * ArithmeticException if the conversion is not exact.
1270:    * @return a BigInteger whose value is equal to the value of this BigDecimal
1271:    * @since 1.5
1272:    */
1273:   public BigInteger toBigIntegerExact()
1274:   {
1275:     if (scale > 0)
1276:       {
1277:         // If we have to divide, we must check if the result is exact.
1278:         BigInteger[] result = 
1279:           intVal.divideAndRemainder(BigInteger.TEN.pow(scale));
1280:         if (result[1].equals(BigInteger.ZERO))
1281:           return result[0];
1282:         throw new ArithmeticException("No exact BigInteger representation");
1283:       }
1284:     else if (scale < 0)
1285:       // If we're multiplying instead, then we needn't check for exactness.
1286:       return intVal.multiply(BigInteger.TEN.pow(-scale));
1287:     // If the scale is zero we can simply return intVal.
1288:     return intVal;
1289:   }
1290: 
1291:   public int intValue () 
1292:   {
1293:     return toBigInteger ().intValue ();
1294:   }
1295:   
1296:   /**
1297:    * Returns a BigDecimal which is numerically equal to this BigDecimal but 
1298:    * with no trailing zeros in the representation.  For example, if this 
1299:    * BigDecimal has [unscaledValue, scale] = [6313000, 4] this method returns
1300:    * a BigDecimal with [unscaledValue, scale] = [6313, 1].  As another 
1301:    * example, [12400, -2] would become [124, -4].
1302:    * @return a numerically equal BigDecimal with no trailing zeros
1303:    */
1304:   public BigDecimal stripTrailingZeros()  
1305:   {
1306:     String intValStr = intVal.toString();
1307:     int newScale = scale;
1308:     int pointer = intValStr.length() - 1;
1309:     // This loop adjusts pointer which will be used to give us the substring
1310:     // of intValStr to use in our new BigDecimal, and also accordingly
1311:     // adjusts the scale of our new BigDecimal.
1312:     while (intValStr.charAt(pointer) == '0')
1313:       {
1314:         pointer --;
1315:         newScale --;
1316:       }
1317:     // Create a new BigDecimal with the appropriate substring and then
1318:     // set its scale.
1319:     BigDecimal result = new BigDecimal(intValStr.substring(0, pointer + 1));    
1320:     result.scale = newScale;
1321:     return result;
1322:   }
1323: 
1324:   public long longValue ()
1325:   {
1326:     return toBigInteger().longValue();
1327:   }
1328: 
1329:   public float floatValue() 
1330:   {
1331:     return Float.valueOf(toString()).floatValue();
1332:   }
1333: 
1334:   public double doubleValue() 
1335:   {
1336:     return Double.valueOf(toString()).doubleValue();
1337:   }
1338: 
1339:   public BigDecimal setScale (int scale) throws ArithmeticException
1340:   {
1341:     return setScale (scale, ROUND_UNNECESSARY);
1342:   }
1343: 
1344:   public BigDecimal setScale (int scale, int roundingMode)
1345:     throws ArithmeticException, IllegalArgumentException
1346:   {
1347:     // NOTE: The 1.5 JRE doesn't throw this, ones prior to it do and
1348:     // the spec says it should. Nevertheless, if 1.6 doesn't fix this
1349:     // we should consider removing it.
1350:     if( scale < 0 ) throw new ArithmeticException("Scale parameter < 0.");
1351:     return divide (ONE, scale, roundingMode);
1352:   }
1353:    
1354:   /**
1355:    * Returns a new BigDecimal constructed from the BigDecimal(String) 
1356:    * constructor using the Double.toString(double) method to obtain
1357:    * the String.
1358:    * @param val the double value used in Double.toString(double)
1359:    * @return a BigDecimal representation of val
1360:    * @throws NumberFormatException if val is NaN or infinite
1361:    * @since 1.5
1362:    */
1363:   public static BigDecimal valueOf(double val)
1364:   {
1365:     if (Double.isInfinite(val) || Double.isNaN(val))
1366:       throw new NumberFormatException("argument cannot be NaN or infinite.");
1367:     return new BigDecimal(Double.toString(val));
1368:   }
1369:   
1370:   /**
1371:    * Returns a BigDecimal whose numerical value is the numerical value
1372:    * of this BigDecimal multiplied by 10 to the power of <code>n</code>. 
1373:    * @param n the power of ten
1374:    * @return the new BigDecimal
1375:    * @since 1.5
1376:    */
1377:   public BigDecimal scaleByPowerOfTen(int n)
1378:   {
1379:     BigDecimal result = new BigDecimal(intVal, scale - n);
1380:     result.precision = precision;
1381:     return result;
1382:   }
1383:   
1384:   /**
1385:    * Returns a BigDecimal whose value is <code>this</code> to the power of 
1386:    * <code>n</code>. 
1387:    * @param n the power
1388:    * @return the new BigDecimal
1389:    * @since 1.5
1390:    */
1391:   public BigDecimal pow(int n)
1392:   {
1393:     if (n < 0 || n > 999999999)
1394:       throw new ArithmeticException("n must be between 0 and 999999999");
1395:     BigDecimal result = new BigDecimal(intVal.pow(n), scale * n);
1396:     return result;
1397:   }
1398:   
1399:   /**
1400:    * Returns a BigDecimal whose value is determined by first calling pow(n)
1401:    * and then by rounding according to the MathContext mc.
1402:    * @param n the power
1403:    * @param mc the MathContext
1404:    * @return the new BigDecimal
1405:    * @throws ArithmeticException if n < 0 or n > 999999999 or if the result is
1406:    * inexact but the rounding is RoundingMode.UNNECESSARY
1407:    * @since 1.5
1408:    */
1409:   public BigDecimal pow(int n, MathContext mc)
1410:   {
1411:     // FIXME: The specs claim to use the X3.274-1996 algorithm.  We
1412:     // currently do not.
1413:     return pow(n).round(mc);
1414:   }
1415:   
1416:   /**
1417:    * Returns a BigDecimal whose value is the absolute value of this BigDecimal
1418:    * with rounding according to the given MathContext.
1419:    * @param mc the MathContext
1420:    * @return the new BigDecimal
1421:    */
1422:   public BigDecimal abs(MathContext mc)
1423:   {
1424:     BigDecimal result = abs();
1425:     result = result.round(mc);
1426:     return result;
1427:   }
1428:   
1429:   /**
1430:    * Returns the size of a unit in the last place of this BigDecimal.  This
1431:    * returns a BigDecimal with [unscaledValue, scale] = [1, this.scale()].
1432:    * @return the size of a unit in the last place of <code>this</code>.
1433:    * @since 1.5
1434:    */
1435:   public BigDecimal ulp()
1436:   {
1437:     return new BigDecimal(BigInteger.ONE, scale);
1438:   }
1439:   
1440:   /**
1441:    * Converts this BigDecimal to a long value.
1442:    * @return the long value
1443:    * @throws ArithmeticException if rounding occurs or if overflow occurs
1444:    * @since 1.5
1445:    */
1446:   public long longValueExact()
1447:   {
1448:     // Set scale will throw an exception if rounding occurs.
1449:     BigDecimal temp = setScale(0, ROUND_UNNECESSARY);
1450:     BigInteger tempVal = temp.intVal;
1451:     // Check for overflow.
1452:     long result = intVal.longValue();
1453:     if (tempVal.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 1
1454:         || (result < 0 && signum() == 1) || (result > 0 && signum() == -1))
1455:       throw new ArithmeticException("this BigDecimal is too " +
1456:             "large to fit into the return type");
1457:     
1458:     return intVal.longValue();
1459:   }
1460:   
1461:   /**
1462:    * Converts this BigDecimal into an int by first calling longValueExact
1463:    * and then checking that the <code>long</code> returned from that
1464:    * method fits into an <code>int</code>.
1465:    * @return an int whose value is <code>this</code>
1466:    * @throws ArithmeticException if this BigDecimal has a fractional part
1467:    * or is too large to fit into an int.
1468:    * @since 1.5
1469:    */
1470:   public int intValueExact()
1471:   {
1472:     long temp = longValueExact();
1473:     int result = (int)temp;
1474:     if (result != temp)
1475:       throw new ArithmeticException ("this BigDecimal cannot fit into an int");
1476:     return result;
1477:   }
1478:   
1479:   /**
1480:    * Converts this BigDecimal into a byte by first calling longValueExact
1481:    * and then checking that the <code>long</code> returned from that
1482:    * method fits into a <code>byte</code>.
1483:    * @return a byte whose value is <code>this</code>
1484:    * @throws ArithmeticException if this BigDecimal has a fractional part
1485:    * or is too large to fit into a byte.
1486:    * @since 1.5
1487:    */
1488:   public byte byteValueExact()
1489:   {
1490:     long temp = longValueExact();
1491:     byte result = (byte)temp;
1492:     if (result != temp)
1493:       throw new ArithmeticException ("this BigDecimal cannot fit into a byte");
1494:     return result;
1495:   }
1496:   
1497:   /**
1498:    * Converts this BigDecimal into a short by first calling longValueExact
1499:    * and then checking that the <code>long</code> returned from that
1500:    * method fits into a <code>short</code>.
1501:    * @return a short whose value is <code>this</code>
1502:    * @throws ArithmeticException if this BigDecimal has a fractional part
1503:    * or is too large to fit into a short.
1504:    * @since 1.5
1505:    */
1506:   public short shortValueExact()
1507:   {
1508:     long temp = longValueExact();
1509:     short result = (short)temp;
1510:     if (result != temp)
1511:       throw new ArithmeticException ("this BigDecimal cannot fit into a short");
1512:     return result;
1513:   }
1514: }