KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > icu > math > BigDecimal


1 //##header 1189099963000 FOUNDATION
2
/* Generated from 'BigDecimal.nrx' 8 Sep 2000 11:10:50 [v2.00] */
3 /* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
4 package com.ibm.icu.math;
5 import java.math.BigInteger JavaDoc;
6 import com.ibm.icu.impl.Utility;
7
8 /* ------------------------------------------------------------------ */
9 /* BigDecimal -- Decimal arithmetic for Java */
10 /* ------------------------------------------------------------------ */
11 /* Copyright IBM Corporation, 1996-2006. All Rights Reserved. */
12 /* */
13 /* The BigDecimal class provides immutable arbitrary-precision */
14 /* floating point (including integer) decimal numbers. */
15 /* */
16 /* As the numbers are decimal, there is an exact correspondence */
17 /* between an instance of a BigDecimal object and its String */
18 /* representation; the BigDecimal class provides direct conversions */
19 /* to and from String and character array objects, and well as */
20 /* conversions to and from the Java primitive types (which may not */
21 /* be exact). */
22 /* ------------------------------------------------------------------ */
23 /* Notes: */
24 /* */
25 /* 1. A BigDecimal object is never changed in value once constructed; */
26 /* this avoids the need for locking. Note in particular that the */
27 /* mantissa array may be shared between many BigDecimal objects, */
28 /* so that once exposed it must not be altered. */
29 /* */
30 /* 2. This class looks at MathContext class fields directly (for */
31 /* performance). It must not and does not change them. */
32 /* */
33 /* 3. Exponent checking is delayed until finish(), as we know */
34 /* intermediate calculations cannot cause 31-bit overflow. */
35 /* [This assertion depends on MAX_DIGITS in MathContext.] */
36 /* */
37 /* 4. Comments for the public API now follow the javadoc conventions. */
38 /* The NetRexx -comments option is used to pass these comments */
39 /* through to the generated Java code (with -format, if desired). */
40 /* */
41 /* 5. System.arraycopy is faster than explicit loop as follows */
42 /* Mean length 4: equal */
43 /* Mean length 8: x2 */
44 /* Mean length 16: x3 */
45 /* Mean length 24: x4 */
46 /* From prior experience, we expect mean length a little below 8, */
47 /* but arraycopy is still the one to use, in general, until later */
48 /* measurements suggest otherwise. */
49 /* */
50 /* 6. 'DMSRCN' referred to below is the original (1981) IBM S/370 */
51 /* assembler code implementation of the algorithms below; it is */
52 /* now called IXXRCN and is available with the OS/390 and VM/ESA */
53 /* operating systems. */
54 /* ------------------------------------------------------------------ */
55 /* Change History: */
56 /* 1997.09.02 Initial version (derived from netrexx.lang classes) */
57 /* 1997.09.12 Add lostDigits checking */
58 /* 1997.10.06 Change mantissa to a byte array */
59 /* 1997.11.22 Rework power [did not prepare arguments, etc.] */
60 /* 1997.12.13 multiply did not prepare arguments */
61 /* 1997.12.14 add did not prepare and align arguments correctly */
62 /* 1998.05.02 0.07 packaging changes suggested by Sun and Oracle */
63 /* 1998.05.21 adjust remainder operator finalization */
64 /* 1998.06.04 rework to pass MathContext to finish() and round() */
65 /* 1998.06.06 change format to use round(); support rounding modes */
66 /* 1998.06.25 rename to BigDecimal and begin merge */
67 /* zero can now have trailing zeros (i.e., exp\=0) */
68 /* 1998.06.28 new methods: movePointXxxx, scale, toBigInteger */
69 /* unscaledValue, valueof */
70 /* 1998.07.01 improve byteaddsub to allow array reuse, etc. */
71 /* 1998.07.01 make null testing explicit to avoid JIT bug [Win32] */
72 /* 1998.07.07 scaled division [divide(BigDecimal, int, int)] */
73 /* 1998.07.08 setScale, faster equals */
74 /* 1998.07.11 allow 1E6 (no sign) <sigh>; new double/float conversion */
75 /* 1998.10.12 change package to com.ibm.icu.math */
76 /* 1998.12.14 power operator no longer rounds RHS [to match ANSI] */
77 /* add toBigDecimal() and BigDecimal(java.math.BigDecimal) */
78 /* 1998.12.29 improve byteaddsub by using table lookup */
79 /* 1999.02.04 lostdigits=0 behaviour rounds instead of digits+1 guard */
80 /* 1999.02.05 cleaner code for BigDecimal(char[]) */
81 /* 1999.02.06 add javadoc comments */
82 /* 1999.02.11 format() changed from 7 to 2 method form */
83 /* 1999.03.05 null pointer checking is no longer explicit */
84 /* 1999.03.05 simplify; changes from discussion with J. Bloch: */
85 /* null no longer permitted for MathContext; drop boolean, */
86 /* byte, char, float, short constructor, deprecate double */
87 /* constructor, no blanks in string constructor, add */
88 /* offset and length version of char[] constructor; */
89 /* add valueOf(double); drop booleanValue, charValue; */
90 /* add ...Exact versions of remaining convertors */
91 /* 1999.03.13 add toBigIntegerExact */
92 /* 1999.03.13 1.00 release to IBM Centre for Java Technology */
93 /* 1999.05.27 1.01 correct 0-0.2 bug under scaled arithmetic */
94 /* 1999.06.29 1.02 constructors should not allow exponent > 9 digits */
95 /* 1999.07.03 1.03 lost digits should not be checked if digits=0 */
96 /* 1999.07.06 lost digits Exception message changed */
97 /* 1999.07.10 1.04 more work on 0-0.2 (scaled arithmetic) */
98 /* 1999.07.17 improve messages from pow method */
99 /* 1999.08.08 performance tweaks */
100 /* 1999.08.15 fastpath in multiply */
101 /* 1999.11.05 1.05 fix problem in intValueExact [e.g., 5555555555] */
102 /* 1999.12.22 1.06 remove multiply fastpath, and improve performance */
103 /* 2000.01.01 copyright update [Y2K has arrived] */
104 /* 2000.06.18 1.08 no longer deprecate BigDecimal(double) */
105 /* ------------------------------------------------------------------ */
106
107
108
109
110
111 /**
112  * The <code>BigDecimal</code> class implements immutable
113  * arbitrary-precision decimal numbers. The methods of the
114  * <code>BigDecimal</code> class provide operations for fixed and
115  * floating point arithmetic, comparison, format conversions, and
116  * hashing.
117  * <p>
118  * As the numbers are decimal, there is an exact correspondence between
119  * an instance of a <code>BigDecimal</code> object and its
120  * <code>String</code> representation; the <code>BigDecimal</code> class
121  * provides direct conversions to and from <code>String</code> and
122  * character array (<code>char[]</code>) objects, as well as conversions
123  * to and from the Java primitive types (which may not be exact) and
124  * <code>BigInteger</code>.
125  * <p>
126  * In the descriptions of constructors and methods in this documentation,
127  * the value of a <code>BigDecimal</code> number object is shown as the
128  * result of invoking the <code>toString()</code> method on the object.
129  * The internal representation of a decimal number is neither defined
130  * nor exposed, and is not permitted to affect the result of any
131  * operation.
132  * <p>
133  * The floating point arithmetic provided by this class is defined by
134  * the ANSI X3.274-1996 standard, and is also documented at
135  * <code>http://www2.hursley.ibm.com/decimal</code>
136  * <br><i>[This URL will change.]</i>
137  *
138  * <h3>Operator methods</h3>
139  * <p>
140  * Operations on <code>BigDecimal</code> numbers are controlled by a
141  * {@link MathContext} object, which provides the context (precision and
142  * other information) for the operation. Methods that can take a
143  * <code>MathContext</code> parameter implement the standard arithmetic
144  * operators for <code>BigDecimal</code> objects and are known as
145  * <i>operator methods</i>. The default settings provided by the
146  * constant {@link MathContext#DEFAULT} (<code>digits=9,
147  * form=SCIENTIFIC, lostDigits=false, roundingMode=ROUND_HALF_UP</code>)
148  * perform general-purpose floating point arithmetic to nine digits of
149  * precision. The <code>MathContext</code> parameter must not be
150  * <code>null</code>.
151  * <p>
152  * Each operator method also has a version provided which does
153  * not take a <code>MathContext</code> parameter. For this version of
154  * each method, the context settings used are <code>digits=0,
155  * form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP</code>;
156  * these settings perform fixed point arithmetic with unlimited
157  * precision, as defined for the original BigDecimal class in Java 1.1
158  * and Java 1.2.
159  * <p>
160  * For monadic operators, only the optional <code>MathContext</code>
161  * parameter is present; the operation acts upon the current object.
162  * <p>
163  * For dyadic operators, a <code>BigDecimal</code> parameter is always
164  * present; it must not be <code>null</code>.
165  * The operation acts with the current object being the left-hand operand
166  * and the <code>BigDecimal</code> parameter being the right-hand operand.
167  * <p>
168  * For example, adding two <code>BigDecimal</code> objects referred to
169  * by the names <code>award</code> and <code>extra</code> could be
170  * written as any of:
171  * <p><code>
172  * award.add(extra)
173  * <br>award.add(extra, MathContext.DEFAULT)
174  * <br>award.add(extra, acontext)
175  * </code>
176  * <p>
177  * (where <code>acontext</code> is a <code>MathContext</code> object),
178  * which would return a <code>BigDecimal</code> object whose value is
179  * the result of adding <code>award</code> and <code>extra</code> under
180  * the appropriate context settings.
181  * <p>
182  * When a <code>BigDecimal</code> operator method is used, a set of
183  * rules define what the result will be (and, by implication, how the
184  * result would be represented as a character string).
185  * These rules are defined in the BigDecimal arithmetic documentation
186  * (see the URL above), but in summary:
187  * <ul>
188  * <li>Results are normally calculated with up to some maximum number of
189  * significant digits.
190  * For example, if the <code>MathContext</code> parameter for an operation
191  * were <code>MathContext.DEFAULT</code> then the result would be
192  * rounded to 9 digits; the division of 2 by 3 would then result in
193  * 0.666666667.
194  * <br>
195  * You can change the default of 9 significant digits by providing the
196  * method with a suitable <code>MathContext</code> object. This lets you
197  * calculate using as many digits as you need -- thousands, if necessary.
198  * Fixed point (scaled) arithmetic is indicated by using a
199  * <code>digits</code> setting of 0 (or omitting the
200  * <code>MathContext</code> parameter).
201  * <br>
202  * Similarly, you can change the algorithm used for rounding from the
203  * default "classic" algorithm.
204  * <li>
205  * In standard arithmetic (that is, when the <code>form</code> setting
206  * is not <code>PLAIN</code>), a zero result is always expressed as the
207  * single digit <code>'0'</code> (that is, with no sign, decimal point,
208  * or exponent part).
209  * <li>
210  * Except for the division and power operators in standard arithmetic,
211  * trailing zeros are preserved (this is in contrast to binary floating
212  * point operations and most electronic calculators, which lose the
213  * information about trailing zeros in the fractional part of results).
214  * <br>
215  * So, for example:
216  * <p><code>
217  * new BigDecimal("2.40").add( new BigDecimal("2")) =&gt; "4.40"
218  * <br>new BigDecimal("2.40").subtract(new BigDecimal("2")) =&gt; "0.40"
219  * <br>new BigDecimal("2.40").multiply(new BigDecimal("2")) =&gt; "4.80"
220  * <br>new BigDecimal("2.40").divide( new BigDecimal("2"), def) =&gt; "1.2"
221  * </code>
222  * <p>where the value on the right of the <code>=&gt;</code> would be the
223  * result of the operation, expressed as a <code>String</code>, and
224  * <code>def</code> (in this and following examples) refers to
225  * <code>MathContext.DEFAULT</code>).
226  * This preservation of trailing zeros is desirable for most
227  * calculations (including financial calculations).
228  * If necessary, trailing zeros may be easily removed using division by 1.
229  * <li>
230  * In standard arithmetic, exponential form is used for a result
231  * depending on its value and the current setting of <code>digits</code>
232  * (the default is 9 digits).
233  * If the number of places needed before the decimal point exceeds the
234  * <code>digits</code> setting, or the absolute value of the number is
235  * less than <code>0.000001</code>, then the number will be expressed in
236  * exponential notation; thus
237  * <p><code>
238  * new BigDecimal("1e+6").multiply(new BigDecimal("1e+6"), def)
239  * </code>
240  * <p>results in <code>1E+12</code> instead of
241  * <code>1000000000000</code>, and
242  * <p><code>
243  * new BigDecimal("1").divide(new BigDecimal("3E+10"), def)
244  * </code>
245  * <p>results in <code>3.33333333E-11</code> instead of
246  * <code>0.0000000000333333333</code>.
247  * <p>
248  * The form of the exponential notation (scientific or engineering) is
249  * determined by the <code>form</code> setting.
250  * <eul>
251  * <p>
252  * The names of methods in this class follow the conventions established
253  * by <code>java.lang.Number</code>, <code>java.math.BigInteger</code>,
254  * and <code>java.math.BigDecimal</code> in Java 1.1 and Java 1.2.
255  *
256  * @see MathContext
257  * @author Mike Cowlishaw
258  * @stable ICU 2.0
259  */

260
261 public class BigDecimal extends java.lang.Number JavaDoc implements java.io.Serializable JavaDoc,java.lang.Comparable JavaDoc{
262  private static final java.lang.String JavaDoc $0="BigDecimal.nrx";
263  
264  
265  
266  /* ----- Constants ----- */
267  /* properties constant public */ // useful to others
268
/**
269   * The <code>BigDecimal</code> constant "0".
270   *
271   * @see #ONE
272   * @see #TEN
273   * @stable ICU 2.0
274   */

275  public static final com.ibm.icu.math.BigDecimal ZERO=new com.ibm.icu.math.BigDecimal((long)0); // use long as we want the int constructor
276
// .. to be able to use this, for speed
277

278  /**
279   * The <code>BigDecimal</code> constant "1".
280   *
281   * @see #TEN
282   * @see #ZERO
283   * @stable ICU 2.0
284   */

285  public static final com.ibm.icu.math.BigDecimal ONE=new com.ibm.icu.math.BigDecimal((long)1); // use long as we want the int constructor
286
// .. to be able to use this, for speed
287

288  /**
289   * The <code>BigDecimal</code> constant "10".
290   *
291   * @see #ONE
292   * @see #ZERO
293   * @stable ICU 2.0
294   */

295  public static final com.ibm.icu.math.BigDecimal TEN=new com.ibm.icu.math.BigDecimal(10);
296  
297  // the rounding modes (copied here for upwards compatibility)
298
/**
299   * Rounding mode to round to a more positive number.
300   * @see MathContext#ROUND_CEILING
301   * @stable ICU 2.0
302   */

303  public static final int ROUND_CEILING=com.ibm.icu.math.MathContext.ROUND_CEILING;
304  
305  /**
306   * Rounding mode to round towards zero.
307   * @see MathContext#ROUND_DOWN
308   * @stable ICU 2.0
309   */

310  public static final int ROUND_DOWN=com.ibm.icu.math.MathContext.ROUND_DOWN;
311  
312  /**
313   * Rounding mode to round to a more negative number.
314   * @see MathContext#ROUND_FLOOR
315   * @stable ICU 2.0
316   */

317  public static final int ROUND_FLOOR=com.ibm.icu.math.MathContext.ROUND_FLOOR;
318  
319  /**
320   * Rounding mode to round to nearest neighbor, where an equidistant
321   * value is rounded down.
322   * @see MathContext#ROUND_HALF_DOWN
323   * @stable ICU 2.0
324   */

325  public static final int ROUND_HALF_DOWN=com.ibm.icu.math.MathContext.ROUND_HALF_DOWN;
326  
327  /**
328   * Rounding mode to round to nearest neighbor, where an equidistant
329   * value is rounded to the nearest even neighbor.
330   * @see MathContext#ROUND_HALF_EVEN
331   * @stable ICU 2.0
332   */

333  public static final int ROUND_HALF_EVEN=com.ibm.icu.math.MathContext.ROUND_HALF_EVEN;
334  
335  /**
336   * Rounding mode to round to nearest neighbor, where an equidistant
337   * value is rounded up.
338   * @see MathContext#ROUND_HALF_UP
339   * @stable ICU 2.0
340   */

341  public static final int ROUND_HALF_UP=com.ibm.icu.math.MathContext.ROUND_HALF_UP;
342  
343  /**
344   * Rounding mode to assert that no rounding is necessary.
345   * @see MathContext#ROUND_UNNECESSARY
346   * @stable ICU 2.0
347   */

348  public static final int ROUND_UNNECESSARY=com.ibm.icu.math.MathContext.ROUND_UNNECESSARY;
349  
350  /**
351   * Rounding mode to round away from zero.
352   * @see MathContext#ROUND_UP
353   * @stable ICU 2.0
354   */

355  public static final int ROUND_UP=com.ibm.icu.math.MathContext.ROUND_UP;
356  
357  /* properties constant private */ // locals
358
private static final byte ispos=1; // ind: indicates positive (must be 1)
359
private static final byte iszero=0; // ind: indicates zero (must be 0)
360
private static final byte isneg=-1; // ind: indicates negative (must be -1)
361
// [later could add NaN, +/- infinity, here]
362

363  private static final int MinExp=-999999999; // minimum exponent allowed
364
private static final int MaxExp=999999999; // maximum exponent allowed
365
private static final int MinArg=-999999999; // minimum argument integer
366
private static final int MaxArg=999999999; // maximum argument integer
367

368  private static final com.ibm.icu.math.MathContext plainMC=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN); // context for plain unlimited math
369

370  /* properties constant private unused */ // present but not referenced
371

372  // Serialization version
373
private static final long serialVersionUID=8245355804974198832L;
374  
375  private static final java.lang.String JavaDoc copyright=" Copyright (c) IBM Corporation 1996, 2000. All rights reserved. ";
376  
377  /* properties static private */
378  // Precalculated constant arrays (used by byteaddsub)
379
private static byte bytecar[]=new byte[(90+99)+1]; // carry/borrow array
380
private static byte bytedig[]=diginit(); // next digit array
381

382  /* ----- Instance properties [all private and immutable] ----- */
383  /* properties private */
384  
385  /**
386   * The indicator. This may take the values:
387   * <ul>
388   * <li>ispos -- the number is positive
389   * <li>iszero -- the number is zero
390   * <li>isneg -- the number is negative
391   * </ul>
392   *
393   * @serial
394   */

395  private byte ind; // assumed undefined
396
// Note: some code below assumes IND = Sign [-1, 0, 1], at present.
397
// We only need two bits for this, but use a byte [also permits
398
// smooth future extension].
399

400  /**
401   * The formatting style. This may take the values:
402   * <ul>
403   * <li>MathContext.PLAIN -- no exponent needed
404   * <li>MathContext.SCIENTIFIC -- scientific notation required
405   * <li>MathContext.ENGINEERING -- engineering notation required
406   * </ul>
407   * <p>
408   * This property is an optimization; it allows us to defer number
409   * layout until it is actually needed as a string, hence avoiding
410   * unnecessary formatting.
411   *
412   * @serial
413   */

414  private byte form=(byte)com.ibm.icu.math.MathContext.PLAIN; // assumed PLAIN
415
// We only need two bits for this, at present, but use a byte
416
// [again, to allow for smooth future extension]
417

418  /**
419   * The value of the mantissa.
420   * <p>
421   * Once constructed, this may become shared between several BigDecimal
422   * objects, so must not be altered.
423   * <p>
424   * For efficiency (speed), this is a byte array, with each byte
425   * taking a value of 0 -> 9.
426   * <p>
427   * If the first byte is 0 then the value of the number is zero (and
428   * mant.length=1, except when constructed from a plain number, for
429   * example, 0.000).
430   *
431   * @serial
432   */

433  private byte mant[]; // assumed null
434

435  /**
436   * The exponent.
437   * <p>
438   * For fixed point arithmetic, scale is <code>-exp</code>, and can
439   * apply to zero.
440   *
441   * Note that this property can have a value less than MinExp when
442   * the mantissa has more than one digit.
443   *
444   * @serial
445   */

446  private int exp;
447  // assumed 0
448

449  /* ---------------------------------------------------------------- */
450  /* Constructors */
451  /* ---------------------------------------------------------------- */
452  
453 //#ifndef FOUNDATION
454
//## /**
455
//## * Constructs a <code>BigDecimal</code> object from a
456
//## * <code>java.math.BigDecimal</code>.
457
//## * <p>
458
//## * Constructs a <code>BigDecimal</code> as though the parameter had
459
//## * been represented as a <code>String</code> (using its
460
//## * <code>toString</code> method) and the
461
//## * {@link #BigDecimal(java.lang.String)} constructor had then been
462
//## * used.
463
//## * The parameter must not be <code>null</code>.
464
//## * <p>
465
//## * <i>(Note: this constructor is provided only in the
466
//## * <code>com.ibm.icu.math</code> version of the BigDecimal class.
467
//## * It would not be present in a <code>java.math</code> version.)</i>
468
//## *
469
//## * @param bd The <code>BigDecimal</code> to be translated.
470
//## * @stable ICU 2.0
471
//## */
472
//##
473
//## public BigDecimal(java.math.BigDecimal bd){
474
//## this(bd.toString());
475
//## return;}
476
//#endif
477

478  /**
479   * Constructs a <code>BigDecimal</code> object from a
480   * <code>BigInteger</code>, with scale 0.
481   * <p>
482   * Constructs a <code>BigDecimal</code> which is the exact decimal
483   * representation of the <code>BigInteger</code>, with a scale of
484   * zero.
485   * The value of the <code>BigDecimal</code> is identical to the value
486   * of the <code>BigInteger</code>.
487   * The parameter must not be <code>null</code>.
488   * <p>
489   * The <code>BigDecimal</code> will contain only decimal digits,
490   * prefixed with a leading minus sign (hyphen) if the
491   * <code>BigInteger</code> is negative. A leading zero will be
492   * present only if the <code>BigInteger</code> is zero.
493   *
494   * @param bi The <code>BigInteger</code> to be converted.
495   * @stable ICU 2.0
496   */

497  
498  public BigDecimal(java.math.BigInteger JavaDoc bi){
499   this(bi.toString(10));
500   return;}
501  // exp remains 0
502

503  /**
504   * Constructs a <code>BigDecimal</code> object from a
505   * <code>BigInteger</code> and a scale.
506   * <p>
507   * Constructs a <code>BigDecimal</code> which is the exact decimal
508   * representation of the <code>BigInteger</code>, scaled by the
509   * second parameter, which may not be negative.
510   * The value of the <code>BigDecimal</code> is the
511   * <code>BigInteger</code> divided by ten to the power of the scale.
512   * The <code>BigInteger</code> parameter must not be
513   * <code>null</code>.
514   * <p>
515   * The <code>BigDecimal</code> will contain only decimal digits, (with
516   * an embedded decimal point followed by <code>scale</code> decimal
517   * digits if the scale is positive), prefixed with a leading minus
518   * sign (hyphen) if the <code>BigInteger</code> is negative. A
519   * leading zero will be present only if the <code>BigInteger</code> is
520   * zero.
521   *
522   * @param bi The <code>BigInteger</code> to be converted.
523   * @param scale The <code>int</code> specifying the scale.
524   * @throws NumberFormatException if the scale is negative.
525   * @stable ICU 2.0
526   */

527  
528  public BigDecimal(java.math.BigInteger JavaDoc bi,int scale){
529   this(bi.toString(10));
530   if (scale<0)
531    throw new java.lang.NumberFormatException JavaDoc("Negative scale:"+" "+scale);
532   exp=(int)-scale; // exponent is -scale
533
return;}
534
535  /**
536   * Constructs a <code>BigDecimal</code> object from an array of characters.
537   * <p>
538   * Constructs a <code>BigDecimal</code> as though a
539   * <code>String</code> had been constructed from the character array
540   * and the {@link #BigDecimal(java.lang.String)} constructor had then
541   * been used. The parameter must not be <code>null</code>.
542   * <p>
543   * Using this constructor is faster than using the
544   * <code>BigDecimal(String)</code> constructor if the string is
545   * already available in character array form.
546   *
547   * @param inchars The <code>char[]</code> array containing the number
548   * to be converted.
549   * @throws NumberFormatException if the parameter is not a valid
550   * number.
551   * @stable ICU 2.0
552   */

553  
554  public BigDecimal(char inchars[]){
555   this(inchars,0,inchars.length);
556   return;}
557
558  /**
559   * Constructs a <code>BigDecimal</code> object from an array of characters.
560   * <p>
561   * Constructs a <code>BigDecimal</code> as though a
562   * <code>String</code> had been constructed from the character array
563   * (or a subarray of that array) and the
564   * {@link #BigDecimal(java.lang.String)} constructor had then been
565   * used. The first parameter must not be <code>null</code>, and the
566   * subarray must be wholly contained within it.
567   * <p>
568   * Using this constructor is faster than using the
569   * <code>BigDecimal(String)</code> constructor if the string is
570   * already available within a character array.
571   *
572   * @param inchars The <code>char[]</code> array containing the number
573   * to be converted.
574   * @param offset The <code>int</code> offset into the array of the
575   * start of the number to be converted.
576   * @param length The <code>int</code> length of the number.
577   * @throws NumberFormatException if the parameter is not a valid
578   * number for any reason.
579   * @stable ICU 2.0
580   */

581  
582  public BigDecimal(char inchars[],int offset,int length){super();
583   boolean exotic;
584   boolean hadexp;
585   int d;
586   int dotoff;
587   int last;
588   int i=0;
589   char si=0;
590   boolean eneg=false;
591   int k=0;
592   int elen=0;
593   int j=0;
594   char sj=0;
595   int dvalue=0;
596   int mag=0;
597   // This is the primary constructor; all incoming strings end up
598
// here; it uses explicit (inline) parsing for speed and to avoid
599
// generating intermediate (temporary) objects of any kind.
600
// 1998.06.25: exponent form built only if E/e in string
601
// 1998.06.25: trailing zeros not removed for zero
602
// 1999.03.06: no embedded blanks; allow offset and length
603
if (length<=0)
604    bad(inchars); // bad conversion (empty string)
605
// [bad offset will raise array bounds exception]
606

607   /* Handle and step past sign */
608   ind=ispos; // assume positive
609
if (inchars[offset]==('-'))
610    {
611     length--;
612     if (length==0)
613      bad(inchars); // nothing after sign
614
ind=isneg;
615     offset++;
616    }
617   else
618    if (inchars[offset]==('+'))
619     {
620      length--;
621      if (length==0)
622       bad(inchars); // nothing after sign
623
offset++;
624     }
625   
626   /* We're at the start of the number */
627   exotic=false; // have extra digits
628
hadexp=false; // had explicit exponent
629
d=0; // count of digits found
630
dotoff=-1; // offset where dot was found
631
last=-1; // last character of mantissa
632
{int $1=length;i=offset;i:for(;$1>0;$1--,i++){
633    si=inchars[i];
634    if (si>='0') // test for Arabic digit
635
if (si<='9')
636      {
637       last=i;
638       d++; // still in mantissa
639
continue i;
640      }
641    if (si=='.')
642     { // record and ignore
643
if (dotoff>=0)
644       bad(inchars); // two dots
645
dotoff=i-offset; // offset into mantissa
646
continue i;
647     }
648    if (si!='e')
649     if (si!='E')
650      { // expect an extra digit
651
if ((!(java.lang.Character.isDigit(si))))
652        bad(inchars); // not a number
653
// defer the base 10 check until later to avoid extra method call
654
exotic=true; // will need conversion later
655
last=i;
656       d++; // still in mantissa
657
continue i;
658      }
659    /* Found 'e' or 'E' -- now process explicit exponent */
660    // 1998.07.11: sign no longer required
661
if ((i-offset)>(length-2))
662     bad(inchars); // no room for even one digit
663
eneg=false;
664    if ((inchars[i+1])==('-'))
665     {
666      eneg=true;
667      k=i+2;
668     }
669    else
670     if ((inchars[i+1])==('+'))
671      k=i+2;
672     else
673      k=i+1;
674    // k is offset of first expected digit
675
elen=length-((k-offset)); // possible number of digits
676
if ((elen==0)|(elen>9))
677     bad(inchars); // 0 or more than 9 digits
678
{int $2=elen;j=k;j:for(;$2>0;$2--,j++){
679     sj=inchars[j];
680     if (sj<'0')
681      bad(inchars); // always bad
682
if (sj>'9')
683      { // maybe an exotic digit
684
if ((!(java.lang.Character.isDigit(sj))))
685        bad(inchars); // not a number
686
dvalue=java.lang.Character.digit(sj,10); // check base
687
if (dvalue<0)
688        bad(inchars); // not base 10
689
}
690     else
691      dvalue=((int)(sj))-((int)('0'));
692     exp=(exp*10)+dvalue;
693     }
694    }/*j*/
695    if (eneg)
696     exp=(int)-exp; // was negative
697
hadexp=true; // remember we had one
698
break i; // we are done
699
}
700   }/*i*/
701   
702   /* Here when all inspected */
703   if (d==0)
704    bad(inchars); // no mantissa digits
705
if (dotoff>=0)
706    exp=(exp+dotoff)-d; // adjust exponent if had dot
707

708   /* strip leading zeros/dot (leave final if all 0's) */
709   {int $3=last-1;i=offset;i:for(;i<=$3;i++){
710    si=inchars[i];
711    if (si=='0')
712     {
713      offset++;
714      dotoff--;
715      d--;
716     }
717    else
718     if (si=='.')
719      {
720       offset++; // step past dot
721
dotoff--;
722      }
723     else
724      if (si<='9')
725       break i;/* non-0 */
726      else
727       {/* exotic */
728        if ((java.lang.Character.digit(si,10))!=0)
729         break i; // non-0 or bad
730
// is 0 .. strip like '0'
731
offset++;
732        dotoff--;
733        d--;
734       }
735    }
736   }/*i*/
737   
738   /* Create the mantissa array */
739   mant=new byte[d]; // we know the length
740
j=offset; // input offset
741
if (exotic)
742    {exotica:do{ // slow: check for exotica
743
{int $4=d;i=0;i:for(;$4>0;$4--,i++){
744      if (i==dotoff)
745       j++; // at dot
746
sj=inchars[j];
747      if (sj<='9')
748       mant[i]=(byte)(((int)(sj))-((int)('0')));/* easy */
749      else
750       {
751        dvalue=java.lang.Character.digit(sj,10);
752        if (dvalue<0)
753         bad(inchars); // not a number after all
754
mant[i]=(byte)dvalue;
755       }
756      j++;
757      }
758     }/*i*/
759    }while(false);}/*exotica*/
760   else
761    {simple:do{
762     {int $5=d;i=0;i:for(;$5>0;$5--,i++){
763      if (i==dotoff)
764       j++;
765      mant[i]=(byte)(((int)(inchars[j]))-((int)('0')));
766      j++;
767      }
768     }/*i*/
769    }while(false);}/*simple*/
770   
771   /* Looks good. Set the sign indicator and form, as needed. */
772   // Trailing zeros are preserved
773
// The rule here for form is:
774
// If no E-notation, then request plain notation
775
// Otherwise act as though add(0,DEFAULT) and request scientific notation
776
// [form is already PLAIN]
777
if (mant[0]==0)
778    {
779     ind=iszero; // force to show zero
780
// negative exponent is significant (e.g., -3 for 0.000) if plain
781
if (exp>0)
782      exp=0; // positive exponent can be ignored
783
if (hadexp)
784      { // zero becomes single digit from add
785
mant=ZERO.mant;
786       exp=0;
787      }
788    }
789   else
790    { // non-zero
791
// [ind was set earlier]
792
// now determine form
793
if (hadexp)
794      {
795       form=(byte)com.ibm.icu.math.MathContext.SCIENTIFIC;
796       // 1999.06.29 check for overflow
797
mag=(exp+mant.length)-1; // true exponent in scientific notation
798
if ((mag<MinExp)|(mag>MaxExp))
799        bad(inchars);
800      }
801    }
802   // say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] mant.length exp ind form
803
return;
804   }
805
806  /**
807   * Constructs a <code>BigDecimal</code> object directly from a
808   * <code>double</code>.
809   * <p>
810   * Constructs a <code>BigDecimal</code> which is the exact decimal
811   * representation of the 64-bit signed binary floating point
812   * parameter.
813   * <p>
814   * Note that this constructor it an exact conversion; it does not give
815   * the same result as converting <code>num</code> to a
816   * <code>String</code> using the <code>Double.toString()</code> method
817   * and then using the {@link #BigDecimal(java.lang.String)}
818   * constructor.
819   * To get that result, use the static {@link #valueOf(double)}
820   * method to construct a <code>BigDecimal</code> from a
821   * <code>double</code>.
822   *
823   * @param num The <code>double</code> to be converted.
824   * @throws NumberFormatException if the parameter is infinite or
825   * not a number.
826   * @stable ICU 2.0
827   */

828  
829  public BigDecimal(double num){
830   // 1999.03.06: use exactly the old algorithm
831
// 2000.01.01: note that this constructor does give an exact result,
832
// so perhaps it should not be deprecated
833
// 2000.06.18: no longer deprecated
834
//#ifndef FOUNDATION
835
//## this((new java.math.BigDecimal(num)).toString());
836
//#else
837
this(String.valueOf(num));
838 //#endif
839
return;}
840  /**
841   * Constructs a <code>BigDecimal</code> object directly from a
842   * <code>int</code>.
843   * <p>
844   * Constructs a <code>BigDecimal</code> which is the exact decimal
845   * representation of the 32-bit signed binary integer parameter.
846   * The <code>BigDecimal</code> will contain only decimal digits,
847   * prefixed with a leading minus sign (hyphen) if the parameter is
848   * negative.
849   * A leading zero will be present only if the parameter is zero.
850   *
851   * @param num The <code>int</code> to be converted.
852   * @stable ICU 2.0
853   */

854  
855  public BigDecimal(int num){super();
856   int mun;
857   int i=0;
858   // We fastpath commoners
859
if (num<=9)
860    if (num>=(-9))
861     {singledigit:do{
862      // very common single digit case
863
{/*select*/
864      if (num==0)
865       {
866        mant=ZERO.mant;
867        ind=iszero;
868       }
869      else if (num==1)
870       {
871        mant=ONE.mant;
872        ind=ispos;
873       }
874      else if (num==(-1))
875       {
876        mant=ONE.mant;
877        ind=isneg;
878       }
879      else{
880       {
881        mant=new byte[1];
882        if (num>0)
883         {
884          mant[0]=(byte)num;
885          ind=ispos;
886         }
887        else
888         { // num<-1
889
mant[0]=(byte)((int)-num);
890          ind=isneg;
891         }
892       }
893      }
894      }
895      return;
896     }while(false);}/*singledigit*/
897   
898   /* We work on negative numbers so we handle the most negative number */
899   if (num>0)
900    {
901     ind=ispos;
902     num=(int)-num;
903    }
904   else
905    ind=isneg;/* negative */ // [0 case already handled]
906
// [it is quicker, here, to pre-calculate the length with
907
// one loop, then allocate exactly the right length of byte array,
908
// then re-fill it with another loop]
909
mun=num; // working copy
910
{i=9;i:for(;;i--){
911    mun=mun/10;
912    if (mun==0)
913     break i;
914    }
915   }/*i*/
916   // i is the position of the leftmost digit placed
917
mant=new byte[10-i];
918   {i=(10-i)-1;i:for(;;i--){
919    mant[i]=(byte)-(((byte)(num%10)));
920    num=num/10;
921    if (num==0)
922     break i;
923    }
924   }/*i*/
925   return;
926   }
927
928  /**
929   * Constructs a <code>BigDecimal</code> object directly from a
930   * <code>long</code>.
931   * <p>
932   * Constructs a <code>BigDecimal</code> which is the exact decimal
933   * representation of the 64-bit signed binary integer parameter.
934   * The <code>BigDecimal</code> will contain only decimal digits,
935   * prefixed with a leading minus sign (hyphen) if the parameter is
936   * negative.
937   * A leading zero will be present only if the parameter is zero.
938   *
939   * @param num The <code>long</code> to be converted.
940   * @stable ICU 2.0
941   */

942  
943  public BigDecimal(long num){super();
944   long mun;
945   int i=0;
946   // Not really worth fastpathing commoners in this constructor [also,
947
// we use this to construct the static constants].
948
// This is much faster than: this(String.valueOf(num).toCharArray())
949
/* We work on negative num so we handle the most negative number */
950   if (num>0)
951    {
952     ind=ispos;
953     num=(long)-num;
954    }
955   else
956    if (num==0)
957     ind=iszero;
958    else
959     ind=isneg;/* negative */
960   mun=num;
961   {i=18;i:for(;;i--){
962    mun=mun/10;
963    if (mun==0)
964     break i;
965    }
966   }/*i*/
967   // i is the position of the leftmost digit placed
968
mant=new byte[19-i];
969   {i=(19-i)-1;i:for(;;i--){
970    mant[i]=(byte)-(((byte)(num%10)));
971    num=num/10;
972    if (num==0)
973     break i;
974    }
975   }/*i*/
976   return;
977   }
978
979  /**
980   * Constructs a <code>BigDecimal</code> object from a <code>String</code>.
981   * <p>
982   * Constructs a <code>BigDecimal</code> from the parameter, which must
983   * not be <code>null</code> and must represent a valid <i>number</i>,
984   * as described formally in the documentation referred to
985   * {@link BigDecimal above}.
986   * <p>
987   * In summary, numbers in <code>String</code> form must have at least
988   * one digit, may have a leading sign, may have a decimal point, and
989   * exponential notation may be used. They follow conventional syntax,
990   * and may not contain blanks.
991   * <p>
992   * Some valid strings from which a <code>BigDecimal</code> might
993   * be constructed are:
994   * <pre>
995   * "0" -- Zero
996   * "12" -- A whole number
997   * "-76" -- A signed whole number
998   * "12.70" -- Some decimal places
999   * "+0.003" -- Plus sign is allowed
1000  * "17." -- The same as 17
1001  * ".5" -- The same as 0.5
1002  * "4E+9" -- Exponential notation
1003  * "0.73e-7" -- Exponential notation
1004  * </pre>
1005  * <p>
1006  * (Exponential notation means that the number includes an optional
1007  * sign and a power of ten following an '</code>E</code>' that
1008  * indicates how the decimal point will be shifted. Thus the
1009  * <code>"4E+9"</code> above is just a short way of writing
1010  * <code>4000000000</code>, and the <code>"0.73e-7"</code> is short
1011  * for <code>0.000000073</code>.)
1012  * <p>
1013  * The <code>BigDecimal</code> constructed from the String is in a
1014  * standard form, with no blanks, as though the
1015  * {@link #add(BigDecimal)} method had been used to add zero to the
1016  * number with unlimited precision.
1017  * If the string uses exponential notation (that is, includes an
1018  * <code>e</code> or an <code>E</code>), then the
1019  * <code>BigDecimal</code> number will be expressed in scientific
1020  * notation (where the power of ten is adjusted so there is a single
1021  * non-zero digit to the left of the decimal point); in this case if
1022  * the number is zero then it will be expressed as the single digit 0,
1023  * and if non-zero it will have an exponent unless that exponent would
1024  * be 0. The exponent must fit in nine digits both before and after it
1025  * is expressed in scientific notation.
1026  * <p>
1027  * Any digits in the parameter must be decimal; that is,
1028  * <code>Character.digit(c, 10)</code> (where </code>c</code> is the
1029  * character in question) would not return -1.
1030  *
1031  * @param string The <code>String</code> to be converted.
1032  * @throws NumberFormatException if the parameter is not a valid
1033  * number.
1034  * @stable ICU 2.0
1035  */

1036 
1037 public BigDecimal(java.lang.String JavaDoc string){
1038  this(string.toCharArray(),0,string.length());
1039  return;}
1040
1041 /* <sgml> Make a default BigDecimal object for local use. </sgml> */
1042 
1043 private BigDecimal(){super();
1044  return;
1045  }
1046
1047 /* ---------------------------------------------------------------- */
1048 /* Operator methods [methods which take a context parameter] */
1049 /* ---------------------------------------------------------------- */
1050 
1051 /**
1052  * Returns a plain <code>BigDecimal</code> whose value is the absolute
1053  * value of this <code>BigDecimal</code>.
1054  * <p>
1055  * The same as {@link #abs(MathContext)}, where the context is
1056  * <code>new MathContext(0, MathContext.PLAIN)</code>.
1057  * <p>
1058  * The length of the decimal part (the scale) of the result will
1059  * be <code>this.scale()</code>
1060  *
1061  * @return A <code>BigDecimal</code> whose value is the absolute
1062  * value of this <code>BigDecimal</code>.
1063  * @stable ICU 2.0
1064  */

1065 
1066 public com.ibm.icu.math.BigDecimal abs(){
1067  return this.abs(plainMC);
1068  }
1069
1070 /**
1071  * Returns a <code>BigDecimal</code> whose value is the absolute value
1072  * of this <code>BigDecimal</code>.
1073  * <p>
1074  * If the current object is zero or positive, then the same result as
1075  * invoking the {@link #plus(MathContext)} method with the same
1076  * parameter is returned.
1077  * Otherwise, the same result as invoking the
1078  * {@link #negate(MathContext)} method with the same parameter is
1079  * returned.
1080  *
1081  * @param set The <code>MathContext</code> arithmetic settings.
1082  * @return A <code>BigDecimal</code> whose value is the absolute
1083  * value of this <code>BigDecimal</code>.
1084  * @stable ICU 2.0
1085  */

1086 
1087 public com.ibm.icu.math.BigDecimal abs(com.ibm.icu.math.MathContext set){
1088  if (this.ind==isneg)
1089   return this.negate(set);
1090  return this.plus(set);
1091  }
1092
1093 /**
1094  * Returns a plain <code>BigDecimal</code> whose value is
1095  * <code>this+rhs</code>, using fixed point arithmetic.
1096  * <p>
1097  * The same as {@link #add(BigDecimal, MathContext)},
1098  * where the <code>BigDecimal</code> is <code>rhs</code>,
1099  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1100  * <p>
1101  * The length of the decimal part (the scale) of the result will be
1102  * the maximum of the scales of the two operands.
1103  *
1104  * @param rhs The <code>BigDecimal</code> for the right hand side of
1105  * the addition.
1106  * @return A <code>BigDecimal</code> whose value is
1107  * <code>this+rhs</code>, using fixed point arithmetic.
1108  * @stable ICU 2.0
1109  */

1110 
1111 public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs){
1112  return this.add(rhs,plainMC);
1113  }
1114
1115 /**
1116  * Returns a <code>BigDecimal</code> whose value is <code>this+rhs</code>.
1117  * <p>
1118  * Implements the addition (<b><code>+</code></b>) operator
1119  * (as defined in the decimal documentation, see {@link BigDecimal
1120  * class header}),
1121  * and returns the result as a <code>BigDecimal</code> object.
1122  *
1123  * @param rhs The <code>BigDecimal</code> for the right hand side of
1124  * the addition.
1125  * @param set The <code>MathContext</code> arithmetic settings.
1126  * @return A <code>BigDecimal</code> whose value is
1127  * <code>this+rhs</code>.
1128  * @stable ICU 2.0
1129  */

1130 
1131 public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1132  com.ibm.icu.math.BigDecimal lhs;
1133  int reqdig;
1134  com.ibm.icu.math.BigDecimal res;
1135  byte usel[];
1136  int usellen;
1137  byte user[];
1138  int userlen;
1139  int newlen=0;
1140  int tlen=0;
1141  int mult=0;
1142  byte t[]=null;
1143  int ia=0;
1144  int ib=0;
1145  int ea=0;
1146  int eb=0;
1147  byte ca=0;
1148  byte cb=0;
1149  /* determine requested digits and form */
1150  if (set.lostDigits)
1151   checkdigits(rhs,set.digits);
1152  lhs=this; // name for clarity and proxy
1153

1154  /* Quick exit for add floating 0 */
1155  // plus() will optimize to return same object if possible
1156
if (lhs.ind==0)
1157   if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
1158    return rhs.plus(set);
1159  if (rhs.ind==0)
1160   if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
1161    return lhs.plus(set);
1162  
1163  /* Prepare numbers (round, unless unlimited precision) */
1164  reqdig=set.digits; // local copy (heavily used)
1165
if (reqdig>0)
1166   {
1167    if (lhs.mant.length>reqdig)
1168     lhs=clone(lhs).round(set);
1169    if (rhs.mant.length>reqdig)
1170     rhs=clone(rhs).round(set);
1171   // [we could reuse the new LHS for result in this case]
1172
}
1173  
1174  res=new com.ibm.icu.math.BigDecimal(); // build result here
1175

1176  /* Now see how much we have to pad or truncate lhs or rhs in order
1177     to align the numbers. If one number is much larger than the
1178     other, then the smaller cannot affect the answer [but we may
1179     still need to pad with up to DIGITS trailing zeros]. */

1180  // Note sign may be 0 if digits (reqdig) is 0
1181
// usel and user will be the byte arrays passed to the adder; we'll
1182
// use them on all paths except quick exits
1183
usel=lhs.mant;
1184  usellen=lhs.mant.length;
1185  user=rhs.mant;
1186  userlen=rhs.mant.length;
1187  {padder:do{/*select*/
1188  if (lhs.exp==rhs.exp)
1189   {/* no padding needed */
1190    // This is the most common, and fastest, path
1191
res.exp=lhs.exp;
1192   }
1193  else if (lhs.exp>rhs.exp)
1194   { // need to pad lhs and/or truncate rhs
1195
newlen=(usellen+lhs.exp)-rhs.exp;
1196    /* If, after pad, lhs would be longer than rhs by digits+1 or
1197       more (and digits>0) then rhs cannot affect answer, so we only
1198       need to pad up to a length of DIGITS+1. */

1199    if (newlen>=((userlen+reqdig)+1))
1200     if (reqdig>0)
1201      {
1202       // LHS is sufficient
1203
res.mant=usel;
1204       res.exp=lhs.exp;
1205       res.ind=lhs.ind;
1206       if (usellen<reqdig)
1207        { // need 0 padding
1208
res.mant=extend(lhs.mant,reqdig);
1209         res.exp=res.exp-((reqdig-usellen));
1210        }
1211       return res.finish(set,false);
1212      }
1213    // RHS may affect result
1214
res.exp=rhs.exp; // expected final exponent
1215
if (newlen>(reqdig+1))
1216     if (reqdig>0)
1217      {
1218       // LHS will be max; RHS truncated
1219
tlen=(newlen-reqdig)-1; // truncation length
1220
userlen=userlen-tlen;
1221       res.exp=res.exp+tlen;
1222       newlen=reqdig+1;
1223      }
1224    if (newlen>usellen)
1225     usellen=newlen; // need to pad LHS
1226
}
1227  else{ // need to pad rhs and/or truncate lhs
1228
newlen=(userlen+rhs.exp)-lhs.exp;
1229   if (newlen>=((usellen+reqdig)+1))
1230    if (reqdig>0)
1231     {
1232      // RHS is sufficient
1233
res.mant=user;
1234      res.exp=rhs.exp;
1235      res.ind=rhs.ind;
1236      if (userlen<reqdig)
1237       { // need 0 padding
1238
res.mant=extend(rhs.mant,reqdig);
1239        res.exp=res.exp-((reqdig-userlen));
1240       }
1241      return res.finish(set,false);
1242     }
1243   // LHS may affect result
1244
res.exp=lhs.exp; // expected final exponent
1245
if (newlen>(reqdig+1))
1246    if (reqdig>0)
1247     {
1248      // RHS will be max; LHS truncated
1249
tlen=(newlen-reqdig)-1; // truncation length
1250
usellen=usellen-tlen;
1251      res.exp=res.exp+tlen;
1252      newlen=reqdig+1;
1253     }
1254   if (newlen>userlen)
1255    userlen=newlen; // need to pad RHS
1256
}
1257  }while(false);}/*padder*/
1258  
1259  /* OK, we have aligned mantissas. Now add or subtract. */
1260  // 1998.06.27 Sign may now be 0 [e.g., 0.000] .. treat as positive
1261
// 1999.05.27 Allow for 00 on lhs [is not larger than 2 on rhs]
1262
// 1999.07.10 Allow for 00 on rhs [is not larger than 2 on rhs]
1263
if (lhs.ind==iszero)
1264   res.ind=ispos;
1265  else
1266   res.ind=lhs.ind; // likely sign, all paths
1267
if (((lhs.ind==isneg)?1:0)==((rhs.ind==isneg)?1:0)) // same sign, 0 non-negative
1268
mult=1;
1269  else
1270   {signdiff:do{ // different signs, so subtraction is needed
1271
mult=-1; // will cause subtract
1272
/* Before we can subtract we must determine which is the larger,
1273       as our add/subtract routine only handles non-negative results
1274       so we may need to swap the operands. */

1275    {swaptest:do{/*select*/
1276    if (rhs.ind==iszero){
1277     // original A bigger
1278
}else if ((usellen<userlen)|(lhs.ind==iszero))
1279     { // original B bigger
1280
t=usel;
1281      usel=user;
1282      user=t; // swap
1283
tlen=usellen;
1284      usellen=userlen;
1285      userlen=tlen; // ..
1286
res.ind=(byte)-res.ind; // and set sign
1287
}
1288    else if (usellen>userlen){
1289     // original A bigger
1290
}else{
1291     {/* logical lengths the same */ // need compare
1292
/* may still need to swap: compare the strings */
1293      ia=0;
1294      ib=0;
1295      ea=usel.length-1;
1296      eb=user.length-1;
1297      {compare:for(;;){
1298       if (ia<=ea)
1299        ca=usel[ia];
1300       else
1301        {
1302         if (ib>eb)
1303          {/* identical */
1304           if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
1305            return ZERO;
1306           // [if PLAIN we must do the subtract, in case of 0.000 results]
1307
break compare;
1308          }
1309         ca=(byte)0;
1310        }
1311       if (ib<=eb)
1312        cb=user[ib];
1313       else
1314        cb=(byte)0;
1315       if (ca!=cb)
1316        {
1317         if (ca<cb)
1318          {/* swap needed */
1319           t=usel;
1320           usel=user;
1321           user=t; // swap
1322
tlen=usellen;
1323           usellen=userlen;
1324           userlen=tlen; // ..
1325
res.ind=(byte)-res.ind;
1326          }
1327         break compare;
1328        }
1329       /* mantissas the same, so far */
1330       ia++;
1331       ib++;
1332       }
1333      }/*compare*/
1334     } // lengths the same
1335
}
1336    }while(false);}/*swaptest*/
1337   }while(false);}/*signdiff*/
1338  
1339  /* here, A is > B if subtracting */
1340  // add [A+B*1] or subtract [A+(B*-1)]
1341
res.mant=byteaddsub(usel,usellen,user,userlen,mult,false);
1342  // [reuse possible only after chop; accounting makes not worthwhile]
1343

1344  // Finish() rounds before stripping leading 0's, then sets form, etc.
1345
return res.finish(set,false);
1346  }
1347
1348 /**
1349  * Compares this <code>BigDecimal</code> to another, using unlimited
1350  * precision.
1351  * <p>
1352  * The same as {@link #compareTo(BigDecimal, MathContext)},
1353  * where the <code>BigDecimal</code> is <code>rhs</code>,
1354  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1355  *
1356  * @param rhs The <code>BigDecimal</code> for the right hand side of
1357  * the comparison.
1358  * @return An <code>int</code> whose value is -1, 0, or 1 as
1359  * <code>this</code> is numerically less than, equal to,
1360  * or greater than <code>rhs</code>.
1361  * @see #compareTo(Object)
1362  * @stable ICU 2.0
1363  */

1364 
1365 public int compareTo(com.ibm.icu.math.BigDecimal rhs){
1366  return this.compareTo(rhs,plainMC);
1367  }
1368
1369 /**
1370  * Compares this <code>BigDecimal</code> to another.
1371  * <p>
1372  * Implements numeric comparison,
1373  * (as defined in the decimal documentation, see {@link BigDecimal
1374  * class header}),
1375  * and returns a result of type <code>int</code>.
1376  * <p>
1377  * The result will be:
1378  * <table cellpadding=2><tr>
1379  * <td align=right><b>-1</b></td>
1380  * <td>if the current object is less than the first parameter</td>
1381  * </tr><tr>
1382  * <td align=right><b>0</b></td>
1383  * <td>if the current object is equal to the first parameter</td>
1384  * </tr><tr>
1385  * <td align=right><b>1</b></td>
1386  * <td>if the current object is greater than the first parameter.</td>
1387  * </tr></table>
1388  * <p>
1389  * A {@link #compareTo(Object)} method is also provided.
1390  *
1391  * @param rhs The <code>BigDecimal</code> for the right hand side of
1392  * the comparison.
1393  * @param set The <code>MathContext</code> arithmetic settings.
1394  * @return An <code>int</code> whose value is -1, 0, or 1 as
1395  * <code>this</code> is numerically less than, equal to,
1396  * or greater than <code>rhs</code>.
1397  * @see #compareTo(Object)
1398  * @stable ICU 2.0
1399  */

1400 
1401 public int compareTo(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1402  int thislength=0;
1403  int i=0;
1404  com.ibm.icu.math.BigDecimal newrhs;
1405  // rhs=null will raise NullPointerException, as per Comparable interface
1406
if (set.lostDigits)
1407   checkdigits(rhs,set.digits);
1408  // [add will recheck in slowpath cases .. but would report -rhs]
1409
if ((this.ind==rhs.ind)&(this.exp==rhs.exp))
1410   {
1411    /* sign & exponent the same [very common] */
1412    thislength=this.mant.length;
1413    if (thislength<rhs.mant.length)
1414     return (byte)-this.ind;
1415    if (thislength>rhs.mant.length)
1416     return this.ind;
1417    /* lengths are the same; we can do a straight mantissa compare
1418       unless maybe rounding [rounding is very unusual] */

1419    if ((thislength<=set.digits)|(set.digits==0))
1420     {
1421      {int $6=thislength;i=0;i:for(;$6>0;$6--,i++){
1422       if (this.mant[i]<rhs.mant[i])
1423        return (byte)-this.ind;
1424       if (this.mant[i]>rhs.mant[i])
1425        return this.ind;
1426       }
1427      }/*i*/
1428      return 0; // identical
1429
}
1430   /* drop through for full comparison */
1431   }
1432  else
1433   {
1434    /* More fastpaths possible */
1435    if (this.ind<rhs.ind)
1436     return -1;
1437    if (this.ind>rhs.ind)
1438     return 1;
1439   }
1440  /* carry out a subtract to make the comparison */
1441  newrhs=clone(rhs); // safe copy
1442
newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
1443
return this.add(newrhs,set).ind; // add, and return sign of result
1444
}
1445
1446 /**
1447  * Returns a plain <code>BigDecimal</code> whose value is
1448  * <code>this/rhs</code>, using fixed point arithmetic.
1449  * <p>
1450  * The same as {@link #divide(BigDecimal, int)},
1451  * where the <code>BigDecimal</code> is <code>rhs</code>,
1452  * and the rounding mode is {@link MathContext#ROUND_HALF_UP}.
1453  *
1454  * The length of the decimal part (the scale) of the result will be
1455  * the same as the scale of the current object, if the latter were
1456  * formatted without exponential notation.
1457  *
1458  * @param rhs The <code>BigDecimal</code> for the right hand side of
1459  * the division.
1460  * @return A plain <code>BigDecimal</code> whose value is
1461  * <code>this/rhs</code>, using fixed point arithmetic.
1462  * @throws ArithmeticException if <code>rhs</code> is zero.
1463  * @stable ICU 2.0
1464  */

1465 
1466 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs){
1467  return this.dodivide('D',rhs,plainMC,-1);
1468  }
1469
1470 /**
1471  * Returns a plain <code>BigDecimal</code> whose value is
1472  * <code>this/rhs</code>, using fixed point arithmetic and a
1473  * rounding mode.
1474  * <p>
1475  * The same as {@link #divide(BigDecimal, int, int)},
1476  * where the <code>BigDecimal</code> is <code>rhs</code>,
1477  * and the second parameter is <code>this.scale()</code>, and
1478  * the third is <code>round</code>.
1479  * <p>
1480  * The length of the decimal part (the scale) of the result will
1481  * therefore be the same as the scale of the current object, if the
1482  * latter were formatted without exponential notation.
1483  * <p>
1484  * @param rhs The <code>BigDecimal</code> for the right hand side of
1485  * the division.
1486  * @param round The <code>int</code> rounding mode to be used for
1487  * the division (see the {@link MathContext} class).
1488  * @return A plain <code>BigDecimal</code> whose value is
1489  * <code>this/rhs</code>, using fixed point arithmetic
1490  * and the specified rounding mode.
1491  * @throws IllegalArgumentException if <code>round</code> is not a
1492  * valid rounding mode.
1493  * @throws ArithmeticException if <code>rhs</code> is zero.
1494  * @throws ArithmeticException if <code>round</code> is {@link
1495  * MathContext#ROUND_UNNECESSARY} and
1496  * <code>this.scale()</code> is insufficient to
1497  * represent the result exactly.
1498  * @stable ICU 2.0
1499  */

1500 
1501 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int round){
1502  com.ibm.icu.math.MathContext set;
1503  set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round, too]
1504
return this.dodivide('D',rhs,set,-1); // take scale from LHS
1505
}
1506
1507 /**
1508  * Returns a plain <code>BigDecimal</code> whose value is
1509  * <code>this/rhs</code>, using fixed point arithmetic and a
1510  * given scale and rounding mode.
1511  * <p>
1512  * The same as {@link #divide(BigDecimal, MathContext)},
1513  * where the <code>BigDecimal</code> is <code>rhs</code>,
1514  * <code>new MathContext(0, MathContext.PLAIN, false, round)</code>,
1515  * except that the length of the decimal part (the scale) to be used
1516  * for the result is explicit rather than being taken from
1517  * <code>this</code>.
1518  * <p>
1519  * The length of the decimal part (the scale) of the result will be
1520  * the same as the scale of the current object, if the latter were
1521  * formatted without exponential notation.
1522  * <p>
1523  * @param rhs The <code>BigDecimal</code> for the right hand side of
1524  * the division.
1525  * @param scale The <code>int</code> scale to be used for the result.
1526  * @param round The <code>int</code> rounding mode to be used for
1527  * the division (see the {@link MathContext} class).
1528  * @return A plain <code>BigDecimal</code> whose value is
1529  * <code>this/rhs</code>, using fixed point arithmetic
1530  * and the specified rounding mode.
1531  * @throws IllegalArgumentException if <code>round</code> is not a
1532  * valid rounding mode.
1533  * @throws ArithmeticException if <code>rhs</code> is zero.
1534  * @throws ArithmeticException if <code>scale</code> is negative.
1535  * @throws ArithmeticException if <code>round</code> is {@link
1536  * MathContext#ROUND_UNNECESSARY} and <code>scale</code>
1537  * is insufficient to represent the result exactly.
1538  * @stable ICU 2.0
1539  */

1540 
1541 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int scale,int round){
1542  com.ibm.icu.math.MathContext set;
1543  if (scale<0)
1544   throw new java.lang.ArithmeticException JavaDoc("Negative scale:"+" "+scale);
1545  set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round]
1546
return this.dodivide('D',rhs,set,scale);
1547  }
1548
1549 /**
1550  * Returns a <code>BigDecimal</code> whose value is <code>this/rhs</code>.
1551  * <p>
1552  * Implements the division (<b><code>/</code></b>) operator
1553  * (as defined in the decimal documentation, see {@link BigDecimal
1554  * class header}),
1555  * and returns the result as a <code>BigDecimal</code> object.
1556  *
1557  * @param rhs The <code>BigDecimal</code> for the right hand side of
1558  * the division.
1559  * @param set The <code>MathContext</code> arithmetic settings.
1560  * @return A <code>BigDecimal</code> whose value is
1561  * <code>this/rhs</code>.
1562  * @throws ArithmeticException if <code>rhs</code> is zero.
1563  * @stable ICU 2.0
1564  */

1565 
1566 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1567  return this.dodivide('D',rhs,set,-1);
1568  }
1569
1570 /**
1571  * Returns a plain <code>BigDecimal</code> whose value is the integer
1572  * part of <code>this/rhs</code>.
1573  * <p>
1574  * The same as {@link #divideInteger(BigDecimal, MathContext)},
1575  * where the <code>BigDecimal</code> is <code>rhs</code>,
1576  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1577  *
1578  * @param rhs The <code>BigDecimal</code> for the right hand side of
1579  * the integer division.
1580  * @return A <code>BigDecimal</code> whose value is the integer
1581  * part of <code>this/rhs</code>.
1582  * @throws ArithmeticException if <code>rhs</code> is zero.
1583  * @stable ICU 2.0
1584  */

1585 
1586 public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs){
1587  // scale 0 to drop .000 when plain
1588
return this.dodivide('I',rhs,plainMC,0);
1589  }
1590
1591 /**
1592  * Returns a <code>BigDecimal</code> whose value is the integer
1593  * part of <code>this/rhs</code>.
1594  * <p>
1595  * Implements the integer division operator
1596  * (as defined in the decimal documentation, see {@link BigDecimal
1597  * class header}),
1598  * and returns the result as a <code>BigDecimal</code> object.
1599  *
1600  * @param rhs The <code>BigDecimal</code> for the right hand side of
1601  * the integer division.
1602  * @param set The <code>MathContext</code> arithmetic settings.
1603  * @return A <code>BigDecimal</code> whose value is the integer
1604  * part of <code>this/rhs</code>.
1605  * @throws ArithmeticException if <code>rhs</code> is zero.
1606  * @throws ArithmeticException if the result will not fit in the
1607  * number of digits specified for the context.
1608  * @stable ICU 2.0
1609  */

1610 
1611 public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1612  // scale 0 to drop .000 when plain
1613
return this.dodivide('I',rhs,set,0);
1614  }
1615
1616 /**
1617  * Returns a plain <code>BigDecimal</code> whose value is
1618  * the maximum of <code>this</code> and <code>rhs</code>.
1619  * <p>
1620  * The same as {@link #max(BigDecimal, MathContext)},
1621  * where the <code>BigDecimal</code> is <code>rhs</code>,
1622  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1623  *
1624  * @param rhs The <code>BigDecimal</code> for the right hand side of
1625  * the comparison.
1626  * @return A <code>BigDecimal</code> whose value is
1627  * the maximum of <code>this</code> and <code>rhs</code>.
1628  * @stable ICU 2.0
1629  */

1630 
1631 public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs){
1632  return this.max(rhs,plainMC);
1633  }
1634
1635 /**
1636  * Returns a <code>BigDecimal</code> whose value is
1637  * the maximum of <code>this</code> and <code>rhs</code>.
1638  * <p>
1639  * Returns the larger of the current object and the first parameter.
1640  * <p>
1641  * If calling the {@link #compareTo(BigDecimal, MathContext)} method
1642  * with the same parameters would return <code>1</code> or
1643  * <code>0</code>, then the result of calling the
1644  * {@link #plus(MathContext)} method on the current object (using the
1645  * same <code>MathContext</code> parameter) is returned.
1646  * Otherwise, the result of calling the {@link #plus(MathContext)}
1647  * method on the first parameter object (using the same
1648  * <code>MathContext</code> parameter) is returned.
1649  *
1650  * @param rhs The <code>BigDecimal</code> for the right hand side of
1651  * the comparison.
1652  * @param set The <code>MathContext</code> arithmetic settings.
1653  * @return A <code>BigDecimal</code> whose value is
1654  * the maximum of <code>this</code> and <code>rhs</code>.
1655  * @stable ICU 2.0
1656  */

1657 
1658 public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1659  if ((this.compareTo(rhs,set))>=0)
1660   return this.plus(set);
1661  else
1662   return rhs.plus(set);
1663  }
1664
1665 /**
1666  * Returns a plain <code>BigDecimal</code> whose value is
1667  * the minimum of <code>this</code> and <code>rhs</code>.
1668  * <p>
1669  * The same as {@link #min(BigDecimal, MathContext)},
1670  * where the <code>BigDecimal</code> is <code>rhs</code>,
1671  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1672  *
1673  * @param rhs The <code>BigDecimal</code> for the right hand side of
1674  * the comparison.
1675  * @return A <code>BigDecimal</code> whose value is
1676  * the minimum of <code>this</code> and <code>rhs</code>.
1677  * @stable ICU 2.0
1678  */

1679 
1680 public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs){
1681  return this.min(rhs,plainMC);
1682  }
1683
1684 /**
1685  * Returns a <code>BigDecimal</code> whose value is
1686  * the minimum of <code>this</code> and <code>rhs</code>.
1687  * <p>
1688  * Returns the smaller of the current object and the first parameter.
1689  * <p>
1690  * If calling the {@link #compareTo(BigDecimal, MathContext)} method
1691  * with the same parameters would return <code>-1</code> or
1692  * <code>0</code>, then the result of calling the
1693  * {@link #plus(MathContext)} method on the current object (using the
1694  * same <code>MathContext</code> parameter) is returned.
1695  * Otherwise, the result of calling the {@link #plus(MathContext)}
1696  * method on the first parameter object (using the same
1697  * <code>MathContext</code> parameter) is returned.
1698  *
1699  * @param rhs The <code>BigDecimal</code> for the right hand side of
1700  * the comparison.
1701  * @param set The <code>MathContext</code> arithmetic settings.
1702  * @return A <code>BigDecimal</code> whose value is
1703  * the minimum of <code>this</code> and <code>rhs</code>.
1704  * @stable ICU 2.0
1705  */

1706 
1707 public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1708  if ((this.compareTo(rhs,set))<=0)
1709   return this.plus(set);
1710  else
1711   return rhs.plus(set);
1712  }
1713
1714 /**
1715  * Returns a plain <code>BigDecimal</code> whose value is
1716  * <code>this*rhs</code>, using fixed point arithmetic.
1717  * <p>
1718  * The same as {@link #add(BigDecimal, MathContext)},
1719  * where the <code>BigDecimal</code> is <code>rhs</code>,
1720  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1721  * <p>
1722  * The length of the decimal part (the scale) of the result will be
1723  * the sum of the scales of the operands, if they were formatted
1724  * without exponential notation.
1725  *
1726  * @param rhs The <code>BigDecimal</code> for the right hand side of
1727  * the multiplication.
1728  * @return A <code>BigDecimal</code> whose value is
1729  * <code>this*rhs</code>, using fixed point arithmetic.
1730  * @stable ICU 2.0
1731  */

1732 
1733 public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs){
1734  return this.multiply(rhs,plainMC);
1735  }
1736
1737 /**
1738  * Returns a <code>BigDecimal</code> whose value is <code>this*rhs</code>.
1739  * <p>
1740  * Implements the multiplication (<b><code>*</code></b>) operator
1741  * (as defined in the decimal documentation, see {@link BigDecimal
1742  * class header}),
1743  * and returns the result as a <code>BigDecimal</code> object.
1744  *
1745  * @param rhs The <code>BigDecimal</code> for the right hand side of
1746  * the multiplication.
1747  * @param set The <code>MathContext</code> arithmetic settings.
1748  * @return A <code>BigDecimal</code> whose value is
1749  * <code>this*rhs</code>.
1750  * @stable ICU 2.0
1751  */

1752 
1753 public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1754  com.ibm.icu.math.BigDecimal lhs;
1755  int padding;
1756  int reqdig;
1757  byte multer[]=null;
1758  byte multand[]=null;
1759  int multandlen;
1760  int acclen=0;
1761  com.ibm.icu.math.BigDecimal res;
1762  byte acc[];
1763  int n=0;
1764  byte mult=0;
1765  if (set.lostDigits)
1766   checkdigits(rhs,set.digits);
1767  lhs=this; // name for clarity and proxy
1768

1769  /* Prepare numbers (truncate, unless unlimited precision) */
1770  padding=0; // trailing 0's to add
1771
reqdig=set.digits; // local copy
1772
if (reqdig>0)
1773   {
1774    if (lhs.mant.length>reqdig)
1775     lhs=clone(lhs).round(set);
1776    if (rhs.mant.length>reqdig)
1777     rhs=clone(rhs).round(set);
1778   // [we could reuse the new LHS for result in this case]
1779
}
1780  else
1781   {/* unlimited */
1782    // fixed point arithmetic will want every trailing 0; we add these
1783
// after the calculation rather than before, for speed.
1784
if (lhs.exp>0)
1785     padding=padding+lhs.exp;
1786    if (rhs.exp>0)
1787     padding=padding+rhs.exp;
1788   }
1789  
1790  // For best speed, as in DMSRCN, we use the shorter number as the
1791
// multiplier and the longer as the multiplicand.
1792
// 1999.12.22: We used to special case when the result would fit in
1793
// a long, but with Java 1.3 this gave no advantage.
1794
if (lhs.mant.length<rhs.mant.length)
1795   {
1796    multer=lhs.mant;
1797    multand=rhs.mant;
1798   }
1799  else
1800   {
1801    multer=rhs.mant;
1802    multand=lhs.mant;
1803   }
1804  
1805  /* Calculate how long result byte array will be */
1806  multandlen=(multer.length+multand.length)-1; // effective length
1807
// optimize for 75% of the cases where a carry is expected...
1808
if ((multer[0]*multand[0])>9)
1809   acclen=multandlen+1;
1810  else
1811   acclen=multandlen;
1812  
1813  /* Now the main long multiplication loop */
1814  res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
1815
acc=new byte[acclen]; // accumulator, all zeros
1816
// 1998.07.01: calculate from left to right so that accumulator goes
1817
// to likely final length on first addition; this avoids a one-digit
1818
// extension (and object allocation) each time around the loop.
1819
// Initial number therefore has virtual zeros added to right.
1820
{int $7=multer.length;n=0;n:for(;$7>0;$7--,n++){
1821   mult=multer[n];
1822   if (mult!=0)
1823    { // [optimization]
1824
// accumulate [accumulator is reusable array]
1825
acc=byteaddsub(acc,acc.length,multand,multandlen,mult,true);
1826    }
1827   // divide multiplicand by 10 for next digit to right
1828
multandlen--; // 'virtual length'
1829
}
1830  }/*n*/
1831  
1832  res.ind=(byte)(lhs.ind*rhs.ind); // final sign
1833
res.exp=(lhs.exp+rhs.exp)-padding; // final exponent
1834
// [overflow is checked by finish]
1835

1836  /* add trailing zeros to the result, if necessary */
1837  if (padding==0)
1838   res.mant=acc;
1839  else
1840   res.mant=extend(acc,acc.length+padding); // add trailing 0s
1841
return res.finish(set,false);
1842  }
1843
1844 /**
1845  * Returns a plain <code>BigDecimal</code> whose value is
1846  * <code>-this</code>.
1847  * <p>
1848  * The same as {@link #negate(MathContext)}, where the context is
1849  * <code>new MathContext(0, MathContext.PLAIN)</code>.
1850  * <p>
1851  * The length of the decimal part (the scale) of the result will be
1852  * be <code>this.scale()</code>
1853  *
1854  *
1855  * @return A <code>BigDecimal</code> whose value is
1856  * <code>-this</code>.
1857  * @stable ICU 2.0
1858  */

1859 
1860 public com.ibm.icu.math.BigDecimal negate(){
1861  return this.negate(plainMC);
1862  }
1863
1864 /**
1865  * Returns a <code>BigDecimal</code> whose value is <code>-this</code>.
1866  * <p>
1867  * Implements the negation (Prefix <b><code>-</code></b>) operator
1868  * (as defined in the decimal documentation, see {@link BigDecimal
1869  * class header}),
1870  * and returns the result as a <code>BigDecimal</code> object.
1871  *
1872  * @param set The <code>MathContext</code> arithmetic settings.
1873  * @return A <code>BigDecimal</code> whose value is
1874  * <code>-this</code>.
1875  * @stable ICU 2.0
1876  */

1877 
1878 public com.ibm.icu.math.BigDecimal negate(com.ibm.icu.math.MathContext set){
1879  com.ibm.icu.math.BigDecimal res;
1880  // Originally called minus(), changed to matched Java precedents
1881
// This simply clones, flips the sign, and possibly rounds
1882
if (set.lostDigits)
1883   checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
1884  res=clone(this); // safe copy
1885
res.ind=(byte)-res.ind;
1886  return res.finish(set,false);
1887  }
1888
1889 /**
1890  * Returns a plain <code>BigDecimal</code> whose value is
1891  * <code>+this</code>.
1892  * Note that <code>this</code> is not necessarily a
1893  * plain <code>BigDecimal</code>, but the result will always be.
1894  * <p>
1895  * The same as {@link #plus(MathContext)}, where the context is
1896  * <code>new MathContext(0, MathContext.PLAIN)</code>.
1897  * <p>
1898  * The length of the decimal part (the scale) of the result will be
1899  * be <code>this.scale()</code>
1900  *
1901  * @return A <code>BigDecimal</code> whose value is
1902  * <code>+this</code>.
1903  * @stable ICU 2.0
1904  */

1905 
1906 public com.ibm.icu.math.BigDecimal plus(){
1907  return this.plus(plainMC);
1908  }
1909
1910 /**
1911  * Returns a <code>BigDecimal</code> whose value is
1912  * <code>+this</code>.
1913  * <p>
1914  * Implements the plus (Prefix <b><code>+</code></b>) operator
1915  * (as defined in the decimal documentation, see {@link BigDecimal
1916  * class header}),
1917  * and returns the result as a <code>BigDecimal</code> object.
1918  * <p>
1919  * This method is useful for rounding or otherwise applying a context
1920  * to a decimal value.
1921  *
1922  * @param set The <code>MathContext</code> arithmetic settings.
1923  * @return A <code>BigDecimal</code> whose value is
1924  * <code>+this</code>.
1925  * @stable ICU 2.0
1926  */

1927 
1928 public com.ibm.icu.math.BigDecimal plus(com.ibm.icu.math.MathContext set){
1929  // This clones and forces the result to the new settings
1930
// May return same object
1931
if (set.lostDigits)
1932   checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
1933  // Optimization: returns same object for some common cases
1934
if (set.form==com.ibm.icu.math.MathContext.PLAIN)
1935   if (this.form==com.ibm.icu.math.MathContext.PLAIN)
1936    {
1937     if (this.mant.length<=set.digits)
1938      return this;
1939     if (set.digits==0)
1940      return this;
1941    }
1942  return clone(this).finish(set,false);
1943  }
1944
1945 /**
1946  * Returns a plain <code>BigDecimal</code> whose value is
1947  * <code>this**rhs</code>, using fixed point arithmetic.
1948  * <p>
1949  * The same as {@link #pow(BigDecimal, MathContext)},
1950  * where the <code>BigDecimal</code> is <code>rhs</code>,
1951  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1952  * <p>
1953  * The parameter is the power to which the <code>this</code> will be
1954  * raised; it must be in the range 0 through 999999999, and must
1955  * have a decimal part of zero. Note that these restrictions may be
1956  * removed in the future, so they should not be used as a test for a
1957  * whole number.
1958  * <p>
1959  * In addition, the power must not be negative, as no
1960  * <code>MathContext</code> is used and so the result would then
1961  * always be 0.
1962  *
1963  * @param rhs The <code>BigDecimal</code> for the right hand side of
1964  * the operation (the power).
1965  * @return A <code>BigDecimal</code> whose value is
1966  * <code>this**rhs</code>, using fixed point arithmetic.
1967  * @throws ArithmeticException if <code>rhs</code> is out of range or
1968  * is not a whole number.
1969  * @stable ICU 2.0
1970  */

1971 
1972 public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs){
1973  return this.pow(rhs,plainMC);
1974  }
1975 // The name for this method is inherited from the precedent set by the
1976
// BigInteger and Math classes.
1977

1978 /**
1979  * Returns a <code>BigDecimal</code> whose value is <code>this**rhs</code>.
1980  * <p>
1981  * Implements the power (<b><code>**</code></b>) operator
1982  * (as defined in the decimal documentation, see {@link BigDecimal
1983  * class header}),
1984  * and returns the result as a <code>BigDecimal</code> object.
1985  * <p>
1986  * The first parameter is the power to which the <code>this</code>
1987  * will be raised; it must be in the range -999999999 through
1988  * 999999999, and must have a decimal part of zero. Note that these
1989  * restrictions may be removed in the future, so they should not be
1990  * used as a test for a whole number.
1991  * <p>
1992  * If the <code>digits</code> setting of the <code>MathContext</code>
1993  * parameter is 0, the power must be zero or positive.
1994  *
1995  * @param rhs The <code>BigDecimal</code> for the right hand side of
1996  * the operation (the power).
1997  * @param set The <code>MathContext</code> arithmetic settings.
1998  * @return A <code>BigDecimal</code> whose value is
1999  * <code>this**rhs</code>.
2000  * @throws ArithmeticException if <code>rhs</code> is out of range or
2001  * is not a whole number.
2002  * @stable ICU 2.0
2003  */

2004 
2005 public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2006  int n;
2007  com.ibm.icu.math.BigDecimal lhs;
2008  int reqdig;
2009  int workdigits=0;
2010  int L=0;
2011  com.ibm.icu.math.MathContext workset;
2012  com.ibm.icu.math.BigDecimal res;
2013  boolean seenbit;
2014  int i=0;
2015  if (set.lostDigits)
2016   checkdigits(rhs,set.digits);
2017  n=rhs.intcheck(MinArg,MaxArg); // check RHS by the rules
2018
lhs=this; // clarified name
2019

2020  reqdig=set.digits; // local copy (heavily used)
2021
if (reqdig==0)
2022   {
2023    if (rhs.ind==isneg)
2024     throw new java.lang.ArithmeticException JavaDoc("Negative power:"+" "+rhs.toString());
2025    workdigits=0;
2026   }
2027  else
2028   {/* non-0 digits */
2029    if ((rhs.mant.length+rhs.exp)>reqdig)
2030     throw new java.lang.ArithmeticException JavaDoc("Too many digits:"+" "+rhs.toString());
2031    
2032    /* Round the lhs to DIGITS if need be */
2033    if (lhs.mant.length>reqdig)
2034     lhs=clone(lhs).round(set);
2035    
2036    /* L for precision calculation [see ANSI X3.274-1996] */
2037    L=rhs.mant.length+rhs.exp; // length without decimal zeros/exp
2038
workdigits=(reqdig+L)+1; // calculate the working DIGITS
2039
}
2040  
2041  /* Create a copy of set for working settings */
2042  // Note: no need to check for lostDigits again.
2043
// 1999.07.17 Note: this construction must follow RHS check
2044
workset=new com.ibm.icu.math.MathContext(workdigits,set.form,false,set.roundingMode);
2045  
2046  res=ONE; // accumulator
2047
if (n==0)
2048   return res; // x**0 == 1
2049
if (n<0)
2050   n=(int)-n; // [rhs.ind records the sign]
2051
seenbit=false; // set once we've seen a 1-bit
2052
{i=1;i:for(;;i++){ // for each bit [top bit ignored]
2053
n=n+n; // shift left 1 bit
2054
if (n<0)
2055    { // top bit is set
2056
seenbit=true; // OK, we're off
2057
res=res.multiply(lhs,workset); // acc=acc*x
2058
}
2059   if (i==31)
2060    break i; // that was the last bit
2061
if ((!seenbit))
2062    continue i; // we don't have to square 1
2063
res=res.multiply(res,workset); // acc=acc*acc [square]
2064
}
2065  }/*i*/ // 32 bits
2066
if (rhs.ind<0) // was a **-n [hence digits>0]
2067
res=ONE.divide(res,workset); // .. so acc=1/acc
2068
return res.finish(set,true); // round and strip [original digits]
2069
}
2070
2071 /**
2072  * Returns a plain <code>BigDecimal</code> whose value is
2073  * the remainder of <code>this/rhs</code>, using fixed point arithmetic.
2074  * <p>
2075  * The same as {@link #remainder(BigDecimal, MathContext)},
2076  * where the <code>BigDecimal</code> is <code>rhs</code>,
2077  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
2078  * <p>
2079  * This is not the modulo operator -- the result may be negative.
2080  *
2081  * @param rhs The <code>BigDecimal</code> for the right hand side of
2082  * the remainder operation.
2083  * @return A <code>BigDecimal</code> whose value is the remainder
2084  * of <code>this/rhs</code>, using fixed point arithmetic.
2085  * @throws ArithmeticException if <code>rhs</code> is zero.
2086  * @stable ICU 2.0
2087  */

2088 
2089 public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs){
2090  return this.dodivide('R',rhs,plainMC,-1);
2091  }
2092
2093 /**
2094  * Returns a <code>BigDecimal</code> whose value is the remainder of
2095  * <code>this/rhs</code>.
2096  * <p>
2097  * Implements the remainder operator
2098  * (as defined in the decimal documentation, see {@link BigDecimal
2099  * class header}),
2100  * and returns the result as a <code>BigDecimal</code> object.
2101  * <p>
2102  * This is not the modulo operator -- the result may be negative.
2103  *
2104  * @param rhs The <code>BigDecimal</code> for the right hand side of
2105  * the remainder operation.
2106  * @param set The <code>MathContext</code> arithmetic settings.
2107  * @return A <code>BigDecimal</code> whose value is the remainder
2108  * of <code>this+rhs</code>.
2109  * @throws ArithmeticException if <code>rhs</code> is zero.
2110  * @throws ArithmeticException if the integer part of the result will
2111  * not fit in the number of digits specified for the
2112  * context.
2113  * @stable ICU 2.0
2114  */

2115 
2116 public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2117  return this.dodivide('R',rhs,set,-1);
2118  }
2119
2120 /**
2121  * Returns a plain <code>BigDecimal</code> whose value is
2122  * <code>this-rhs</code>, using fixed point arithmetic.
2123  * <p>
2124  * The same as {@link #subtract(BigDecimal, MathContext)},
2125  * where the <code>BigDecimal</code> is <code>rhs</code>,
2126  * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
2127  * <p>
2128  * The length of the decimal part (the scale) of the result will be
2129  * the maximum of the scales of the two operands.
2130  *
2131  * @param rhs The <code>BigDecimal</code> for the right hand side of
2132  * the subtraction.
2133  * @return A <code>BigDecimal</code> whose value is
2134  * <code>this-rhs</code>, using fixed point arithmetic.
2135  * @stable ICU 2.0
2136  */

2137 
2138 public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs){
2139  return this.subtract(rhs,plainMC);
2140  }
2141
2142 /**
2143  * Returns a <code>BigDecimal</code> whose value is <code>this-rhs</code>.
2144  * <p>
2145  * Implements the subtraction (<b><code>-</code></b>) operator
2146  * (as defined in the decimal documentation, see {@link BigDecimal
2147  * class header}),
2148  * and returns the result as a <code>BigDecimal</code> object.
2149  *
2150  * @param rhs The <code>BigDecimal</code> for the right hand side of
2151  * the subtraction.
2152  * @param set The <code>MathContext</code> arithmetic settings.
2153  * @return A <code>BigDecimal</code> whose value is
2154  * <code>this-rhs</code>.
2155  * @stable ICU 2.0
2156  */

2157 
2158 public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2159  com.ibm.icu.math.BigDecimal newrhs;
2160  if (set.lostDigits)
2161   checkdigits(rhs,set.digits);
2162  // [add will recheck .. but would report -rhs]
2163
/* carry out the subtraction */
2164  // we could fastpath -0, but it is too rare.
2165
newrhs=clone(rhs); // safe copy
2166
newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
2167
return this.add(newrhs,set); // arithmetic
2168
}
2169
2170 /* ---------------------------------------------------------------- */
2171 /* Other methods */
2172 /* ---------------------------------------------------------------- */
2173 
2174 /**
2175  * Converts this <code>BigDecimal</code> to a <code>byte</code>.
2176  * If the <code>BigDecimal</code> has a non-zero decimal part or is
2177  * out of the possible range for a <code>byte</code> (8-bit signed
2178  * integer) result then an <code>ArithmeticException</code> is thrown.
2179  *
2180  * @return A <code>byte</code> equal in value to <code>this</code>.
2181  * @throws ArithmeticException if <code>this</code> has a non-zero
2182  * decimal part, or will not fit in a <code>byte</code>.
2183  * @stable ICU 2.0
2184  */

2185 
2186 public byte byteValueExact(){
2187  int num;
2188  num=this.intValueExact(); // will check decimal part too
2189
if ((num>127)|(num<(-128)))
2190   throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
2191  return (byte)num;
2192  }
2193
2194 /**
2195  * Compares this <code>BigDecimal</code> with the value of the parameter.
2196  * <p>
2197  * If the parameter is <code>null</code>, or is not an instance of the
2198  * <code>BigDecimal</code> type, an exception is thrown.
2199  * Otherwise, the parameter is cast to type <code>BigDecimal</code>
2200  * and the result of the {@link #compareTo(BigDecimal)} method,
2201  * using the cast parameter, is returned.
2202  * <p>
2203  * The {@link #compareTo(BigDecimal, MathContext)} method should be
2204  * used when a <code>MathContext</code> is needed for the comparison.
2205  *
2206  * @param rhsobj The <code>Object</code> for the right hand side of
2207  * the comparison.
2208  * @return An <code>int</code> whose value is -1, 0, or 1 as
2209  * <code>this</code> is numerically less than, equal to,
2210  * or greater than <code>rhs</code>.
2211  * @throws ClassCastException if <code>rhs</code> cannot be cast to
2212  * a <code>BigDecimal</code> object.
2213  * @see #compareTo(BigDecimal)
2214  * @stable ICU 2.0
2215  */

2216 
2217 public int compareTo(java.lang.Object JavaDoc rhsobj){
2218  // the cast in the next line will raise ClassCastException if necessary
2219
return compareTo((com.ibm.icu.math.BigDecimal)rhsobj,plainMC);
2220  }
2221
2222 /**
2223  * Converts this <code>BigDecimal</code> to a <code>double</code>.
2224  * If the <code>BigDecimal</code> is out of the possible range for a
2225  * <code>double</code> (64-bit signed floating point) result then an
2226  * <code>ArithmeticException</code> is thrown.
2227  * <p>
2228  * The double produced is identical to result of expressing the
2229  * <code>BigDecimal</code> as a <code>String</code> and then
2230  * converting it using the <code>Double(String)</code> constructor;
2231  * this can result in values of <code>Double.NEGATIVE_INFINITY</code>
2232  * or <code>Double.POSITIVE_INFINITY</code>.
2233  *
2234  * @return A <code>double</code> corresponding to <code>this</code>.
2235  * @stable ICU 2.0
2236  */

2237 
2238 public double doubleValue(){
2239  // We go via a String [as does BigDecimal in JDK 1.2]
2240
// Next line could possibly raise NumberFormatException
2241
return java.lang.Double.valueOf(this.toString()).doubleValue();
2242  }
2243
2244 /**
2245  * Compares this <code>BigDecimal</code> with <code>rhs</code> for
2246  * equality.
2247  * <p>
2248  * If the parameter is <code>null</code>, or is not an instance of the
2249  * BigDecimal type, or is not exactly equal to the current
2250  * <code>BigDecimal</code> object, then <i>false</i> is returned.
2251  * Otherwise, <i>true</i> is returned.
2252  * <p>
2253  * "Exactly equal", here, means that the <code>String</code>
2254  * representations of the <code>BigDecimal</code> numbers are
2255  * identical (they have the same characters in the same sequence).
2256  * <p>
2257  * The {@link #compareTo(BigDecimal, MathContext)} method should be
2258  * used for more general comparisons.
2259  * @param obj The <code>Object</code> for the right hand side of
2260  * the comparison.
2261  * @return A <code>boolean</code> whose value <i>true</i> if and
2262  * only if the operands have identical string representations.
2263  * @throws ClassCastException if <code>rhs</code> cannot be cast to
2264  * a <code>BigDecimal</code> object.
2265  * @stable ICU 2.0
2266  * @see #compareTo(Object)
2267  * @see #compareTo(BigDecimal)
2268  * @see #compareTo(BigDecimal, MathContext)
2269  */

2270 
2271 public boolean equals(java.lang.Object JavaDoc obj){
2272  com.ibm.icu.math.BigDecimal rhs;
2273  int i=0;
2274  char lca[]=null;
2275  char rca[]=null;
2276  // We are equal iff toString of both are exactly the same
2277
if (obj==null)
2278   return false; // not equal
2279
if ((!(((obj instanceof com.ibm.icu.math.BigDecimal)))))
2280   return false; // not a decimal
2281
rhs=(com.ibm.icu.math.BigDecimal)obj; // cast; we know it will work
2282
if (this.ind!=rhs.ind)
2283   return false; // different signs never match
2284
if (((this.mant.length==rhs.mant.length)&(this.exp==rhs.exp))&(this.form==rhs.form))
2285   
2286   { // mantissas say all
2287
// here with equal-length byte arrays to compare
2288
{int $8=this.mant.length;i=0;i:for(;$8>0;$8--,i++){
2289     if (this.mant[i]!=rhs.mant[i])
2290      return false;
2291     }
2292    }/*i*/
2293   }
2294  else
2295   { // need proper layout
2296
lca=this.layout(); // layout to character array
2297
rca=rhs.layout();
2298    if (lca.length!=rca.length)
2299     return false; // mismatch
2300
// here with equal-length character arrays to compare
2301
{int $9=lca.length;i=0;i:for(;$9>0;$9--,i++){
2302     if (lca[i]!=rca[i])
2303      return false;
2304     }
2305    }/*i*/
2306   }
2307  return true; // arrays have identical content
2308
}
2309
2310 /**
2311  * Converts this <code>BigDecimal</code> to a <code>float</code>.
2312  * If the <code>BigDecimal</code> is out of the possible range for a
2313  * <code>float</code> (32-bit signed floating point) result then an
2314  * <code>ArithmeticException</code> is thrown.
2315  * <p>
2316  * The float produced is identical to result of expressing the
2317  * <code>BigDecimal</code> as a <code>String</code> and then
2318  * converting it using the <code>Float(String)</code> constructor;
2319  * this can result in values of <code>Float.NEGATIVE_INFINITY</code>
2320  * or <code>Float.POSITIVE_INFINITY</code>.
2321  *
2322  * @return A <code>float</code> corresponding to <code>this</code>.
2323  * @stable ICU 2.0
2324  */

2325 
2326 public float floatValue(){
2327  return java.lang.Float.valueOf(this.toString()).floatValue();
2328  }
2329
2330 /**
2331  * Returns the <code>String</code> representation of this
2332  * <code>BigDecimal</code>, modified by layout parameters.
2333  * <p>
2334  * <i>This method is provided as a primitive for use by more
2335  * sophisticated classes, such as <code>DecimalFormat</code>, that
2336  * can apply locale-sensitive editing of the result. The level of
2337  * formatting that it provides is a necessary part of the BigDecimal
2338  * class as it is sensitive to and must follow the calculation and
2339  * rounding rules for BigDecimal arithmetic.
2340  * However, if the function is provided elsewhere, it may be removed
2341  * from this class. </i>
2342  * <p>
2343  * The parameters, for both forms of the <code>format</code> method
2344  * are all of type <code>int</code>.
2345  * A value of -1 for any parameter indicates that the default action
2346  * or value for that parameter should be used.
2347  * <p>
2348  * The parameters, <code>before</code> and <code>after</code>,
2349  * specify the number of characters to be used for the integer part
2350  * and decimal part of the result respectively. Exponential notation
2351  * is not used. If either parameter is -1 (which indicates the default
2352  * action), the number of characters used will be exactly as many as
2353  * are needed for that part.
2354  * <p>
2355  * <code>before</code> must be a positive number; if it is larger than
2356  * is needed to contain the integer part, that part is padded on the
2357  * left with blanks to the requested length. If <code>before</code> is
2358  * not large enough to contain the integer part of the number
2359  * (including the sign, for negative numbers) an exception is thrown.
2360  * <p>
2361  * <code>after</code> must be a non-negative number; if it is not the
2362  * same size as the decimal part of the number, the number will be
2363  * rounded (or extended with zeros) to fit. Specifying 0 for
2364  * <code>after</code> will cause the number to be rounded to an
2365  * integer (that is, it will have no decimal part or decimal point).
2366  * The rounding method will be the default,
2367  * <code>MathContext.ROUND_HALF_UP</code>.
2368  * <p>
2369  * Other rounding methods, and the use of exponential notation, can
2370  * be selected by using {@link #format(int,int,int,int,int,int)}.
2371  * Using the two-parameter form of the method has exactly the same
2372  * effect as using the six-parameter form with the final four
2373  * parameters all being -1.
2374  *
2375  * @param before The <code>int</code> specifying the number of places
2376  * before the decimal point. Use -1 for 'as many as
2377  * are needed'.
2378  * @param after The <code>int</code> specifying the number of places
2379  * after the decimal point. Use -1 for 'as many as are
2380  * needed'.
2381  * @return A <code>String</code> representing this
2382  * <code>BigDecimal</code>, laid out according to the
2383  * specified parameters
2384  * @throws ArithmeticException if the number cannot be laid out as
2385  * requested.
2386  * @throws IllegalArgumentException if a parameter is out of range.
2387  * @stable ICU 2.0
2388  * @see #toString
2389  * @see #toCharArray
2390  */

2391 
2392 public java.lang.String JavaDoc format(int before,int after){
2393  return format(before,after,-1,-1,com.ibm.icu.math.MathContext.SCIENTIFIC,ROUND_HALF_UP);
2394  }
2395
2396 /**
2397  * Returns the <code>String</code> representation of this
2398  * <code>BigDecimal</code>, modified by layout parameters and allowing
2399  * exponential notation.
2400  * <p>
2401  * <i>This method is provided as a primitive for use by more
2402  * sophisticated classes, such as <code>DecimalFormat</code>, that
2403  * can apply locale-sensitive editing of the result. The level of
2404  * formatting that it provides is a necessary part of the BigDecimal
2405  * class as it is sensitive to and must follow the calculation and
2406  * rounding rules for BigDecimal arithmetic.
2407  * However, if the function is provided elsewhere, it may be removed
2408  * from this class. </i>
2409  * <p>
2410  * The parameters are all of type <code>int</code>.
2411  * A value of -1 for any parameter indicates that the default action
2412  * or value for that parameter should be used.
2413  * <p>
2414  * The first two parameters (<code>before</code> and
2415  * <code>after</code>) specify the number of characters to be used for
2416  * the integer part and decimal part of the result respectively, as
2417  * defined for {@link #format(int,int)}.
2418  * If either of these is -1 (which indicates the default action), the
2419  * number of characters used will be exactly as many as are needed for
2420  * that part.
2421  * <p>
2422  * The remaining parameters control the use of exponential notation
2423  * and rounding. Three (<code>explaces</code>, <code>exdigits</code>,
2424  * and <code>exform</code>) control the exponent part of the result.
2425  * As before, the default action for any of these parameters may be
2426  * selected by using the value -1.
2427  * <p>
2428  * <code>explaces</code> must be a positive number; it sets the number
2429  * of places (digits after the sign of the exponent) to be used for
2430  * any exponent part, the default (when <code>explaces</code> is -1)
2431  * being to use as many as are needed.
2432  * If <code>explaces</code> is not -1, space is always reserved for
2433  * an exponent; if one is not needed (for example, if the exponent
2434  * will be 0) then <code>explaces</code>+2 blanks are appended to the
2435  * result.
2436  * <!-- (This preserves vertical alignment of similarly formatted
2437  * numbers in a monospace font.) -->
2438  * If <code>explaces</code> is not -1 and is not large enough to
2439  * contain the exponent, an exception is thrown.
2440  * <p>
2441  * <code>exdigits</code> sets the trigger point for use of exponential
2442  * notation. If, before any rounding, the number of places needed
2443  * before the decimal point exceeds <code>exdigits</code>, or if the
2444  * absolute value of the result is less than <code>0.000001</code>,
2445  * then exponential form will be used, provided that
2446  * <code>exdigits</code> was specified.
2447  * When <code>exdigits</code> is -1, exponential notation will never
2448  * be used. If 0 is specified for <code>exdigits</code>, exponential
2449  * notation is always used unless the exponent would be 0.
2450  * <p>
2451  * <code>exform</code> sets the form for exponential notation (if
2452  * needed).
2453  * It may be either {@link MathContext#SCIENTIFIC} or
2454  * {@link MathContext#ENGINEERING}.
2455  * If the latter, engineering, form is requested, up to three digits
2456  * (plus sign, if negative) may be needed for the integer part of the
2457  * result (<code>before</code>). Otherwise, only one digit (plus
2458  * sign, if negative) is needed.
2459  * <p>
2460  * Finally, the sixth argument, <code>exround</code>, selects the
2461  * rounding algorithm to be used, and must be one of the values
2462  * indicated by a public constant in the {@link MathContext} class
2463  * whose name starts with <code>ROUND_</code>.
2464  * The default (<code>ROUND_HALF_UP</code>) may also be selected by
2465  * using the value -1, as before.
2466  * <p>
2467  * The special value <code>MathContext.ROUND_UNNECESSARY</code> may be
2468  * used to detect whether non-zero digits are discarded -- if
2469  * <code>exround</code> has this value than if non-zero digits would
2470  * be discarded (rounded) during formatting then an
2471  * <code>ArithmeticException</code> is thrown.
2472  *
2473  * @param before The <code>int</code> specifying the number of places
2474  * before the decimal point.
2475  * Use -1 for 'as many as are needed'.
2476  * @param after The <code>int</code> specifying the number of places
2477  * after the decimal point.
2478  * Use -1 for 'as many as are needed'.
2479  * @param explaces The <code>int</code> specifying the number of places
2480  * to be used for any exponent.
2481  * Use -1 for 'as many as are needed'.
2482  * @param exdigits The <code>int</code> specifying the trigger
2483  * (digits before the decimal point) which if
2484  * exceeded causes exponential notation to be used.
2485  * Use 0 to force exponential notation.
2486  * Use -1 to force plain notation (no exponential
2487  * notation).
2488  * @param exformint The <code>int</code> specifying the form of
2489  * exponential notation to be used
2490  * ({@link MathContext#SCIENTIFIC} or
2491  * {@link MathContext#ENGINEERING}).
2492  * @param exround The <code>int</code> specifying the rounding mode
2493  * to use.
2494  * Use -1 for the default, {@link MathContext#ROUND_HALF_UP}.
2495  * @return A <code>String</code> representing this
2496  * <code>BigDecimal</code>, laid out according to the
2497  * specified parameters
2498  * @throws ArithmeticException if the number cannot be laid out as
2499  * requested.
2500  * @throws IllegalArgumentException if a parameter is out of range.
2501  * @see #toString
2502  * @see #toCharArray
2503  * @stable ICU 2.0
2504  */

2505 
2506 public java.lang.String JavaDoc format(int before,int after,int explaces,int exdigits,int exformint,int exround){
2507  com.ibm.icu.math.BigDecimal num;
2508  int mag=0;
2509  int thisafter=0;
2510  int lead=0;
2511  byte newmant[]=null;
2512  int chop=0;
2513  int need=0;
2514  int oldexp=0;
2515  char a[];
2516  int p=0;
2517  char newa[]=null;
2518  int i=0;
2519  int places=0;
2520  
2521  
2522  /* Check arguments */
2523  if ((before<(-1))|(before==0))
2524   badarg("format",1,java.lang.String.valueOf(before));
2525  if (after<(-1))
2526   badarg("format",2,java.lang.String.valueOf(after));
2527  if ((explaces<(-1))|(explaces==0))
2528   badarg("format",3,java.lang.String.valueOf(explaces));
2529  if (exdigits<(-1))
2530   badarg("format",4,java.lang.String.valueOf(explaces));
2531  {/*select*/
2532  if (exformint==com.ibm.icu.math.MathContext.SCIENTIFIC){
2533  }else if (exformint==com.ibm.icu.math.MathContext.ENGINEERING){
2534  }else if (exformint==(-1))
2535   exformint=com.ibm.icu.math.MathContext.SCIENTIFIC;
2536   // note PLAIN isn't allowed
2537
else{
2538   badarg("format",5,java.lang.String.valueOf(exformint));
2539  }
2540  }
2541  // checking the rounding mode is done by trying to construct a
2542
// MathContext object with that mode; it will fail if bad
2543
if (exround!=ROUND_HALF_UP)
2544   {try{ // if non-default...
2545
if (exround==(-1))
2546     exround=ROUND_HALF_UP;
2547    else
2548     new com.ibm.icu.math.MathContext(9,com.ibm.icu.math.MathContext.SCIENTIFIC,false,exround);
2549   }
2550   catch (java.lang.IllegalArgumentException JavaDoc $10){
2551    badarg("format",6,java.lang.String.valueOf(exround));
2552   }}
2553  
2554  num=clone(this); // make private copy
2555

2556  /* Here:
2557     num is BigDecimal to format
2558     before is places before point [>0]
2559     after is places after point [>=0]
2560     explaces is exponent places [>0]
2561     exdigits is exponent digits [>=0]
2562     exformint is exponent form [one of two]
2563     exround is rounding mode [one of eight]
2564     'before' through 'exdigits' are -1 if not specified
2565  */

2566  
2567  /* determine form */
2568  {setform:do{/*select*/
2569  if (exdigits==(-1))
2570   num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2571  else if (num.ind==iszero)
2572   num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2573  else{
2574   // determine whether triggers
2575
mag=num.exp+num.mant.length;
2576   if (mag>exdigits)
2577    num.form=(byte)exformint;
2578   else
2579    if (mag<(-5))
2580     num.form=(byte)exformint;
2581    else
2582     num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2583  }
2584  }while(false);}/*setform*/
2585  
2586  /* If 'after' was specified then we may need to adjust the
2587     mantissa. This is a little tricky, as we must conform to the
2588     rules of exponential layout if necessary (e.g., we cannot end up
2589     with 10.0 if scientific). */

2590  if (after>=0)
2591   {setafter:for(;;){
2592    // calculate the current after-length
2593
{/*select*/
2594    if (num.form==com.ibm.icu.math.MathContext.PLAIN)
2595     thisafter=(int)-num.exp; // has decimal part
2596
else if (num.form==com.ibm.icu.math.MathContext.SCIENTIFIC)
2597     thisafter=num.mant.length-1;
2598    else{ // engineering
2599
lead=(((num.exp+num.mant.length)-1))%3; // exponent to use
2600
if (lead<0)
2601      lead=3+lead; // negative exponent case
2602
lead++; // number of leading digits
2603
if (lead>=num.mant.length)
2604      thisafter=0;
2605     else
2606      thisafter=num.mant.length-lead;
2607    }
2608    }
2609    if (thisafter==after)
2610     break setafter; // we're in luck
2611
if (thisafter<after)
2612     { // need added trailing zeros
2613
// [thisafter can be negative]
2614
newmant=extend(num.mant,(num.mant.length+after)-thisafter);
2615      num.mant=newmant;
2616      num.exp=num.exp-((after-thisafter)); // adjust exponent
2617
if (num.exp<MinExp)
2618       throw new java.lang.ArithmeticException JavaDoc("Exponent Overflow:"+" "+num.exp);
2619      break setafter;
2620     }
2621    // We have too many digits after the decimal point; this could
2622
// cause a carry, which could change the mantissa...
2623
// Watch out for implied leading zeros in PLAIN case
2624
chop=thisafter-after; // digits to lop [is >0]
2625
if (chop>num.mant.length)
2626     { // all digits go, no chance of carry
2627
// carry on with zero
2628
num.mant=ZERO.mant;
2629      num.ind=iszero;
2630      num.exp=0;
2631      continue setafter; // recheck: we may need trailing zeros
2632
}
2633    // we have a digit to inspect from existing mantissa
2634
// round the number as required
2635
need=num.mant.length-chop; // digits to end up with [may be 0]
2636
oldexp=num.exp; // save old exponent
2637
num.round(need,exround);
2638    // if the exponent grew by more than the digits we chopped, then
2639
// we must have had a carry, so will need to recheck the layout
2640
if ((num.exp-oldexp)==chop)
2641     break setafter; // number did not have carry
2642
// mantissa got extended .. so go around and check again
2643
}
2644   }/*setafter*/
2645  
2646  a=num.layout(); // lay out, with exponent if required, etc.
2647

2648  /* Here we have laid-out number in 'a' */
2649  // now apply 'before' and 'explaces' as needed
2650
if (before>0)
2651   {
2652    // look for '.' or 'E'
2653
{int $11=a.length;p=0;p:for(;$11>0;$11--,p++){
2654     if (a[p]=='.')
2655      break p;
2656     if (a[p]=='E')
2657      break p;
2658     }
2659    }/*p*/
2660    // p is now offset of '.', 'E', or character after end of array
2661
// that is, the current length of before part
2662
if (p>before)
2663     badarg("format",1,java.lang.String.valueOf(before)); // won't fit
2664
if (p<before)
2665     { // need leading blanks
2666
newa=new char[(a.length+before)-p];
2667      {int $12=before-p;i=0;i:for(;$12>0;$12--,i++){
2668       newa[i]=' ';
2669       }
2670      }/*i*/
2671      java.lang.System.arraycopy((java.lang.Object JavaDoc)a,0,(java.lang.Object JavaDoc)newa,i,a.length);
2672      a=newa;
2673     }
2674   // [if p=before then it's just the right length]
2675
}
2676  
2677  if (explaces>0)
2678   {
2679    // look for 'E' [cannot be at offset 0]
2680
{int $13=a.length-1;p=a.length-1;p:for(;$13>0;$13--,p--){
2681     if (a[p]=='E')
2682      break p;
2683     }
2684    }/*p*/
2685    // p is now offset of 'E', or 0
2686
if (p==0)
2687     { // no E part; add trailing blanks
2688
newa=new char[(a.length+explaces)+2];
2689      java.lang.System.arraycopy((java.lang.Object JavaDoc)a,0,(java.lang.Object JavaDoc)newa,0,a.length);
2690      {int $14=explaces+2;i=a.length;i:for(;$14>0;$14--,i++){
2691       newa[i]=' ';
2692       }
2693      }/*i*/
2694      a=newa;
2695     }
2696    else
2697     {/* found E */ // may need to insert zeros
2698
places=(a.length-p)-2; // number so far
2699
if (places>explaces)
2700       badarg("format",3,java.lang.String.valueOf(explaces));
2701      if (places<explaces)
2702       { // need to insert zeros
2703
newa=new char[(a.length+explaces)-places];
2704        java.lang.System.arraycopy((java.lang.Object JavaDoc)a,0,(java.lang.Object JavaDoc)newa,0,p+2); // through E and sign
2705
{int $15=explaces-places;i=p+2;i:for(;$15>0;$15--,i++){
2706         newa[i]='0';
2707         }
2708        }/*i*/
2709        java.lang.System.arraycopy((java.lang.Object JavaDoc)a,p+2,(java.lang.Object JavaDoc)newa,i,places); // remainder of exponent
2710
a=newa;
2711       }
2712     // [if places=explaces then it's just the right length]
2713
}
2714   }
2715  return new java.lang.String JavaDoc(a);
2716  }
2717
2718 /**
2719  * Returns the hashcode for this <code>BigDecimal</code>.
2720  * This hashcode is suitable for use by the
2721  * <code>java.util.Hashtable</code> class.
2722  * <p>
2723  * Note that two <code>BigDecimal</code> objects are only guaranteed
2724  * to produce the same hashcode if they are exactly equal (that is,
2725  * the <code>String</code> representations of the
2726  * <code>BigDecimal</code> numbers are identical -- they have the same
2727  * characters in the same sequence).
2728  *
2729  * @return An <code>int</code> that is the hashcode for <code>this</code>.
2730  * @stable ICU 2.0
2731  */

2732 
2733 public int hashCode(){
2734  // Maybe calculate ourselves, later. If so, note that there can be
2735
// more than one internal representation for a given toString() result.
2736
return this.toString().hashCode();
2737  }
2738
2739 /**
2740  * Converts this <code>BigDecimal</code> to an <code>int</code>.
2741  * If the <code>BigDecimal</code> has a non-zero decimal part it is
2742  * discarded. If the <code>BigDecimal</code> is out of the possible
2743  * range for an <code>int</code> (32-bit signed integer) result then
2744  * only the low-order 32 bits are used. (That is, the number may be
2745  * <i>decapitated</i>.) To avoid unexpected errors when these
2746  * conditions occur, use the {@link #intValueExact} method.
2747  *
2748  * @return An <code>int</code> converted from <code>this</code>,
2749  * truncated and decapitated if necessary.
2750  * @stable ICU 2.0
2751  */

2752 
2753 public int intValue(){
2754  return toBigInteger().intValue();
2755  }
2756
2757 /**
2758  * Converts this <code>BigDecimal</code> to an <code>int</code>.
2759  * If the <code>BigDecimal</code> has a non-zero decimal part or is
2760  * out of the possible range for an <code>int</code> (32-bit signed
2761  * integer) result then an <code>ArithmeticException</code> is thrown.
2762  *
2763  * @return An <code>int</code> equal in value to <code>this</code>.
2764  * @throws ArithmeticException if <code>this</code> has a non-zero
2765  * decimal part, or will not fit in an
2766  * <code>int</code>.
2767  * @stable ICU 2.0
2768  */

2769 
2770 public int intValueExact(){
2771  int lodigit;
2772  int useexp=0;
2773  int result;
2774  int i=0;
2775  int topdig=0;
2776  // This does not use longValueExact() as the latter can be much
2777
// slower.
2778
// intcheck (from pow) relies on this to check decimal part
2779
if (ind==iszero)
2780   return 0; // easy, and quite common
2781
/* test and drop any trailing decimal part */
2782  lodigit=mant.length-1;
2783  if (exp<0)
2784   {
2785    lodigit=lodigit+exp; // reduces by -(-exp)
2786
/* all decimal places must be 0 */
2787    if ((!(allzero(mant,lodigit+1))))
2788     throw new java.lang.ArithmeticException JavaDoc("Decimal part non-zero:"+" "+this.toString());
2789    if (lodigit<0)
2790     return 0; // -1<this<1
2791
useexp=0;
2792   }
2793  else
2794   {/* >=0 */
2795    if ((exp+lodigit)>9) // early exit
2796
throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
2797    useexp=exp;
2798   }
2799  /* convert the mantissa to binary, inline for speed */
2800  result=0;
2801  {int $16=lodigit+useexp;i=0;i:for(;i<=$16;i++){
2802   result=result*10;
2803   if (i<=lodigit)
2804    result=result+mant[i];
2805   }
2806  }/*i*/
2807  
2808  /* Now, if the risky length, check for overflow */
2809  if ((lodigit+useexp)==9)
2810   {
2811    // note we cannot just test for -ve result, as overflow can move a
2812
// zero into the top bit [consider 5555555555]
2813
topdig=result/1000000000; // get top digit, preserving sign
2814
if (topdig!=mant[0])
2815     { // digit must match and be positive
2816
// except in the special case ...
2817
if (result==java.lang.Integer.MIN_VALUE) // looks like the special
2818
if (ind==isneg) // really was negative
2819
if (mant[0]==2)
2820         return result; // really had top digit 2
2821
throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
2822     }
2823   }
2824  
2825  /* Looks good */
2826  if (ind==ispos)
2827   return result;
2828  return (int)-result;
2829  }
2830
2831 /**
2832  * Converts this <code>BigDecimal</code> to a <code>long</code>.
2833  * If the <code>BigDecimal</code> has a non-zero decimal part it is
2834  * discarded. If the <code>BigDecimal</code> is out of the possible
2835  * range for a <code>long</code> (64-bit signed integer) result then
2836  * only the low-order 64 bits are used. (That is, the number may be
2837  * <i>decapitated</i>.) To avoid unexpected errors when these
2838  * conditions occur, use the {@link #longValueExact} method.
2839  *
2840  * @return A <code>long</code> converted from <code>this</code>,
2841  * truncated and decapitated if necessary.
2842  * @stable ICU 2.0
2843  */

2844 
2845 public long longValue(){
2846  return toBigInteger().longValue();
2847  }
2848
2849 /**
2850  * Converts this <code>BigDecimal</code> to a <code>long</code>.
2851  * If the <code>BigDecimal</code> has a non-zero decimal part or is
2852  * out of the possible range for a <code>long</code> (64-bit signed
2853  * integer) result then an <code>ArithmeticException</code> is thrown.
2854  *
2855  * @return A <code>long</code> equal in value to <code>this</code>.
2856  * @throws ArithmeticException if <code>this</code> has a non-zero
2857  * decimal part, or will not fit in a
2858  * <code>long</code>.
2859  * @stable ICU 2.0
2860  */

2861 
2862 public long longValueExact(){
2863  int lodigit;
2864  int cstart=0;
2865  int useexp=0;
2866  long result;
2867  int i=0;
2868  long topdig=0;
2869  // Identical to intValueExact except for result=long, and exp>=20 test
2870
if (ind==0)
2871   return 0; // easy, and quite common
2872
lodigit=mant.length-1; // last included digit
2873
if (exp<0)
2874   {
2875    lodigit=lodigit+exp; // -(-exp)
2876
/* all decimal places must be 0 */
2877    if (lodigit<0)
2878     cstart=0;
2879    else
2880     cstart=lodigit+1;
2881    if ((!(allzero(mant,cstart))))
2882     throw new java.lang.ArithmeticException JavaDoc("Decimal part non-zero:"+" "+this.toString());
2883    if (lodigit<0)
2884     return 0; // -1<this<1
2885
useexp=0;
2886   }
2887  else
2888   {/* >=0 */
2889    if ((exp+mant.length)>18) // early exit
2890
throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
2891    useexp=exp;
2892   }
2893  
2894  /* convert the mantissa to binary, inline for speed */
2895  // note that we could safely use the 'test for wrap to negative'
2896
// algorithm here, but instead we parallel the intValueExact
2897
// algorithm for ease of checking and maintenance.
2898
result=(long)0;
2899  {int $17=lodigit+useexp;i=0;i:for(;i<=$17;i++){
2900   result=result*10;
2901   if (i<=lodigit)
2902    result=result+mant[i];
2903   }
2904  }/*i*/
2905  
2906  /* Now, if the risky length, check for overflow */
2907  if ((lodigit+useexp)==18)
2908   {
2909    topdig=result/1000000000000000000L; // get top digit, preserving sign
2910
if (topdig!=mant[0])
2911     { // digit must match and be positive
2912
// except in the special case ...
2913
if (result==java.lang.Long.MIN_VALUE) // looks like the special
2914
if (ind==isneg) // really was negative
2915
if (mant[0]==9)
2916         return result; // really had top digit 9
2917
throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
2918     }
2919   }
2920  
2921  /* Looks good */
2922  if (ind==ispos)
2923   return result;
2924  return (long)-result;
2925  }
2926
2927 /**
2928  * Returns a plain <code>BigDecimal</code> whose decimal point has
2929  * been moved to the left by a specified number of positions.
2930  * The parameter, <code>n</code>, specifies the number of positions to
2931  * move the decimal point.
2932  * That is, if <code>n</code> is 0 or positive, the number returned is
2933  * given by:
2934  * <p><code>
2935  * this.multiply(TEN.pow(new BigDecimal(-n)))
2936  * </code>
2937  * <p>
2938  * <code>n</code> may be negative, in which case the method returns
2939  * the same result as <code>movePointRight(-n)</code>.
2940  *
2941  * @param n The <code>int</code> specifying the number of places to
2942  * move the decimal point leftwards.
2943  * @return A <code>BigDecimal</code> derived from
2944  * <code>this</code>, with the decimal point moved
2945  * <code>n</code> places to the left.
2946  * @stable ICU 2.0
2947  */

2948 
2949 public com.ibm.icu.math.BigDecimal movePointLeft(int n){
2950  com.ibm.icu.math.BigDecimal res;
2951  // very little point in optimizing for shift of 0
2952
res=clone(this);
2953  res.exp=res.exp-n;
2954  return res.finish(plainMC,false); // finish sets form and checks exponent
2955
}
2956
2957 /**
2958  * Returns a plain <code>BigDecimal</code> whose decimal point has
2959  * been moved to the right by a specified number of positions.
2960  * The parameter, <code>n</code>, specifies the number of positions to
2961  * move the decimal point.
2962  * That is, if <code>n</code> is 0 or positive, the number returned is
2963  * given by:
2964  * <p><code>
2965  * this.multiply(TEN.pow(new BigDecimal(n)))
2966  * </code>
2967  * <p>
2968  * <code>n</code> may be negative, in which case the method returns
2969  * the same result as <code>movePointLeft(-n)</code>.
2970  *
2971  * @param n The <code>int</code> specifying the number of places to
2972  * move the decimal point rightwards.
2973  * @return A <code>BigDecimal</code> derived from
2974  * <code>this</code>, with the decimal point moved
2975  * <code>n</code> places to the right.
2976  * @stable ICU 2.0
2977  */

2978 
2979 public com.ibm.icu.math.BigDecimal movePointRight(int n){
2980  com.ibm.icu.math.BigDecimal res;
2981  res=clone(this);
2982  res.exp=res.exp+n;
2983  return res.finish(plainMC,false);
2984  }
2985
2986 /**
2987  * Returns the scale of this <code>BigDecimal</code>.
2988  * Returns a non-negative <code>int</code> which is the scale of the
2989  * number. The scale is the number of digits in the decimal part of
2990  * the number if the number were formatted without exponential
2991  * notation.
2992  *
2993  * @return An <code>int</code> whose value is the scale of this
2994  * <code>BigDecimal</code>.
2995  * @stable ICU 2.0
2996  */

2997 
2998 public int scale(){
2999  if (exp>=0)
3000   return 0; // scale can never be negative
3001
return (int)-exp;
3002  }
3003
3004 /**
3005  * Returns a plain <code>BigDecimal</code> with a given scale.
3006  * <p>
3007  * If the given scale (which must be zero or positive) is the same as
3008  * or greater than the length of the decimal part (the scale) of this
3009  * <code>BigDecimal</code> then trailing zeros will be added to the
3010  * decimal part as necessary.
3011  * <p>
3012  * If the given scale is less than the length of the decimal part (the
3013  * scale) of this <code>BigDecimal</code> then trailing digits
3014  * will be removed, and in this case an
3015  * <code>ArithmeticException</code> is thrown if any discarded digits
3016  * are non-zero.
3017  * <p>
3018  * The same as {@link #setScale(int, int)}, where the first parameter
3019  * is the scale, and the second is
3020  * <code>MathContext.ROUND_UNNECESSARY</code>.
3021  *
3022  * @param scale The <code>int</code> specifying the scale of the
3023  * resulting <code>BigDecimal</code>.
3024  * @return A plain <code>BigDecimal</code> with the given scale.
3025  * @throws ArithmeticException if <code>scale</code> is negative.
3026  * @throws ArithmeticException if reducing scale would discard
3027  * non-zero digits.
3028  * @stable ICU 2.0
3029  */

3030 
3031 public com.ibm.icu.math.BigDecimal setScale(int scale){
3032  return setScale(scale,ROUND_UNNECESSARY);
3033  }
3034
3035 /**
3036  * Returns a plain <code>BigDecimal</code> with a given scale.
3037  * <p>
3038  * If the given scale (which must be zero or positive) is the same as
3039  * or greater than the length of the decimal part (the scale) of this
3040  * <code>BigDecimal</code> then trailing zeros will be added to the
3041  * decimal part as necessary.
3042  * <p>
3043  * If the given scale is less than the length of the decimal part (the
3044  * scale) of this <code>BigDecimal</code> then trailing digits
3045  * will be removed, and the rounding mode given by the second
3046  * parameter is used to determine if the remaining digits are
3047  * affected by a carry.
3048  * In this case, an <code>IllegalArgumentException</code> is thrown if
3049  * <code>round</code> is not a valid rounding mode.
3050  * <p>
3051  * If <code>round</code> is <code>MathContext.ROUND_UNNECESSARY</code>,
3052  * an <code>ArithmeticException</code> is thrown if any discarded
3053  * digits are non-zero.
3054  *
3055  * @param scale The <code>int</code> specifying the scale of the
3056  * resulting <code>BigDecimal</code>.
3057  * @param round The <code>int</code> rounding mode to be used for
3058  * the division (see the {@link MathContext} class).
3059  * @return A plain <code>BigDecimal</code> with the given scale.
3060  * @throws IllegalArgumentException if <code>round</code> is not a
3061  * valid rounding mode.
3062  * @throws ArithmeticException if <code>scale</code> is negative.
3063  * @throws ArithmeticException if <code>round</code> is
3064  * <code>MathContext.ROUND_UNNECESSARY</code>, and
3065  * reducing scale would discard non-zero digits.
3066  * @stable ICU 2.0
3067  */

3068 
3069 public com.ibm.icu.math.BigDecimal setScale(int scale,int round){
3070  int ourscale;
3071  com.ibm.icu.math.BigDecimal res;
3072  int padding=0;
3073  int newlen=0;
3074  // at present this naughtily only checks the round value if it is
3075
// needed (used), for speed
3076
ourscale=this.scale();
3077  if (ourscale==scale) // already correct scale
3078
if (this.form==com.ibm.icu.math.MathContext.PLAIN) // .. and form
3079
return this;
3080  res=clone(this); // need copy
3081
if (ourscale<=scale)
3082   { // simply zero-padding/changing form
3083
// if ourscale is 0 we may have lots of 0s to add
3084
if (ourscale==0)
3085     padding=res.exp+scale;
3086    else
3087     padding=scale-ourscale;
3088    res.mant=extend(res.mant,res.mant.length+padding);
3089    res.exp=(int)-scale; // as requested
3090
}
3091  else
3092   {/* ourscale>scale: shortening, probably */
3093    if (scale<0)
3094     throw new java.lang.ArithmeticException JavaDoc("Negative scale:"+" "+scale);
3095    // [round() will raise exception if invalid round]
3096
newlen=res.mant.length-((ourscale-scale)); // [<=0 is OK]
3097
res=res.round(newlen,round); // round to required length
3098
// This could have shifted left if round (say) 0.9->1[.0]
3099
// Repair if so by adding a zero and reducing exponent
3100
if (res.exp!=((int)-scale))
3101     {
3102      res.mant=extend(res.mant,res.mant.length+1);
3103      res.exp=res.exp-1;
3104     }
3105   }
3106  res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // by definition
3107
return res;
3108  }
3109
3110 /**
3111  * Converts this <code>BigDecimal</code> to a <code>short</code>.
3112  * If the <code>BigDecimal</code> has a non-zero decimal part or is
3113  * out of the possible range for a <code>short</code> (16-bit signed
3114  * integer) result then an <code>ArithmeticException</code> is thrown.
3115  *
3116  * @return A <code>short</code> equal in value to <code>this</code>.
3117  * @throws ArithmeticException if <code>this</code> has a non-zero
3118  * decimal part, or will not fit in a
3119  * <code>short</code>.
3120  * @stable ICU 2.0
3121  */

3122 
3123 public short shortValueExact(){
3124  int num;
3125  num=this.intValueExact(); // will check decimal part too
3126
if ((num>32767)|(num<(-32768)))
3127   throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+this.toString());
3128  return (short)num;
3129  }
3130
3131 /**
3132  * Returns the sign of this <code>BigDecimal</code>, as an
3133  * <code>int</code>.
3134  * This returns the <i>signum</i> function value that represents the
3135  * sign of this <code>BigDecimal</code>.
3136  * That is, -1 if the <code>BigDecimal</code> is negative, 0 if it is
3137  * numerically equal to zero, or 1 if it is positive.
3138  *
3139  * @return An <code>int</code> which is -1 if the
3140  * <code>BigDecimal</code> is negative, 0 if it is
3141  * numerically equal to zero, or 1 if it is positive.
3142  * @stable ICU 2.0
3143  */

3144 
3145 public int signum(){
3146  return (int)this.ind; // [note this assumes values for ind.]
3147
}
3148
3149//#ifndef FOUNDATION
3150
//## /**
3151
//## * Converts this <code>BigDecimal</code> to a
3152
//## * <code>java.math.BigDecimal</code>.
3153
//## * <p>
3154
//## * This is an exact conversion; the result is the same as if the
3155
//## * <code>BigDecimal</code> were formatted as a plain number without
3156
//## * any rounding or exponent and then the
3157
//## * <code>java.math.BigDecimal(java.lang.String)</code> constructor
3158
//## * were used to construct the result.
3159
//## * <p>
3160
//## * <i>(Note: this method is provided only in the
3161
//## * <code>com.ibm.icu.math</code> version of the BigDecimal class.
3162
//## * It would not be present in a <code>java.math</code> version.)</i>
3163
//## *
3164
//## * @return The <code>java.math.BigDecimal</code> equal in value
3165
//## * to this <code>BigDecimal</code>.
3166
//## * @stable ICU 2.0
3167
//## */
3168
//##
3169
//## public java.math.BigDecimal toBigDecimal(){
3170
//## return new java.math.BigDecimal(this.unscaledValue(),this.scale());
3171
//## }
3172
//#endif
3173

3174 /**
3175  * Converts this <code>BigDecimal</code> to a
3176  * <code>java.math.BigInteger</code>.
3177  * <p>
3178  * Any decimal part is truncated (discarded).
3179  * If an exception is desired should the decimal part be non-zero,
3180  * use {@link #toBigIntegerExact()}.
3181  *
3182  * @return The <code>java.math.BigInteger</code> equal in value
3183  * to the integer part of this <code>BigDecimal</code>.
3184  * @stable ICU 2.0
3185  */

3186 
3187 public java.math.BigInteger JavaDoc toBigInteger(){
3188  com.ibm.icu.math.BigDecimal res=null;
3189  int newlen=0;
3190  byte newmant[]=null;
3191  {/*select*/
3192  if ((exp>=0)&(form==com.ibm.icu.math.MathContext.PLAIN))
3193   res=this; // can layout simply
3194
else if (exp>=0)
3195   {
3196    res=clone(this); // safe copy
3197
res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // .. and request PLAIN
3198
}
3199  else{
3200   { // exp<0; scale to be truncated
3201
// we could use divideInteger, but we may as well be quicker
3202
if (((int)-this.exp)>=this.mant.length)
3203     res=ZERO; // all blows away
3204
else
3205     {
3206      res=clone(this); // safe copy
3207
newlen=res.mant.length+res.exp;
3208      newmant=new byte[newlen]; // [shorter]
3209
java.lang.System.arraycopy((java.lang.Object JavaDoc)res.mant,0,(java.lang.Object JavaDoc)newmant,0,newlen);
3210      res.mant=newmant;
3211      res.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
3212      res.exp=0;
3213     }
3214   }
3215  }
3216  }
3217  return new BigInteger JavaDoc(new java.lang.String JavaDoc(res.layout()));
3218  }
3219
3220 /**
3221  * Converts this <code>BigDecimal</code> to a
3222  * <code>java.math.BigInteger</code>.
3223  * <p>
3224  * An exception is thrown if the decimal part (if any) is non-zero.
3225  *
3226  * @return The <code>java.math.BigInteger</code> equal in value
3227  * to the integer part of this <code>BigDecimal</code>.
3228  * @throws ArithmeticException if <code>this</code> has a non-zero
3229  * decimal part.
3230  * @stable ICU 2.0
3231  */

3232 
3233 public java.math.BigInteger JavaDoc toBigIntegerExact(){
3234  /* test any trailing decimal part */
3235  if (exp<0)
3236   { // possible decimal part
3237
/* all decimal places must be 0; note exp<0 */
3238    if ((!(allzero(mant,mant.length+exp))))
3239     throw new java.lang.ArithmeticException JavaDoc("Decimal part non-zero:"+" "+this.toString());
3240   }
3241  return toBigInteger();
3242  }
3243
3244 /**
3245  * Returns the <code>BigDecimal</code> as a character array.
3246  * The result of this method is the same as using the
3247  * sequence <code>toString().toCharArray()</code>, but avoids creating
3248  * the intermediate <code>String</code> and <code>char[]</code>
3249  * objects.
3250  *
3251  * @return The <code>char[]</code> array corresponding to this
3252  * <code>BigDecimal</code>.
3253  * @stable ICU 2.0
3254  */

3255 
3256 public char[] toCharArray(){
3257  return layout();
3258  }
3259
3260 /**
3261  * Returns the <code>BigDecimal</code> as a <code>String</code>.
3262  * This returns a <code>String</code> that exactly represents this
3263  * <code>BigDecimal</code>, as defined in the decimal documentation
3264  * (see {@link BigDecimal class header}).
3265  * <p>
3266  * By definition, using the {@link #BigDecimal(String)} constructor
3267  * on the result <code>String</code> will create a
3268  * <code>BigDecimal</code> that is exactly equal to the original
3269  * <code>BigDecimal</code>.
3270  *
3271  * @return The <code>String</code> exactly corresponding to this
3272  * <code>BigDecimal</code>.
3273  * @see #format(int, int)
3274  * @see #format(int, int, int, int, int, int)
3275  * @see #toCharArray()
3276  * @stable ICU 2.0
3277  */

3278 
3279 public java.lang.String JavaDoc toString(){
3280  return new java.lang.String JavaDoc(layout());
3281  }
3282
3283 /**
3284  * Returns the number as a <code>BigInteger</code> after removing the
3285  * scale.
3286  * That is, the number is expressed as a plain number, any decimal
3287  * point is then removed (retaining the digits of any decimal part),
3288  * and the result is then converted to a <code>BigInteger</code>.
3289  *
3290  * @return The <code>java.math.BigInteger</code> equal in value to
3291  * this <code>BigDecimal</code> multiplied by ten to the
3292  * power of <code>this.scale()</code>.
3293  * @stable ICU 2.0
3294  */

3295 
3296 public java.math.BigInteger JavaDoc unscaledValue(){
3297  com.ibm.icu.math.BigDecimal res=null;
3298  if (exp>=0)
3299   res=this;
3300  else
3301   {
3302    res=clone(this); // safe copy
3303
res.exp=0; // drop scale
3304
}
3305  return res.toBigInteger();
3306  }
3307
3308 /**
3309  * Translates a <code>double</code> to a <code>BigDecimal</code>.
3310  * <p>
3311  * Returns a <code>BigDecimal</code> which is the decimal
3312  * representation of the 64-bit signed binary floating point
3313  * parameter. If the parameter is infinite, or is not a number (NaN),
3314  * a <code>NumberFormatException</code> is thrown.
3315  * <p>
3316  * The number is constructed as though <code>num</code> had been
3317  * converted to a <code>String</code> using the
3318  * <code>Double.toString()</code> method and the
3319  * {@link #BigDecimal(java.lang.String)} constructor had then been used.
3320  * This is typically not an exact conversion.
3321  *
3322  * @param dub The <code>double</code> to be translated.
3323  * @return The <code>BigDecimal</code> equal in value to
3324  * <code>dub</code>.
3325  * @throws NumberFormatException if the parameter is infinite or
3326  * not a number.
3327  * @stable ICU 2.0
3328  */

3329 
3330 public static com.ibm.icu.math.BigDecimal valueOf(double dub){
3331  // Reminder: a zero double returns '0.0', so we cannot fastpath to
3332
// use the constant ZERO. This might be important enough to justify
3333
// a factory approach, a cache, or a few private constants, later.
3334
return new com.ibm.icu.math.BigDecimal((new java.lang.Double JavaDoc(dub)).toString());
3335  }
3336
3337 /**
3338  * Translates a <code>long</code> to a <code>BigDecimal</code>.
3339  * That is, returns a plain <code>BigDecimal</code> whose value is
3340  * equal to the given <code>long</code>.
3341  *
3342  * @param lint The <code>long</code> to be translated.
3343  * @return The <code>BigDecimal</code> equal in value to
3344  * <code>lint</code>.
3345  * @stable ICU 2.0
3346  */

3347 
3348 public static com.ibm.icu.math.BigDecimal valueOf(long lint){
3349  return valueOf(lint,0);
3350  }
3351
3352 /**
3353  * Translates a <code>long</code> to a <code>BigDecimal</code> with a
3354  * given scale.
3355  * That is, returns a plain <code>BigDecimal</code> whose unscaled
3356  * value is equal to the given <code>long</code>, adjusted by the
3357  * second parameter, <code>scale</code>.
3358  * <p>
3359  * The result is given by:
3360  * <p><code>
3361  * (new BigDecimal(lint)).divide(TEN.pow(new BigDecimal(scale)))
3362  * </code>
3363  * <p>
3364  * A <code>NumberFormatException</code> is thrown if <code>scale</code>
3365  * is negative.
3366  *
3367  * @param lint The <code>long</code> to be translated.
3368  * @param scale The <code>int</code> scale to be applied.
3369  * @return The <code>BigDecimal</code> equal in value to
3370  * <code>lint</code>.
3371  * @throws NumberFormatException if the scale is negative.
3372  * @stable ICU 2.0
3373  */

3374 
3375 public static com.ibm.icu.math.BigDecimal valueOf(long lint,int scale){
3376  com.ibm.icu.math.BigDecimal res=null;
3377  {/*select*/
3378  if (lint==0)
3379   res=ZERO;
3380  else if (lint==1)
3381   res=ONE;
3382  else if (lint==10)
3383   res=TEN;
3384  else{
3385   res=new com.ibm.icu.math.BigDecimal(lint);
3386  }
3387  }
3388  if (scale==0)
3389   return res;
3390  if (scale<0)
3391   throw new java.lang.NumberFormatException JavaDoc("Negative scale:"+" "+scale);
3392  res=clone(res); // safe copy [do not mutate]
3393
res.exp=(int)-scale; // exponent is -scale
3394
return res;
3395  }
3396
3397 /* ---------------------------------------------------------------- */
3398 /* Private methods */
3399 /* ---------------------------------------------------------------- */
3400 
3401 /* <sgml> Return char array value of a BigDecimal (conversion from
3402       BigDecimal to laid-out canonical char array).
3403    <p>The mantissa will either already have been rounded (following an
3404       operation) or will be of length appropriate (in the case of
3405       construction from an int, for example).
3406    <p>We must not alter the mantissa, here.
3407    <p>'form' describes whether we are to use exponential notation (and
3408       if so, which), or if we are to lay out as a plain/pure numeric.
3409    </sgml> */

3410 
3411 private char[] layout(){
3412  char cmant[];
3413  int i=0;
3414  java.lang.StringBuffer JavaDoc sb=null;
3415  int euse=0;
3416  int sig=0;
3417  char csign=0;
3418  char rec[]=null;
3419  int needsign;
3420  int mag;
3421  int len=0;
3422  cmant=new char[mant.length]; // copy byte[] to a char[]
3423
{int $18=mant.length;i=0;i:for(;$18>0;$18--,i++){
3424   cmant[i]=(char)(mant[i]+((int)('0')));
3425   }
3426  }/*i*/
3427  
3428  if (form!=com.ibm.icu.math.MathContext.PLAIN)
3429   {/* exponential notation needed */
3430    sb=new java.lang.StringBuffer JavaDoc(cmant.length+15); // -x.xxxE+999999999
3431
if (ind==isneg)
3432     sb.append('-');
3433    euse=(exp+cmant.length)-1; // exponent to use
3434
/* setup sig=significant digits and copy to result */
3435    if (form==com.ibm.icu.math.MathContext.SCIENTIFIC)
3436     { // [default]
3437
sb.append(cmant[0]); // significant character
3438
if (cmant.length>1) // have decimal part
3439
sb.append('.').append(cmant,1,cmant.length-1);
3440     }
3441    else
3442     {engineering:do{
3443      sig=euse%3; // common
3444
if (sig<0)
3445       sig=3+sig; // negative exponent
3446
euse=euse-sig;
3447      sig++;
3448      if (sig>=cmant.length)
3449       { // zero padding may be needed
3450
sb.append(cmant,0,cmant.length);
3451        {int $19=sig-cmant.length;for(;$19>0;$19--){
3452         sb.append('0');
3453         }
3454        }
3455       }
3456      else
3457       { // decimal point needed
3458
sb.append(cmant,0,sig).append('.').append(cmant,sig,cmant.length-sig);
3459       }
3460     }while(false);}/*engineering*/
3461    if (euse!=0)
3462     {
3463      if (euse<0)
3464       {
3465        csign='-';
3466        euse=(int)-euse;
3467       }
3468      else
3469       csign='+';
3470      sb.append('E').append(csign).append(euse);
3471     }
3472    rec=new char[sb.length()];
3473    Utility.getChars(sb, 0,sb.length(),rec,0);
3474    return rec;
3475   }
3476  
3477  /* Here for non-exponential (plain) notation */
3478  if (exp==0)
3479   {/* easy */
3480    if (ind>=0)
3481     return cmant; // non-negative integer
3482
rec=new char[cmant.length+1];
3483    rec[0]='-';
3484    java.lang.System.arraycopy((java.lang.Object JavaDoc)cmant,0,(java.lang.Object JavaDoc)rec,1,cmant.length);
3485    return rec;
3486   }
3487  
3488  /* Need a '.' and/or some zeros */
3489  needsign=(int)((ind==isneg)?1:0); // space for sign? 0 or 1
3490

3491  /* MAG is the position of the point in the mantissa (index of the
3492     character it follows) */

3493  mag=exp+cmant.length;
3494  
3495  if (mag<1)
3496   {/* 0.00xxxx form */
3497    len=(needsign+2)-exp; // needsign+2+(-mag)+cmant.length
3498
rec=new char[len];
3499    if (needsign!=0)
3500     rec[0]='-';
3501    rec[needsign]='0';
3502    rec[needsign+1]='.';
3503    {int $20=(int)-mag;i=needsign+2;i:for(;$20>0;$20--,i++){ // maybe none
3504
rec[i]='0';
3505     }
3506    }/*i*/
3507    java.lang.System.arraycopy((java.lang.Object JavaDoc)cmant,0,(java.lang.Object JavaDoc)rec,(needsign+2)-mag,cmant.length);
3508    return rec;
3509   }
3510  
3511  if (mag>cmant.length)
3512   {/* xxxx0000 form */
3513    len=needsign+mag;
3514    rec=new char[len];
3515    if (needsign!=0)
3516     rec[0]='-';
3517    java.lang.System.arraycopy((java.lang.Object JavaDoc)cmant,0,(java.lang.Object JavaDoc)rec,needsign,cmant.length);
3518    {int $21=mag-cmant.length;i=needsign+cmant.length;i:for(;$21>0;$21--,i++){ // never 0
3519
rec[i]='0';
3520     }
3521    }/*i*/
3522    return rec;
3523   }
3524  
3525  /* decimal point is in the middle of the mantissa */
3526  len=(needsign+1)+cmant.length;
3527  rec=new char[len];
3528  if (needsign!=0)
3529   rec[0]='-';
3530  java.lang.System.arraycopy((java.lang.Object JavaDoc)cmant,0,(java.lang.Object JavaDoc)rec,needsign,mag);
3531  rec[needsign+mag]='.';
3532  java.lang.System.arraycopy((java.lang.Object JavaDoc)cmant,mag,(java.lang.Object JavaDoc)rec,(needsign+mag)+1,cmant.length-mag);
3533  return rec;
3534  }
3535
3536 /* <sgml> Checks a BigDecimal argument to ensure it's a true integer
3537       in a given range.
3538    <p>If OK, returns it as an int. </sgml> */

3539 // [currently only used by pow]
3540

3541 private int intcheck(int min,int max){
3542  int i;
3543  i=this.intValueExact(); // [checks for non-0 decimal part]
3544
// Use same message as though intValueExact failed due to size
3545
if ((i<min)|(i>max))
3546   throw new java.lang.ArithmeticException JavaDoc("Conversion overflow:"+" "+i);
3547  return i;
3548  }
3549
3550 /* <sgml> Carry out division operations. </sgml> */
3551 /*
3552    Arg1 is operation code: D=divide, I=integer divide, R=remainder
3553    Arg2 is the rhs.
3554    Arg3 is the context.
3555    Arg4 is explicit scale iff code='D' or 'I' (-1 if none).
3556 
3557    Underlying algorithm (complications for Remainder function and
3558    scaled division are omitted for clarity):
3559 
3560      Test for x/0 and then 0/x
3561      Exp =Exp1 - Exp2
3562      Exp =Exp +len(var1) -len(var2)
3563      Sign=Sign1 * Sign2
3564      Pad accumulator (Var1) to double-length with 0's (pad1)
3565      Pad Var2 to same length as Var1
3566      B2B=1st two digits of var2, +1 to allow for roundup
3567      have=0
3568      Do until (have=digits+1 OR residue=0)
3569        if exp<0 then if integer divide/residue then leave
3570        this_digit=0
3571        Do forever
3572           compare numbers
3573           if <0 then leave inner_loop
3574           if =0 then (- quick exit without subtract -) do
3575              this_digit=this_digit+1; output this_digit
3576              leave outer_loop; end
3577           Compare lengths of numbers (mantissae):
3578           If same then CA=first_digit_of_Var1
3579                   else CA=first_two_digits_of_Var1
3580           mult=ca*10/b2b -- Good and safe guess at divisor
3581           if mult=0 then mult=1
3582           this_digit=this_digit+mult
3583           subtract
3584           end inner_loop
3585         if have\=0 | this_digit\=0 then do
3586           output this_digit
3587           have=have+1; end
3588         var2=var2/10
3589         exp=exp-1
3590         end outer_loop
3591      exp=exp+1 -- set the proper exponent
3592      if have=0 then generate answer=0
3593      Return to FINISHED
3594      Result defined by MATHV1
3595 
3596    For extended commentary, see DMSRCN.
3597  */

3598 
3599 private com.ibm.icu.math.BigDecimal dodivide(char code,com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set,int scale){
3600  com.ibm.icu.math.BigDecimal lhs;
3601  int reqdig;
3602  int newexp;
3603  com.ibm.icu.math.BigDecimal res;
3604  int newlen;
3605  byte var1[];
3606  int var1len;
3607  byte var2[];
3608  int var2len;
3609  int b2b;
3610  int have;
3611  int thisdigit=0;
3612  int i=0;
3613  byte v2=0;
3614  int ba=0;
3615  int mult=0;
3616  int start=0;
3617  int padding=0;
3618  int d=0;
3619  byte newvar1[]=null;
3620  byte lasthave=0;
3621  int actdig=0;
3622  byte newmant[]=null;
3623  
3624  if (set.lostDigits)
3625   checkdigits(rhs,set.digits);
3626  lhs=this; // name for clarity
3627

3628  // [note we must have checked lostDigits before the following checks]
3629
if (rhs.ind==0)
3630   throw new java.lang.ArithmeticException JavaDoc("Divide by 0"); // includes 0/0
3631
if (lhs.ind==0)
3632   { // 0/x => 0 [possibly with .0s]
3633
if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
3634     return ZERO;
3635    if (scale==(-1))
3636     return lhs;
3637    return lhs.setScale(scale);
3638   }
3639  
3640  /* Prepare numbers according to BigDecimal rules */
3641  reqdig=set.digits; // local copy (heavily used)
3642
if (reqdig>0)
3643   {
3644    if (lhs.mant.length>reqdig)
3645     lhs=clone(lhs).round(set);
3646    if (rhs.mant.length>reqdig)
3647     rhs=clone(rhs).round(set);
3648   }
3649  else
3650   {/* scaled divide */
3651    if (scale==(-1))
3652     scale=lhs.scale();
3653    // set reqdig to be at least large enough for the computation
3654
reqdig=lhs.mant.length; // base length
3655
// next line handles both positive lhs.exp and also scale mismatch
3656
if (scale!=((int)-lhs.exp))
3657     reqdig=(reqdig+scale)+lhs.exp;
3658    reqdig=(reqdig-((rhs.mant.length-1)))-rhs.exp; // reduce by RHS effect
3659
if (reqdig<lhs.mant.length)
3660     reqdig=lhs.mant.length; // clamp
3661
if (reqdig<rhs.mant.length)
3662     reqdig=rhs.mant.length; // ..
3663
}
3664  
3665  /* precalculate exponent */
3666  newexp=((lhs.exp-rhs.exp)+lhs.mant.length)-rhs.mant.length;
3667  /* If new exponent -ve, then some quick exits are possible */
3668  if (newexp<0)
3669   if (code!='D')
3670    {
3671     if (code=='I')
3672      return ZERO; // easy - no integer part
3673
/* Must be 'R'; remainder is [finished clone of] input value */
3674     return clone(lhs).finish(set,false);
3675    }
3676  
3677  /* We need slow division */
3678  res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
3679
res.ind=(byte)(lhs.ind*rhs.ind); // final sign (for D/I)
3680
res.exp=newexp; // initial exponent (for D/I)
3681
res.mant=new byte[reqdig+1]; // where build the result
3682

3683  /* Now [virtually pad the mantissae with trailing zeros */
3684  // Also copy the LHS, which will be our working array
3685
newlen=(reqdig+reqdig)+1;
3686  var1=extend(lhs.mant,newlen); // always makes longer, so new safe array
3687
var1len=newlen; // [remaining digits are 0]
3688

3689  var2=rhs.mant;
3690  var2len=newlen;
3691  
3692  /* Calculate first two digits of rhs (var2), +1 for later estimations */
3693  b2b=(var2[0]*10)+1;
3694  if (var2.length>1)
3695   b2b=b2b+var2[1];
3696  
3697  /* start the long-division loops */
3698  have=0;
3699  {outer:for(;;){
3700   thisdigit=0;
3701   /* find the next digit */
3702   {inner:for(;;){
3703    if (var1len<var2len)
3704     break inner; // V1 too low
3705
if (var1len==var2len)
3706     { // compare needed
3707
{compare:do{ // comparison
3708
{int $22=var1len;i=0;i:for(;$22>0;$22--,i++){
3709        // var1len is always <= var1.length
3710
if (i<var2.length)
3711         v2=var2[i];
3712        else
3713         v2=(byte)0;
3714        if (var1[i]<v2)
3715         break inner; // V1 too low
3716
if (var1[i]>v2)
3717         break compare; // OK to subtract
3718
}
3719       }/*i*/
3720       /* reach here if lhs and rhs are identical; subtraction will
3721          increase digit by one, and the residue will be 0 so we
3722          are done; leave the loop with residue set to 0 (in case
3723          code is 'R' or ROUND_UNNECESSARY or a ROUND_HALF_xxxx is
3724          being checked) */

3725       thisdigit++;
3726       res.mant[have]=(byte)thisdigit;
3727       have++;
3728       var1[0]=(byte)0; // residue to 0 [this is all we'll test]
3729
// var1len=1 -- [optimized out]
3730
break outer;
3731      }while(false);}/*compare*/
3732      /* prepare for subtraction. Estimate BA (lengths the same) */
3733      ba=(int)var1[0]; // use only first digit
3734
} // lengths the same
3735
else
3736     {/* lhs longer than rhs */
3737      /* use first two digits for estimate */
3738      ba=var1[0]*10;
3739      if (var1len>1)
3740       ba=ba+var1[1];
3741     }
3742    /* subtraction needed; V1>=V2 */
3743    mult=(ba*10)/b2b;
3744    if (mult==0)
3745     mult=1;
3746    thisdigit=thisdigit+mult;
3747    // subtract; var1 reusable
3748
var1=byteaddsub(var1,var1len,var2,var2len,(int)-mult,true);
3749    if (var1[0]!=0)
3750     continue inner; // maybe another subtract needed
3751
/* V1 now probably has leading zeros, remove leading 0's and try
3752       again. (It could be longer than V2) */

3753    {int $23=var1len-2;start=0;start:for(;start<=$23;start++){
3754     if (var1[start]!=0)
3755      break start;
3756     var1len--;
3757     }
3758    }/*start*/
3759    if (start==0)
3760     continue inner;
3761    // shift left
3762
java.lang.System.arraycopy((java.lang.Object JavaDoc)var1,start,(java.lang.Object JavaDoc)var1,0,var1len);
3763    }
3764   }/*inner*/
3765   
3766   /* We have the next digit */
3767   if ((have!=0)|(thisdigit!=0))
3768    { // put the digit we got
3769
res.mant[have]=(byte)thisdigit;
3770     have++;
3771     if (have==(reqdig+1))
3772      break outer; // we have all we need
3773
if (var1[0]==0)
3774      break outer; // residue now 0
3775
}
3776   /* can leave now if a scaled divide and exponent is small enough */
3777   if (scale>=0)
3778    if (((int)-res.exp)>scale)
3779     break outer;
3780   /* can leave now if not Divide and no integer part left */
3781   if (code!='D')
3782    if (res.exp<=0)
3783     break outer;
3784   res.exp=res.exp-1; // reduce the exponent
3785
/* to get here, V1 is less than V2, so divide V2 by 10 and go for
3786      the next digit */

3787   var2len--;
3788   }
3789  }/*outer*/
3790  
3791  /* here when we have finished dividing, for some reason */
3792  // have is the number of digits we collected in res.mant
3793
if (have==0)
3794   have=1; // res.mant[0] is 0; we always want a digit
3795

3796  if ((code=='I')|(code=='R'))
3797   {/* check for integer overflow needed */
3798    if ((have+res.exp)>reqdig)
3799     throw new java.lang.ArithmeticException JavaDoc("Integer overflow");
3800    
3801    if (code=='R')
3802     {remainder:do{
3803      /* We were doing Remainder -- return the residue */
3804      if (res.mant[0]==0) // no integer part was found
3805
return clone(lhs).finish(set,false); // .. so return lhs, canonical
3806
if (var1[0]==0)
3807       return ZERO; // simple 0 residue
3808
res.ind=lhs.ind; // sign is always as LHS
3809
/* Calculate the exponent by subtracting the number of padding zeros
3810         we added and adding the original exponent */

3811      padding=((reqdig+reqdig)+1)-lhs.mant.length;
3812      res.exp=(res.exp-padding)+lhs.exp;
3813      
3814      /* strip insignificant padding zeros from residue, and create/copy
3815         the resulting mantissa if need be */

3816      d=var1len;
3817      {i=d-1;i:for(;i>=1;i--){if(!((res.exp<lhs.exp)&(res.exp<rhs.exp)))break;
3818       if (var1[i]!=0)
3819        break i;
3820       d--;
3821       res.exp=res.exp+1;
3822       }
3823      }/*i*/
3824      if (d<var1.length)
3825       {/* need to reduce */
3826        newvar1=new byte[d];
3827        java.lang.System.arraycopy((java.lang.Object JavaDoc)var1,0,(java.lang.Object JavaDoc)newvar1,0,d); // shorten
3828
var1=newvar1;
3829       }
3830      res.mant=var1;
3831      return res.finish(set,false);
3832     }while(false);}/*remainder*/
3833   }
3834   
3835  else
3836   {/* 'D' -- no overflow check needed */
3837    // If there was a residue then bump the final digit (iff 0 or 5)
3838
// so that the residue is visible for ROUND_UP, ROUND_HALF_xxx and
3839
// ROUND_UNNECESSARY checks (etc.) later.
3840
// [if we finished early, the residue will be 0]
3841
if (var1[0]!=0)
3842     { // residue not 0
3843
lasthave=res.mant[have-1];
3844      if (((lasthave%5))==0)
3845       res.mant[have-1]=(byte)(lasthave+1);
3846     }
3847   }
3848  
3849  /* Here for Divide or Integer Divide */
3850  // handle scaled results first ['I' always scale 0, optional for 'D']
3851
if (scale>=0)
3852   {scaled:do{
3853    // say 'scale have res.exp len' scale have res.exp res.mant.length
3854
if (have!=res.mant.length)
3855     // already padded with 0's, so just adjust exponent
3856
res.exp=res.exp-((res.mant.length-have));
3857    // calculate number of digits we really want [may be 0]
3858
actdig=res.mant.length-((((int)-res.exp)-scale));
3859    res.round(actdig,set.roundingMode); // round to desired length
3860
// This could have shifted left if round (say) 0.9->1[.0]
3861
// Repair if so by adding a zero and reducing exponent
3862
if (res.exp!=((int)-scale))
3863     {
3864      res.mant=extend(res.mant,res.mant.length+1);
3865      res.exp=res.exp-1;
3866     }
3867    return res.finish(set,true); // [strip if not PLAIN]
3868
}while(false);}/*scaled*/
3869  
3870  // reach here only if a non-scaled
3871
if (have==res.mant.length)
3872   { // got digits+1 digits
3873
res.round(set);
3874    have=reqdig;
3875   }
3876  else
3877   {/* have<=reqdig */
3878    if (res.mant[0]==0)
3879     return ZERO; // fastpath
3880
// make the mantissa truly just 'have' long
3881
// [we could let finish do this, during strip, if we adjusted
3882
// the exponent; however, truncation avoids the strip loop]
3883
newmant=new byte[have]; // shorten
3884
java.lang.System.arraycopy((java.lang.Object JavaDoc)res.mant,0,(java.lang.Object JavaDoc)newmant,0,have);
3885    res.mant=newmant;
3886   }
3887  return res.finish(set,true);
3888  }
3889
3890 
3891 /* <sgml> Report a conversion exception. </sgml> */
3892 
3893 private void bad(char s[]){
3894  throw new java.lang.NumberFormatException JavaDoc("Not a number:"+" "+java.lang.String.valueOf(s));
3895  }
3896
3897 /* <sgml> Report a bad argument to a method. </sgml>
3898    Arg1 is method name
3899    Arg2 is argument position
3900    Arg3 is what was found */

3901 
3902 private void badarg(java.lang.String JavaDoc name,int pos,java.lang.String JavaDoc value){
3903  throw new java.lang.IllegalArgumentException JavaDoc("Bad argument"+" "+pos+" "+"to"+" "+name+":"+" "+value);
3904  }
3905
3906 /* <sgml> Extend byte array to given length, padding with 0s. If no
3907    extension is required then return the same array. </sgml>
3908 
3909    Arg1 is the source byte array
3910    Arg2 is the new length (longer)
3911    */

3912 
3913 private static final byte[] extend(byte inarr[],int newlen){
3914  byte newarr[];
3915  if (inarr.length==newlen)
3916   return inarr;
3917  newarr=new byte[newlen];
3918  java.lang.System.arraycopy((java.lang.Object JavaDoc)inarr,0,(java.lang.Object JavaDoc)newarr,0,inarr.length);
3919  // 0 padding is carried out by the JVM on allocation initialization
3920
return newarr;
3921  }
3922
3923 /* <sgml> Add or subtract two >=0 integers in byte arrays
3924    <p>This routine performs the calculation:
3925    <pre>
3926    C=A+(B*M)
3927    </pre>
3928    Where M is in the range -9 through +9
3929    <p>
3930    If M<0 then A>=B must be true, so the result is always
3931    non-negative.
3932 
3933    Leading zeros are not removed after a subtraction. The result is
3934    either the same length as the longer of A and B, or 1 longer than
3935    that (if a carry occurred).
3936 
3937    A is not altered unless Arg6 is 1.
3938    B is never altered.
3939 
3940    Arg1 is A
3941    Arg2 is A length to use (if longer than A, pad with 0's)
3942    Arg3 is B
3943    Arg4 is B length to use (if longer than B, pad with 0's)
3944    Arg5 is M, the multiplier
3945    Arg6 is 1 if A can be used to build the result (if it fits)
3946 
3947    This routine is severely performance-critical; *any* change here
3948    must be measured (timed) to assure no performance degradation.
3949    */

3950 // 1996.02.20 -- enhanced version of DMSRCN algorithm (1981)
3951
// 1997.10.05 -- changed to byte arrays (from char arrays)
3952
// 1998.07.01 -- changed to allow destructive reuse of LHS
3953
// 1998.07.01 -- changed to allow virtual lengths for the arrays
3954
// 1998.12.29 -- use lookaside for digit/carry calculation
3955
// 1999.08.07 -- avoid multiply when mult=1, and make db an int
3956
// 1999.12.22 -- special case m=-1, also drop 0 special case
3957

3958 private static final byte[] byteaddsub(byte a[],int avlen,byte b[],int bvlen,int m,boolean reuse){
3959  int alength;
3960  int blength;
3961  int ap;
3962  int bp;
3963  int maxarr;
3964  byte reb[];
3965  boolean quickm;
3966  int digit;
3967  int op=0;
3968  int dp90=0;
3969  byte newarr[];
3970  int i=0;
3971  
3972  
3973  
3974  
3975  // We'll usually be right if we assume no carry
3976
alength=a.length; // physical lengths
3977
blength=b.length; // ..
3978
ap=avlen-1; // -> final (rightmost) digit
3979
bp=bvlen-1; // ..
3980
maxarr=bp;
3981  if (maxarr<ap)
3982   maxarr=ap;
3983  reb=(byte[])null; // result byte array
3984
if (reuse)
3985   if ((maxarr+1)==alength)
3986    reb=a; // OK to reuse A
3987
if (reb==null)
3988   reb=new byte[maxarr+1]; // need new array
3989

3990  quickm=false; // 1 if no multiply needed
3991
if (m==1)
3992   quickm=true; // most common
3993
else
3994   if (m==(-1))
3995    quickm=true; // also common
3996

3997  digit=0; // digit, with carry or borrow
3998
{op=maxarr;op:for(;op>=0;op--){
3999   if (ap>=0)
4000    {
4001     if (ap<alength)
4002      digit=digit+a[ap]; // within A
4003
ap--;
4004    }
4005   if (bp>=0)
4006    {
4007     if (bp<blength)
4008      { // within B
4009
if (quickm)
4010        {
4011         if (m>0)
4012          digit=digit+b[bp]; // most common
4013
else
4014          digit=digit-b[bp]; // also common
4015
}
4016       else
4017        digit=digit+(b[bp]*m);
4018      }
4019     bp--;
4020    }
4021   /* result so far (digit) could be -90 through 99 */
4022   if (digit<10)
4023    if (digit>=0)
4024     {quick:do{ // 0-9
4025
reb[op]=(byte)digit;
4026      digit=0; // no carry
4027
continue op;
4028     }while(false);}/*quick*/
4029   dp90=digit+90;
4030   reb[op]=bytedig[dp90]; // this digit
4031
digit=bytecar[dp90]; // carry or borrow
4032
}
4033  }/*op*/
4034  
4035  if (digit==0)
4036   return reb; // no carry
4037
// following line will become an Assert, later
4038
// if digit<0 then signal ArithmeticException("internal.error ["digit"]")
4039

4040  /* We have carry -- need to make space for the extra digit */
4041  newarr=(byte[])null;
4042  if (reuse)
4043   if ((maxarr+2)==a.length)
4044    newarr=a; // OK to reuse A
4045
if (newarr==null)
4046   newarr=new byte[maxarr+2];
4047  newarr[0]=(byte)digit; // the carried digit ..
4048
// .. and all the rest [use local loop for short numbers]
4049
if (maxarr<10)
4050   {int $24=maxarr+1;i=0;i:for(;$24>0;$24--,i++){
4051    newarr[i+1]=reb[i];
4052    }
4053   }/*i*/
4054  else
4055   java.lang.System.arraycopy((java.lang.Object JavaDoc)reb,0,(java.lang.Object JavaDoc)newarr,1,maxarr+1);
4056  return newarr;
4057  }
4058
4059 /* <sgml> Initializer for digit array properties (lookaside). </sgml>
4060    Returns the digit array, and initializes the carry array. */

4061 
4062 private static final byte[] diginit(){
4063  byte work[];
4064  int op=0;
4065  int digit=0;
4066  work=new byte[(90+99)+1];
4067  {op=0;op:for(;op<=(90+99);op++){
4068   digit=op-90;
4069   if (digit>=0)
4070    {
4071     work[op]=(byte)(digit%10);
4072     bytecar[op]=(byte)(digit/10); // calculate carry
4073
continue op;
4074    }
4075   // borrowing...
4076
digit=digit+100; // yes, this is right [consider -50]
4077
work[op]=(byte)(digit%10);
4078   bytecar[op]=(byte)((digit/10)-10); // calculate borrow [NB: - after %]
4079
}
4080  }/*op*/
4081  return work;
4082  }
4083
4084 /* <sgml> Create a copy of BigDecimal object for local use.
4085    <p>This does NOT make a copy of the mantissa array.
4086    </sgml>
4087    Arg1 is the BigDecimal to clone (non-null)
4088    */

4089 
4090 private static final com.ibm.icu.math.BigDecimal clone(com.ibm.icu.math.BigDecimal dec){
4091  com.ibm.icu.math.BigDecimal copy;
4092  copy=new com.ibm.icu.math.BigDecimal();
4093  copy.ind=dec.ind;
4094  copy.exp=dec.exp;
4095  copy.form=dec.form;
4096  copy.mant=dec.mant;
4097  return copy;
4098  }
4099
4100 /* <sgml> Check one or two numbers for lost digits. </sgml>
4101    Arg1 is RHS (or null, if none)
4102    Arg2 is current DIGITS setting
4103    returns quietly or throws an exception */

4104 
4105 private void checkdigits(com.ibm.icu.math.BigDecimal rhs,int dig){
4106  if (dig==0)
4107   return; // don't check if digits=0
4108
// first check lhs...
4109
if (this.mant.length>dig)
4110   if ((!(allzero(this.mant,dig))))
4111    throw new java.lang.ArithmeticException JavaDoc("Too many digits:"+" "+this.toString());
4112  if (rhs==null)
4113   return; // monadic
4114
if (rhs.mant.length>dig)
4115   if ((!(allzero(rhs.mant,dig))))
4116    throw new java.lang.ArithmeticException JavaDoc("Too many digits:"+" "+rhs.toString());
4117  }
4118
4119 /* <sgml> Round to specified digits, if necessary. </sgml>
4120    Arg1 is requested MathContext [with length and rounding mode]
4121    returns this, for convenience */

4122 
4123 private com.ibm.icu.math.BigDecimal round(com.ibm.icu.math.MathContext set){
4124  return round(set.digits,set.roundingMode);
4125  }
4126
4127 /* <sgml> Round to specified digits, if necessary.
4128    Arg1 is requested length (digits to round to)
4129            [may be <=0 when called from format, dodivide, etc.]
4130    Arg2 is rounding mode
4131    returns this, for convenience
4132 
4133    ind and exp are adjusted, but not cleared for a mantissa of zero
4134 
4135    The length of the mantissa returned will be Arg1, except when Arg1
4136    is 0, in which case the returned mantissa length will be 1.
4137    </sgml>
4138    */

4139 
4140 private com.ibm.icu.math.BigDecimal round(int len,int mode){
4141  int adjust;
4142  int sign;
4143  byte oldmant[];
4144  boolean reuse=false;
4145  byte first=0;
4146  int increment;
4147  byte newmant[]=null;
4148  adjust=mant.length-len;
4149  if (adjust<=0)
4150   return this; // nowt to do
4151

4152  exp=exp+adjust; // exponent of result
4153
sign=(int)ind; // save [assumes -1, 0, 1]
4154
oldmant=mant; // save
4155
if (len>0)
4156   {
4157    // remove the unwanted digits
4158
mant=new byte[len];
4159    java.lang.System.arraycopy((java.lang.Object JavaDoc)oldmant,0,(java.lang.Object JavaDoc)mant,0,len);
4160    reuse=true; // can reuse mantissa
4161
first=oldmant[len]; // first of discarded digits
4162
}
4163  else
4164   {/* len<=0 */
4165    mant=ZERO.mant;
4166    ind=iszero;
4167    reuse=false; // cannot reuse mantissa
4168
if (len==0)
4169     first=oldmant[0];
4170    else
4171     first=(byte)0; // [virtual digit]
4172
}
4173  
4174  // decide rounding adjustment depending on mode, sign, and discarded digits
4175
increment=0; // bumper
4176
{modes:do{/*select*/
4177  if (mode==ROUND_HALF_UP)
4178   { // default first [most common]
4179
if (first>=5)
4180     increment=sign;
4181   }
4182  else if (mode==ROUND_UNNECESSARY)
4183   { // default for setScale()
4184
// discarding any non-zero digits is an error
4185
if ((!(allzero(oldmant,len))))
4186     throw new java.lang.ArithmeticException JavaDoc("Rounding necessary");
4187   }
4188  else if (mode==ROUND_HALF_DOWN)
4189   { // 0.5000 goes down
4190
if (first>5)
4191     increment=sign;
4192    else
4193     if (first==5)
4194      if ((!(allzero(oldmant,len+1))))
4195       increment=sign;
4196   }
4197  else if (mode==ROUND_HALF_EVEN)
4198   { // 0.5000 goes down if left digit even
4199
if (first>5)
4200     increment=sign;
4201    else
4202     if (first==5)
4203      {
4204       if ((!(allzero(oldmant,len+1))))
4205        increment=sign;
4206       else /* 0.5000 */
4207        if ((((mant[mant.length-1])%2))==1)
4208         increment=sign;
4209      }
4210   }
4211  else if (mode==ROUND_DOWN){
4212   // never increment
4213
}else if (mode==ROUND_UP)
4214   { // increment if discarded non-zero
4215
if ((!(allzero(oldmant,len))))
4216     increment=sign;
4217   }
4218  else if (mode==ROUND_CEILING)
4219   { // more positive
4220
if (sign>0)
4221     if ((!(allzero(oldmant,len))))
4222      increment=sign;
4223   }
4224  else if (mode==ROUND_FLOOR)
4225   { // more negative
4226
if (sign<0)
4227     if ((!(allzero(oldmant,len))))
4228      increment=sign;
4229   }
4230  else{
4231   throw new java.lang.IllegalArgumentException JavaDoc("Bad round value:"+" "+mode);
4232  }
4233  }while(false);}/*modes*/
4234  
4235  if (increment!=0)
4236   {bump:do{
4237    if (ind==iszero)
4238     {
4239      // we must not subtract from 0, but result is trivial anyway
4240
mant=ONE.mant;
4241      ind=(byte)increment;
4242     }
4243    else
4244     {
4245      // mantissa is non-0; we can safely add or subtract 1
4246
if (ind==isneg)
4247       increment=(int)-increment;
4248      newmant=byteaddsub(mant,mant.length,ONE.mant,1,increment,reuse);
4249      if (newmant.length>mant.length)
4250       { // had a carry
4251
// drop rightmost digit and raise exponent
4252
exp++;
4253        // mant is already the correct length
4254
java.lang.System.arraycopy((java.lang.Object JavaDoc)newmant,0,(java.lang.Object JavaDoc)mant,0,mant.length);
4255       }
4256      else
4257       mant=newmant;
4258     }
4259   }while(false);}/*bump*/
4260  // rounding can increase exponent significantly
4261
if (exp>MaxExp)
4262   throw new java.lang.ArithmeticException JavaDoc("Exponent Overflow:"+" "+exp);
4263  return this;
4264  }
4265
4266 /* <sgml> Test if rightmost digits are all 0.
4267    Arg1 is a mantissa array to test
4268    Arg2 is the offset of first digit to check
4269            [may be negative; if so, digits to left are 0's]
4270    returns 1 if all the digits starting at Arg2 are 0
4271 
4272    Arg2 may be beyond array bounds, in which case 1 is returned
4273    </sgml> */

4274 
4275 private static final boolean allzero(byte array[],int start){
4276  int i=0;
4277  if (start<0)
4278   start=0;
4279  {int $25=array.length-1;i=start;i:for(;i<=$25;i++){
4280   if (array[i]!=0)
4281    return false;
4282   }
4283  }/*i*/
4284  return true;
4285  }
4286
4287 /* <sgml> Carry out final checks and canonicalization
4288    <p>
4289    This finishes off the current number by:
4290      1. Rounding if necessary (NB: length includes leading zeros)
4291      2. Stripping trailing zeros (if requested and \PLAIN)
4292      3. Stripping leading zeros (always)
4293      4. Selecting exponential notation (if required)
4294      5. Converting a zero result to just '0' (if \PLAIN)
4295    In practice, these operations overlap and share code.
4296    It always sets form.
4297    </sgml>
4298    Arg1 is requested MathContext (length to round to, trigger, and FORM)
4299    Arg2 is 1 if trailing insignificant zeros should be removed after
4300         round (for division, etc.), provided that set.form isn't PLAIN.
4301   returns this, for convenience
4302   */

4303 
4304 private com.ibm.icu.math.BigDecimal finish(com.ibm.icu.math.MathContext set,boolean strip){
4305  int d=0;
4306  int i=0;
4307  byte newmant[]=null;
4308  int mag=0;
4309  int sig=0;
4310  /* Round if mantissa too long and digits requested */
4311  if (set.digits!=0)
4312   if (this.mant.length>set.digits)
4313    this.round(set);
4314  
4315  /* If strip requested (and standard formatting), remove
4316     insignificant trailing zeros. */

4317  if (strip)
4318   if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
4319    {
4320     d=this.mant.length;
4321     /* see if we need to drop any trailing zeros */
4322     {i=d-1;i:for(;i>=1;i--){
4323      if (this.mant[i]!=0)
4324       break i;
4325      d--;
4326      exp++;
4327      }
4328     }/*i*/
4329     if (d<this.mant.length)
4330      {/* need to reduce */
4331       newmant=new byte[d];
4332       java.lang.System.arraycopy((java.lang.Object JavaDoc)this.mant,0,(java.lang.Object JavaDoc)newmant,0,d);
4333       this.mant=newmant;
4334      }
4335    }
4336  
4337  form=(byte)com.ibm.icu.math.MathContext.PLAIN; // preset
4338

4339  /* Now check for leading- and all- zeros in mantissa */
4340  {int $26=this.mant.length;i=0;i:for(;$26>0;$26--,i++){
4341   if (this.mant[i]!=0)
4342    {
4343     // non-0 result; ind will be correct
4344
// remove leading zeros [e.g., after subtract]
4345
if (i>0)
4346      {delead:do{
4347       newmant=new byte[this.mant.length-i];
4348       java.lang.System.arraycopy((java.lang.Object JavaDoc)this.mant,i,(java.lang.Object JavaDoc)newmant,0,this.mant.length-i);
4349       this.mant=newmant;
4350      }while(false);}/*delead*/
4351     // now determine form if not PLAIN
4352
mag=exp+mant.length;
4353     if (mag>0)
4354      { // most common path
4355
if (mag>set.digits)
4356        if (set.digits!=0)
4357         form=(byte)set.form;
4358       if ((mag-1)<=MaxExp)
4359        return this; // no overflow; quick return
4360
}
4361     else
4362      if (mag<(-5))
4363       form=(byte)set.form;
4364     /* check for overflow */
4365     mag--;
4366     if ((mag<MinExp)|(mag>MaxExp))
4367      {overflow:do{
4368       // possible reprieve if form is engineering
4369
if (form==com.ibm.icu.math.MathContext.ENGINEERING)
4370        {
4371         sig=mag%3; // leftover
4372
if (sig<0)
4373          sig=3+sig; // negative exponent
4374
mag=mag-sig; // exponent to use
4375
// 1999.06.29: second test here must be MaxExp
4376
if (mag>=MinExp)
4377          if (mag<=MaxExp)
4378           break overflow;
4379        }
4380       throw new java.lang.ArithmeticException JavaDoc("Exponent Overflow:"+" "+mag);
4381      }while(false);}/*overflow*/
4382     return this;
4383    }
4384   }
4385  }/*i*/
4386  
4387  // Drop through to here only if mantissa is all zeros
4388
ind=iszero;
4389  {/*select*/
4390  if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
4391   exp=0; // standard result; go to '0'
4392
else if (exp>0)
4393   exp=0; // +ve exponent also goes to '0'
4394
else{
4395   // a plain number with -ve exponent; preserve and check exponent
4396
if (exp<MinExp)
4397    throw new java.lang.ArithmeticException JavaDoc("Exponent Overflow:"+" "+exp);
4398  }
4399  }
4400  mant=ZERO.mant; // canonical mantissa
4401
return this;
4402  }
4403 }
4404
Popular Tags