]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_2_1-src/src/com/ibm/icu/math/BigDecimal.java
go
[Dictionary.git] / jars / icu4j-4_2_1-src / src / com / ibm / icu / math / BigDecimal.java
1 //##header J2SE15
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;
6 import com.ibm.icu.impl.Utility;
7 import com.ibm.icu.lang.UCharacter;
8
9 /* ------------------------------------------------------------------ */
10 /* BigDecimal -- Decimal arithmetic for Java                          */
11 /* ------------------------------------------------------------------ */
12 /* Copyright IBM Corporation, 1996-2009.  All Rights Reserved.       */
13 /*                                                                    */
14 /* The BigDecimal class provides immutable arbitrary-precision        */
15 /* floating point (including integer) decimal numbers.                */
16 /*                                                                    */
17 /* As the numbers are decimal, there is an exact correspondence       */
18 /* between an instance of a BigDecimal object and its String          */
19 /* representation; the BigDecimal class provides direct conversions   */
20 /* to and from String and character array objects, and well as        */
21 /* conversions to and from the Java primitive types (which may not    */
22 /* be exact).                                                         */
23 /* ------------------------------------------------------------------ */
24 /* Notes:                                                             */
25 /*                                                                    */
26 /* 1. A BigDecimal object is never changed in value once constructed; */
27 /*    this avoids the need for locking.  Note in particular that the  */
28 /*    mantissa array may be shared between many BigDecimal objects,   */
29 /*    so that once exposed it must not be altered.                    */
30 /*                                                                    */
31 /* 2. This class looks at MathContext class fields directly (for      */
32 /*    performance).  It must not and does not change them.            */
33 /*                                                                    */
34 /* 3. Exponent checking is delayed until finish(), as we know         */
35 /*    intermediate calculations cannot cause 31-bit overflow.         */
36 /*    [This assertion depends on MAX_DIGITS in MathContext.]          */
37 /*                                                                    */
38 /* 4. Comments for the public API now follow the javadoc conventions. */
39 /*    The NetRexx -comments option is used to pass these comments     */
40 /*    through to the generated Java code (with -format, if desired).  */
41 /*                                                                    */
42 /* 5. System.arraycopy is faster than explicit loop as follows        */
43 /*      Mean length 4:  equal                                         */
44 /*      Mean length 8:  x2                                            */
45 /*      Mean length 16: x3                                            */
46 /*      Mean length 24: x4                                            */
47 /*    From prior experience, we expect mean length a little below 8,  */
48 /*    but arraycopy is still the one to use, in general, until later  */
49 /*    measurements suggest otherwise.                                 */
50 /*                                                                    */
51 /* 6. 'DMSRCN' referred to below is the original (1981) IBM S/370     */
52 /*    assembler code implementation of the algorithms below; it is    */
53 /*    now called IXXRCN and is available with the OS/390 and VM/ESA   */
54 /*    operating systems.                                              */
55 /* ------------------------------------------------------------------ */
56 /* Change History:                                                    */
57 /* 1997.09.02 Initial version (derived from netrexx.lang classes)     */
58 /* 1997.09.12 Add lostDigits checking                                 */
59 /* 1997.10.06 Change mantissa to a byte array                         */
60 /* 1997.11.22 Rework power [did not prepare arguments, etc.]          */
61 /* 1997.12.13 multiply did not prepare arguments                      */
62 /* 1997.12.14 add did not prepare and align arguments correctly       */
63 /* 1998.05.02 0.07 packaging changes suggested by Sun and Oracle      */
64 /* 1998.05.21 adjust remainder operator finalization                  */
65 /* 1998.06.04 rework to pass MathContext to finish() and round()      */
66 /* 1998.06.06 change format to use round(); support rounding modes    */
67 /* 1998.06.25 rename to BigDecimal and begin merge                    */
68 /*            zero can now have trailing zeros (i.e., exp\=0)         */
69 /* 1998.06.28 new methods: movePointXxxx, scale, toBigInteger         */
70 /*                         unscaledValue, valueof                     */
71 /* 1998.07.01 improve byteaddsub to allow array reuse, etc.           */
72 /* 1998.07.01 make null testing explicit to avoid JIT bug [Win32]     */
73 /* 1998.07.07 scaled division  [divide(BigDecimal, int, int)]         */
74 /* 1998.07.08 setScale, faster equals                                 */
75 /* 1998.07.11 allow 1E6 (no sign) <sigh>; new double/float conversion */
76 /* 1998.10.12 change package to com.ibm.icu.math                          */
77 /* 1998.12.14 power operator no longer rounds RHS [to match ANSI]     */
78 /*            add toBigDecimal() and BigDecimal(java.math.BigDecimal) */
79 /* 1998.12.29 improve byteaddsub by using table lookup                */
80 /* 1999.02.04 lostdigits=0 behaviour rounds instead of digits+1 guard */
81 /* 1999.02.05 cleaner code for BigDecimal(char[])                     */
82 /* 1999.02.06 add javadoc comments                                    */
83 /* 1999.02.11 format() changed from 7 to 2 method form                */
84 /* 1999.03.05 null pointer checking is no longer explicit             */
85 /* 1999.03.05 simplify; changes from discussion with J. Bloch:        */
86 /*            null no longer permitted for MathContext; drop boolean, */
87 /*            byte, char, float, short constructor, deprecate double  */
88 /*            constructor, no blanks in string constructor, add       */
89 /*            offset and length version of char[] constructor;        */
90 /*            add valueOf(double); drop booleanValue, charValue;      */
91 /*            add ...Exact versions of remaining convertors           */
92 /* 1999.03.13 add toBigIntegerExact                                   */
93 /* 1999.03.13 1.00 release to IBM Centre for Java Technology          */
94 /* 1999.05.27 1.01 correct 0-0.2 bug under scaled arithmetic          */
95 /* 1999.06.29 1.02 constructors should not allow exponent > 9 digits  */
96 /* 1999.07.03 1.03 lost digits should not be checked if digits=0      */
97 /* 1999.07.06      lost digits Exception message changed              */
98 /* 1999.07.10 1.04 more work on 0-0.2 (scaled arithmetic)             */
99 /* 1999.07.17      improve messages from pow method                   */
100 /* 1999.08.08      performance tweaks                                 */
101 /* 1999.08.15      fastpath in multiply                               */
102 /* 1999.11.05 1.05 fix problem in intValueExact [e.g., 5555555555]    */
103 /* 1999.12.22 1.06 remove multiply fastpath, and improve performance  */
104 /* 2000.01.01      copyright update [Y2K has arrived]                 */
105 /* 2000.06.18 1.08 no longer deprecate BigDecimal(double)             */
106 /* ------------------------------------------------------------------ */
107
108
109
110
111
112 /**
113  * The <code>BigDecimal</code> class implements immutable
114  * arbitrary-precision decimal numbers.  The methods of the
115  * <code>BigDecimal</code> class provide operations for fixed and
116  * floating point arithmetic, comparison, format conversions, and
117  * hashing.
118  * <p>
119  * As the numbers are decimal, there is an exact correspondence between
120  * an instance of a <code>BigDecimal</code> object and its
121  * <code>String</code> representation; the <code>BigDecimal</code> class
122  * provides direct conversions to and from <code>String</code> and
123  * character array (<code>char[]</code>) objects, as well as conversions
124  * to and from the Java primitive types (which may not be exact) and
125  * <code>BigInteger</code>.
126  * <p>
127  * In the descriptions of constructors and methods in this documentation,
128  * the value of a <code>BigDecimal</code> number object is shown as the
129  * result of invoking the <code>toString()</code> method on the object.
130  * The internal representation of a decimal number is neither defined
131  * nor exposed, and is not permitted to affect the result of any
132  * operation.
133  * <p>
134  * The floating point arithmetic provided by this class is defined by
135  * the ANSI X3.274-1996 standard, and is also documented at
136  * <code>http://www2.hursley.ibm.com/decimal</code>
137  * <br><i>[This URL will change.]</i>
138  *
139  * <h3>Operator methods</h3>
140  * <p>
141  * Operations on <code>BigDecimal</code> numbers are controlled by a
142  * {@link MathContext} object, which provides the context (precision and
143  * other information) for the operation. Methods that can take a
144  * <code>MathContext</code> parameter implement the standard arithmetic
145  * operators for <code>BigDecimal</code> objects and are known as
146  * <i>operator methods</i>.  The default settings provided by the
147  * constant {@link MathContext#DEFAULT} (<code>digits=9,
148  * form=SCIENTIFIC, lostDigits=false, roundingMode=ROUND_HALF_UP</code>)
149  * perform general-purpose floating point arithmetic to nine digits of
150  * precision.  The <code>MathContext</code> parameter must not be
151  * <code>null</code>.
152  * <p>
153  * Each operator method also has a version provided which does
154  * not take a <code>MathContext</code> parameter.  For this version of
155  * each method, the context settings used are <code>digits=0,
156  * form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP</code>;
157  * these settings perform fixed point arithmetic with unlimited
158  * precision, as defined for the original BigDecimal class in Java 1.1
159  * and Java 1.2.
160  * <p>
161  * For monadic operators, only the optional <code>MathContext</code>
162  * parameter is present; the operation acts upon the current object.
163  * <p>
164  * For dyadic operators, a <code>BigDecimal</code> parameter is always
165  * present; it must not be <code>null</code>.
166  * The operation acts with the current object being the left-hand operand
167  * and the <code>BigDecimal</code> parameter being the right-hand operand.
168  * <p>
169  * For example, adding two <code>BigDecimal</code> objects referred to
170  * by the names <code>award</code> and <code>extra</code> could be
171  * written as any of:
172  * <p><code>
173  *     award.add(extra)
174  * <br>award.add(extra, MathContext.DEFAULT)
175  * <br>award.add(extra, acontext)
176  * </code>
177  * <p>
178  * (where <code>acontext</code> is a <code>MathContext</code> object),
179  * which would return a <code>BigDecimal</code> object whose value is
180  * the result of adding <code>award</code> and <code>extra</code> under
181  * the appropriate context settings.
182  * <p>
183  * When a <code>BigDecimal</code> operator method is used, a set of
184  * rules define what the result will be (and, by implication, how the
185  * result would be represented as a character string).
186  * These rules are defined in the BigDecimal arithmetic documentation
187  * (see the URL above), but in summary:
188  * <ul>
189  * <li>Results are normally calculated with up to some maximum number of
190  * significant digits.
191  * For example, if the <code>MathContext</code> parameter for an operation
192  * were <code>MathContext.DEFAULT</code> then the result would be
193  * rounded to 9 digits; the division of 2 by 3 would then result in
194  * 0.666666667.
195  * <br>
196  * You can change the default of 9 significant digits by providing the
197  * method with a suitable <code>MathContext</code> object. This lets you
198  * calculate using as many digits as you need -- thousands, if necessary.
199  * Fixed point (scaled) arithmetic is indicated by using a
200  * <code>digits</code> setting of 0 (or omitting the
201  * <code>MathContext</code> parameter).
202  * <br>
203  * Similarly, you can change the algorithm used for rounding from the
204  * default "classic" algorithm.
205  * <li>
206  * In standard arithmetic (that is, when the <code>form</code> setting
207  * is not <code>PLAIN</code>), a zero result is always expressed as the
208  * single digit <code>'0'</code> (that is, with no sign, decimal point,
209  * or exponent part).
210  * <li>
211  * Except for the division and power operators in standard arithmetic,
212  * trailing zeros are preserved (this is in contrast to binary floating
213  * point operations and most electronic calculators, which lose the
214  * information about trailing zeros in the fractional part of results).
215  * <br>
216  * So, for example:
217  * <p><code>
218  *     new BigDecimal("2.40").add(     new BigDecimal("2"))      =&gt; "4.40"
219  * <br>new BigDecimal("2.40").subtract(new BigDecimal("2"))      =&gt; "0.40"
220  * <br>new BigDecimal("2.40").multiply(new BigDecimal("2"))      =&gt; "4.80"
221  * <br>new BigDecimal("2.40").divide(  new BigDecimal("2"), def) =&gt; "1.2"
222  * </code>
223  * <p>where the value on the right of the <code>=&gt;</code> would be the
224  * result of the operation, expressed as a <code>String</code>, and
225  * <code>def</code> (in this and following examples) refers to
226  * <code>MathContext.DEFAULT</code>).
227  * This preservation of trailing zeros is desirable for most
228  * calculations (including financial calculations).
229  * If necessary, trailing zeros may be easily removed using division by 1.
230  * <li>
231  * In standard arithmetic, exponential form is used for a result
232  * depending on its value and the current setting of <code>digits</code>
233  * (the default is 9 digits).
234  * If the number of places needed before the decimal point exceeds the
235  * <code>digits</code> setting, or the absolute value of the number is
236  * less than <code>0.000001</code>, then the number will be expressed in
237  * exponential notation; thus
238  * <p><code>
239  *   new BigDecimal("1e+6").multiply(new BigDecimal("1e+6"), def)
240  * </code>
241  * <p>results in <code>1E+12</code> instead of
242  * <code>1000000000000</code>, and
243  * <p><code>
244  *   new BigDecimal("1").divide(new BigDecimal("3E+10"), def)
245  * </code>
246  * <p>results in <code>3.33333333E-11</code> instead of
247  * <code>0.0000000000333333333</code>.
248  * <p>
249  * The form of the exponential notation (scientific or engineering) is
250  * determined by the <code>form</code> setting.
251  * <eul>
252  * <p>
253  * The names of methods in this class follow the conventions established
254  * by <code>java.lang.Number</code>, <code>java.math.BigInteger</code>,
255  * and <code>java.math.BigDecimal</code> in Java 1.1 and Java 1.2.
256  *
257  * @see     MathContext
258  * @author  Mike Cowlishaw
259  * @stable ICU 2.0
260  */
261
262 public class BigDecimal extends java.lang.Number implements java.io.Serializable,java.lang.Comparable{
263  //private static final java.lang.String $0="BigDecimal.nrx";
264  
265  
266  
267  /* ----- Constants ----- */
268  /* properties constant public */ // useful to others
269  /**
270   * The <code>BigDecimal</code> constant "0".
271   *
272   * @see #ONE
273   * @see #TEN
274   * @stable ICU 2.0
275   */
276  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
277  // .. to be able to use this, for speed
278  
279  /**
280   * The <code>BigDecimal</code> constant "1".
281   *
282   * @see #TEN
283   * @see #ZERO
284   * @stable ICU 2.0
285   */
286  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
287  // .. to be able to use this, for speed
288  
289  /**
290   * The <code>BigDecimal</code> constant "10".
291   *
292   * @see #ONE
293   * @see #ZERO
294   * @stable ICU 2.0
295   */
296  public static final com.ibm.icu.math.BigDecimal TEN=new com.ibm.icu.math.BigDecimal(10);
297  
298  // the rounding modes (copied here for upwards compatibility)
299  /**
300   * Rounding mode to round to a more positive number.
301   * @see MathContext#ROUND_CEILING
302   * @stable ICU 2.0
303   */
304  public static final int ROUND_CEILING=com.ibm.icu.math.MathContext.ROUND_CEILING;
305  
306  /**
307   * Rounding mode to round towards zero.
308   * @see MathContext#ROUND_DOWN
309   * @stable ICU 2.0
310   */
311  public static final int ROUND_DOWN=com.ibm.icu.math.MathContext.ROUND_DOWN;
312  
313  /**
314   * Rounding mode to round to a more negative number.
315   * @see MathContext#ROUND_FLOOR
316   * @stable ICU 2.0
317   */
318  public static final int ROUND_FLOOR=com.ibm.icu.math.MathContext.ROUND_FLOOR;
319  
320  /**
321   * Rounding mode to round to nearest neighbor, where an equidistant
322   * value is rounded down.
323   * @see MathContext#ROUND_HALF_DOWN
324   * @stable ICU 2.0
325   */
326  public static final int ROUND_HALF_DOWN=com.ibm.icu.math.MathContext.ROUND_HALF_DOWN;
327  
328  /**
329   * Rounding mode to round to nearest neighbor, where an equidistant
330   * value is rounded to the nearest even neighbor.
331   * @see MathContext#ROUND_HALF_EVEN
332   * @stable ICU 2.0
333   */
334  public static final int ROUND_HALF_EVEN=com.ibm.icu.math.MathContext.ROUND_HALF_EVEN;
335  
336  /**
337   * Rounding mode to round to nearest neighbor, where an equidistant
338   * value is rounded up.
339   * @see MathContext#ROUND_HALF_UP
340   * @stable ICU 2.0
341   */
342  public static final int ROUND_HALF_UP=com.ibm.icu.math.MathContext.ROUND_HALF_UP;
343  
344  /**
345   * Rounding mode to assert that no rounding is necessary.
346   * @see MathContext#ROUND_UNNECESSARY
347   * @stable ICU 2.0
348   */
349  public static final int ROUND_UNNECESSARY=com.ibm.icu.math.MathContext.ROUND_UNNECESSARY;
350  
351  /**
352   * Rounding mode to round away from zero.
353   * @see MathContext#ROUND_UP
354   * @stable ICU 2.0
355   */
356  public static final int ROUND_UP=com.ibm.icu.math.MathContext.ROUND_UP;
357  
358  /* properties constant private */ // locals
359  private static final byte ispos=1; // ind: indicates positive (must be 1)
360  private static final byte iszero=0; // ind: indicates zero     (must be 0)
361  private static final byte isneg=-1; // ind: indicates negative (must be -1)
362  // [later could add NaN, +/- infinity, here]
363  
364  private static final int MinExp=-999999999; // minimum exponent allowed
365  private static final int MaxExp=999999999; // maximum exponent allowed
366  private static final int MinArg=-999999999; // minimum argument integer
367  private static final int MaxArg=999999999; // maximum argument integer
368  
369  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
370  
371  /* properties constant private unused */ // present but not referenced
372  
373  // Serialization version
374  private static final long serialVersionUID=8245355804974198832L;
375  
376  //private static final java.lang.String copyright=" Copyright (c) IBM Corporation 1996, 2000.  All rights reserved. ";
377  
378  /* properties static private */
379  // Precalculated constant arrays (used by byteaddsub)
380  private static byte bytecar[]=new byte[(90+99)+1]; // carry/borrow array
381  private static byte bytedig[]=diginit(); // next digit array
382  
383  /* ----- Instance properties [all private and immutable] ----- */
384  /* properties private */
385  
386  /**
387   * The indicator. This may take the values:
388   * <ul>
389   * <li>ispos  -- the number is positive
390   * <li>iszero -- the number is zero
391   * <li>isneg  -- the number is negative
392   * </ul>
393   *
394   * @serial
395   */
396  private byte ind; // assumed undefined
397  // Note: some code below assumes IND = Sign [-1, 0, 1], at present.
398  // We only need two bits for this, but use a byte [also permits
399  // smooth future extension].
400  
401  /**
402   * The formatting style. This may take the values:
403   * <ul>
404   * <li>MathContext.PLAIN        -- no exponent needed
405   * <li>MathContext.SCIENTIFIC   -- scientific notation required
406   * <li>MathContext.ENGINEERING  -- engineering notation required
407   * </ul>
408   * <p>
409   * This property is an optimization; it allows us to defer number
410   * layout until it is actually needed as a string, hence avoiding
411   * unnecessary formatting.
412   *
413   * @serial
414   */
415  private byte form=(byte)com.ibm.icu.math.MathContext.PLAIN; // assumed PLAIN
416  // We only need two bits for this, at present, but use a byte
417  // [again, to allow for smooth future extension]
418  
419  /**
420   * The value of the mantissa.
421   * <p>
422   * Once constructed, this may become shared between several BigDecimal
423   * objects, so must not be altered.
424   * <p>
425   * For efficiency (speed), this is a byte array, with each byte
426   * taking a value of 0 -> 9.
427   * <p>
428   * If the first byte is 0 then the value of the number is zero (and
429   * mant.length=1, except when constructed from a plain number, for
430   * example, 0.000).
431   *
432   * @serial
433   */
434  private byte mant[]; // assumed null
435  
436  /**
437   * The exponent.
438   * <p>
439   * For fixed point arithmetic, scale is <code>-exp</code>, and can
440   * apply to zero.
441   *
442   * Note that this property can have a value less than MinExp when
443   * the mantissa has more than one digit.
444   *
445   * @serial
446   */
447  private int exp;
448  // assumed 0
449  
450  /* ---------------------------------------------------------------- */
451  /* Constructors                                                     */
452  /* ---------------------------------------------------------------- */
453  
454 //#if defined(FOUNDATION10)
455 //#else
456  /**
457   * Constructs a <code>BigDecimal</code> object from a
458   * <code>java.math.BigDecimal</code>.
459   * <p>
460   * Constructs a <code>BigDecimal</code> as though the parameter had
461   * been represented as a <code>String</code> (using its
462   * <code>toString</code> method) and the
463   * {@link #BigDecimal(java.lang.String)} constructor had then been
464   * used.
465   * The parameter must not be <code>null</code>.
466   * <p>
467   * <i>(Note: this constructor is provided only in the
468   * <code>com.ibm.icu.math</code> version of the BigDecimal class.
469   * It would not be present in a <code>java.math</code> version.)</i>
470   *
471   * @param bd The <code>BigDecimal</code> to be translated.
472   * @stable ICU 2.0
473   */
474  
475  public BigDecimal(java.math.BigDecimal bd){
476   this(bd.toString());
477   return;}
478 //#endif
479
480  /**
481   * Constructs a <code>BigDecimal</code> object from a
482   * <code>BigInteger</code>, with scale 0.
483   * <p>
484   * Constructs a <code>BigDecimal</code> which is the exact decimal
485   * representation of the <code>BigInteger</code>, with a scale of
486   * zero.
487   * The value of the <code>BigDecimal</code> is identical to the value
488   * of the <code>BigInteger</code>.
489   * The parameter must not be <code>null</code>.
490   * <p>
491   * The <code>BigDecimal</code> will contain only decimal digits,
492   * prefixed with a leading minus sign (hyphen) if the
493   * <code>BigInteger</code> is negative.  A leading zero will be
494   * present only if the <code>BigInteger</code> is zero.
495   *
496   * @param bi The <code>BigInteger</code> to be converted.
497   * @stable ICU 2.0
498   */
499  
500  public BigDecimal(java.math.BigInteger bi){
501   this(bi.toString(10));
502   return;}
503  // exp remains 0
504  
505  /**
506   * Constructs a <code>BigDecimal</code> object from a
507   * <code>BigInteger</code> and a scale.
508   * <p>
509   * Constructs a <code>BigDecimal</code> which is the exact decimal
510   * representation of the <code>BigInteger</code>, scaled by the
511   * second parameter, which may not be negative.
512   * The value of the <code>BigDecimal</code> is the
513   * <code>BigInteger</code> divided by ten to the power of the scale.
514   * The <code>BigInteger</code> parameter must not be
515   * <code>null</code>.
516   * <p>
517   * The <code>BigDecimal</code> will contain only decimal digits, (with
518   * an embedded decimal point followed by <code>scale</code> decimal
519   * digits if the scale is positive), prefixed with a leading minus
520   * sign (hyphen) if the <code>BigInteger</code> is negative.  A
521   * leading zero will be present only if the <code>BigInteger</code> is
522   * zero.
523   *
524   * @param  bi    The <code>BigInteger</code> to be converted.
525   * @param  scale The <code>int</code> specifying the scale.
526   * @throws NumberFormatException if the scale is negative.
527   * @stable ICU 2.0
528   */
529  
530  public BigDecimal(java.math.BigInteger bi,int scale){
531   this(bi.toString(10));
532   if (scale<0) 
533    throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
534   exp=(int)-scale; // exponent is -scale
535   return;}
536
537  /**
538   * Constructs a <code>BigDecimal</code> object from an array of characters.
539   * <p>
540   * Constructs a <code>BigDecimal</code> as though a
541   * <code>String</code> had been constructed from the character array
542   * and the {@link #BigDecimal(java.lang.String)} constructor had then
543   * been used. The parameter must not be <code>null</code>.
544   * <p>
545   * Using this constructor is faster than using the
546   * <code>BigDecimal(String)</code> constructor if the string is
547   * already available in character array form.
548   *
549   * @param inchars The <code>char[]</code> array containing the number
550   *                to be converted.
551   * @throws NumberFormatException if the parameter is not a valid
552   *                number.
553   * @stable ICU 2.0
554   */
555  
556  public BigDecimal(char inchars[]){
557   this(inchars,0,inchars.length);
558   return;}
559
560  /**
561   * Constructs a <code>BigDecimal</code> object from an array of characters.
562   * <p>
563   * Constructs a <code>BigDecimal</code> as though a
564   * <code>String</code> had been constructed from the character array
565   * (or a subarray of that array) and the
566   * {@link #BigDecimal(java.lang.String)} constructor had then been
567   * used. The first parameter must not be <code>null</code>, and the
568   * subarray must be wholly contained within it.
569   * <p>
570   * Using this constructor is faster than using the
571   * <code>BigDecimal(String)</code> constructor if the string is
572   * already available within a character array.
573   *
574   * @param inchars The <code>char[]</code> array containing the number
575   *                to be converted.
576   * @param offset  The <code>int</code> offset into the array of the
577   *                start of the number to be converted.
578   * @param length  The <code>int</code> length of the number.
579   * @throws NumberFormatException if the parameter is not a valid
580   *                number for any reason.
581   * @stable ICU 2.0
582   */
583  
584  public BigDecimal(char inchars[],int offset,int length){super();
585   boolean exotic;
586   boolean hadexp;
587   int d;
588   int dotoff;
589   int last;
590   int i=0;
591   char si=0;
592   boolean eneg=false;
593   int k=0;
594   int elen=0;
595   int j=0;
596   char sj=0;
597   int dvalue=0;
598   int mag=0;
599   // This is the primary constructor; all incoming strings end up
600   // here; it uses explicit (inline) parsing for speed and to avoid
601   // generating intermediate (temporary) objects of any kind.
602   // 1998.06.25: exponent form built only if E/e in string
603   // 1998.06.25: trailing zeros not removed for zero
604   // 1999.03.06: no embedded blanks; allow offset and length
605   if (length<=0) 
606    bad(inchars); // bad conversion (empty string)
607   // [bad offset will raise array bounds exception]
608   
609   /* Handle and step past sign */
610   ind=ispos; // assume positive
611   if (inchars[offset]==('-')) 
612    {
613     length--;
614     if (length==0) 
615      bad(inchars); // nothing after sign
616     ind=isneg;
617     offset++;
618    }
619   else 
620    if (inchars[offset]==('+')) 
621     {
622      length--;
623      if (length==0) 
624       bad(inchars); // nothing after sign
625      offset++;
626     }
627   
628   /* We're at the start of the number */
629   exotic=false; // have extra digits
630   hadexp=false; // had explicit exponent
631   d=0; // count of digits found
632   dotoff=-1; // offset where dot was found
633   last=-1; // last character of mantissa
634   {int $1=length;i=offset;i:for(;$1>0;$1--,i++){
635    si=inchars[i];
636    if (si>='0')  // test for Arabic digit
637     if (si<='9') 
638      {
639       last=i;
640       d++; // still in mantissa
641       continue i;
642      }
643    if (si=='.') 
644     { // record and ignore
645      if (dotoff>=0) 
646       bad(inchars); // two dots
647      dotoff=i-offset; // offset into mantissa
648      continue i;
649     }
650    if (si!='e') 
651     if (si!='E') 
652      { // expect an extra digit
653       if ((!(UCharacter.isDigit(si)))) 
654        bad(inchars); // not a number
655       // defer the base 10 check until later to avoid extra method call
656       exotic=true; // will need conversion later
657       last=i;
658       d++; // still in mantissa
659       continue i;
660      }
661    /* Found 'e' or 'E' -- now process explicit exponent */
662    // 1998.07.11: sign no longer required
663    if ((i-offset)>(length-2)) 
664     bad(inchars); // no room for even one digit
665    eneg=false;
666    if ((inchars[i+1])==('-')) 
667     {
668      eneg=true;
669      k=i+2;
670     }
671    else 
672     if ((inchars[i+1])==('+')) 
673      k=i+2;
674     else 
675      k=i+1;
676    // k is offset of first expected digit
677    elen=length-((k-offset)); // possible number of digits
678    if ((elen==0)|(elen>9)) 
679     bad(inchars); // 0 or more than 9 digits
680    {int $2=elen;j=k;for(;$2>0;$2--,j++){
681     sj=inchars[j];
682     if (sj<'0') 
683      bad(inchars); // always bad
684     if (sj>'9') 
685      { // maybe an exotic digit
686       if ((!(UCharacter.isDigit(sj)))) 
687        bad(inchars); // not a number
688       dvalue=UCharacter.digit(sj,10); // check base
689       if (dvalue<0) 
690        bad(inchars); // not base 10
691      }
692     else 
693      dvalue=((int)(sj))-((int)('0'));
694     exp=(exp*10)+dvalue;
695     }
696    }/*j*/
697    if (eneg) 
698     exp=(int)-exp; // was negative
699    hadexp=true; // remember we had one
700    break i; // we are done
701    }
702   }/*i*/
703   
704   /* Here when all inspected */
705   if (d==0) 
706    bad(inchars); // no mantissa digits
707   if (dotoff>=0) 
708    exp=(exp+dotoff)-d; // adjust exponent if had dot
709   
710   /* strip leading zeros/dot (leave final if all 0's) */
711   {int $3=last-1;i=offset;i:for(;i<=$3;i++){
712    si=inchars[i];
713    if (si=='0') 
714     {
715      offset++;
716      dotoff--;
717      d--;
718     }
719    else 
720     if (si=='.') 
721      {
722       offset++; // step past dot
723       dotoff--;
724      }
725     else 
726      if (si<='9') 
727       break i;/* non-0 */
728      else 
729       {/* exotic */
730        if ((UCharacter.digit(si,10))!=0) 
731         break i; // non-0 or bad
732        // is 0 .. strip like '0'
733        offset++;
734        dotoff--;
735        d--;
736       }
737    }
738   }/*i*/
739   
740   /* Create the mantissa array */
741   mant=new byte[d]; // we know the length
742   j=offset; // input offset
743   if (exotic) 
744    {do{ // slow: check for exotica
745     {int $4=d;i=0;for(;$4>0;$4--,i++){
746      if (i==dotoff) 
747       j++; // at dot
748      sj=inchars[j];
749      if (sj<='9') 
750       mant[i]=(byte)(((int)(sj))-((int)('0')));/* easy */
751      else 
752       {
753        dvalue=UCharacter.digit(sj,10);
754        if (dvalue<0) 
755         bad(inchars); // not a number after all
756        mant[i]=(byte)dvalue;
757       }
758      j++;
759      }
760     }/*i*/
761    }while(false);}/*exotica*/
762   else 
763    {do{
764     {int $5=d;i=0;for(;$5>0;$5--,i++){
765      if (i==dotoff) 
766       j++;
767      mant[i]=(byte)(((int)(inchars[j]))-((int)('0')));
768      j++;
769      }
770     }/*i*/
771    }while(false);}/*simple*/
772   
773   /* Looks good.  Set the sign indicator and form, as needed. */
774   // Trailing zeros are preserved
775   // The rule here for form is:
776   //   If no E-notation, then request plain notation
777   //   Otherwise act as though add(0,DEFAULT) and request scientific notation
778   // [form is already PLAIN]
779   if (mant[0]==0) 
780    {
781     ind=iszero; // force to show zero
782     // negative exponent is significant (e.g., -3 for 0.000) if plain
783     if (exp>0) 
784      exp=0; // positive exponent can be ignored
785     if (hadexp) 
786      { // zero becomes single digit from add
787       mant=ZERO.mant;
788       exp=0;
789      }
790    }
791   else 
792    { // non-zero
793     // [ind was set earlier]
794     // now determine form
795     if (hadexp) 
796      {
797       form=(byte)com.ibm.icu.math.MathContext.SCIENTIFIC;
798       // 1999.06.29 check for overflow
799       mag=(exp+mant.length)-1; // true exponent in scientific notation
800       if ((mag<MinExp)|(mag>MaxExp)) 
801        bad(inchars);
802      }
803    }
804   // say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] mant.length exp ind form
805   return;
806   }
807
808  /**
809   * Constructs a <code>BigDecimal</code> object directly from a
810   * <code>double</code>.
811   * <p>
812   * Constructs a <code>BigDecimal</code> which is the exact decimal
813   * representation of the 64-bit signed binary floating point
814   * parameter.
815   * <p>
816   * Note that this constructor it an exact conversion; it does not give
817   * the same result as converting <code>num</code> to a
818   * <code>String</code> using the <code>Double.toString()</code> method
819   * and then using the {@link #BigDecimal(java.lang.String)}
820   * constructor.
821   * To get that result, use the static {@link #valueOf(double)}
822   * method to construct a <code>BigDecimal</code> from a
823   * <code>double</code>.
824   *
825   * @param num The <code>double</code> to be converted.
826   * @throws NumberFormatException if the parameter is infinite or
827   *            not a number.
828   * @stable ICU 2.0
829   */
830  
831  public BigDecimal(double num){
832   // 1999.03.06: use exactly the old algorithm
833   // 2000.01.01: note that this constructor does give an exact result,
834   //             so perhaps it should not be deprecated
835   // 2000.06.18: no longer deprecated
836 //#if defined(FOUNDATION10)
837 //##    this(String.valueOf(num));
838 //#else
839   this((new java.math.BigDecimal(num)).toString());
840 //#endif
841   return;}
842  /**
843   * Constructs a <code>BigDecimal</code> object directly from a
844   * <code>int</code>.
845   * <p>
846   * Constructs a <code>BigDecimal</code> which is the exact decimal
847   * representation of the 32-bit signed binary integer parameter.
848   * The <code>BigDecimal</code> will contain only decimal digits,
849   * prefixed with a leading minus sign (hyphen) if the parameter is
850   * negative.
851   * A leading zero will be present only if the parameter is zero.
852   *
853   * @param num The <code>int</code> to be converted.
854   * @stable ICU 2.0
855   */
856  
857  public BigDecimal(int num){super();
858   int mun;
859   int i=0;
860   // We fastpath commoners
861   if (num<=9) 
862    if (num>=(-9)) 
863     {do{
864      // very common single digit case
865      {/*select*/
866      if (num==0)
867       {
868        mant=ZERO.mant;
869        ind=iszero;
870       }
871      else if (num==1)
872       {
873        mant=ONE.mant;
874        ind=ispos;
875       }
876      else if (num==(-1))
877       {
878        mant=ONE.mant;
879        ind=isneg;
880       }
881      else{
882       {
883        mant=new byte[1];
884        if (num>0) 
885         {
886          mant[0]=(byte)num;
887          ind=ispos;
888         }
889        else 
890         { // num<-1
891          mant[0]=(byte)((int)-num);
892          ind=isneg;
893         }
894       }
895      }
896      }
897      return;
898     }while(false);}/*singledigit*/
899   
900   /* We work on negative numbers so we handle the most negative number */
901   if (num>0) 
902    {
903     ind=ispos;
904     num=(int)-num;
905    }
906   else 
907    ind=isneg;/* negative */ // [0 case already handled]
908   // [it is quicker, here, to pre-calculate the length with
909   // one loop, then allocate exactly the right length of byte array,
910   // then re-fill it with another loop]
911   mun=num; // working copy
912   {i=9;i:for(;;i--){
913    mun=mun/10;
914    if (mun==0) 
915     break i;
916    }
917   }/*i*/
918   // i is the position of the leftmost digit placed
919   mant=new byte[10-i];
920   {i=(10-i)-1;i:for(;;i--){
921    mant[i]=(byte)-(((byte)(num%10)));
922    num=num/10;
923    if (num==0) 
924     break i;
925    }
926   }/*i*/
927   return;
928   }
929
930  /**
931   * Constructs a <code>BigDecimal</code> object directly from a
932   * <code>long</code>.
933   * <p>
934   * Constructs a <code>BigDecimal</code> which is the exact decimal
935   * representation of the 64-bit signed binary integer parameter.
936   * The <code>BigDecimal</code> will contain only decimal digits,
937   * prefixed with a leading minus sign (hyphen) if the parameter is
938   * negative.
939   * A leading zero will be present only if the parameter is zero.
940   *
941   * @param num The <code>long</code> to be converted.
942   * @stable ICU 2.0
943   */
944  
945  public BigDecimal(long num){super();
946   long mun;
947   int i=0;
948   // Not really worth fastpathing commoners in this constructor [also,
949   // we use this to construct the static constants].
950   // This is much faster than: this(String.valueOf(num).toCharArray())
951   /* We work on negative num so we handle the most negative number */
952   if (num>0) 
953    {
954     ind=ispos;
955     num=(long)-num;
956    }
957   else 
958    if (num==0) 
959     ind=iszero;
960    else 
961     ind=isneg;/* negative */
962   mun=num;
963   {i=18;i:for(;;i--){
964    mun=mun/10;
965    if (mun==0) 
966     break i;
967    }
968   }/*i*/
969   // i is the position of the leftmost digit placed
970   mant=new byte[19-i];
971   {i=(19-i)-1;i:for(;;i--){
972    mant[i]=(byte)-(((byte)(num%10)));
973    num=num/10;
974    if (num==0) 
975     break i;
976    }
977   }/*i*/
978   return;
979   }
980
981  /**
982   * Constructs a <code>BigDecimal</code> object from a <code>String</code>.
983   * <p>
984   * Constructs a <code>BigDecimal</code> from the parameter, which must
985   * not be <code>null</code> and must represent a valid <i>number</i>,
986   * as described formally in the documentation referred to
987   * {@link BigDecimal above}.
988   * <p>
989   * In summary, numbers in <code>String</code> form must have at least
990   * one digit, may have a leading sign, may have a decimal point, and
991   * exponential notation may be used.  They follow conventional syntax,
992   * and may not contain blanks.
993   * <p>
994   * Some valid strings from which a <code>BigDecimal</code> might
995   * be constructed are:
996   * <pre>
997   *       "0"         -- Zero
998   *      "12"         -- A whole number
999   *     "-76"         -- A signed whole number
1000   *      "12.70"      -- Some decimal places
1001   *     "+0.003"      -- Plus sign is allowed
1002   *      "17."        -- The same as 17
1003   *        ".5"       -- The same as 0.5
1004   *      "4E+9"       -- Exponential notation
1005   *       "0.73e-7"   -- Exponential notation
1006   * </pre>
1007   * <p>
1008   * (Exponential notation means that the number includes an optional
1009   * sign and a power of ten following an '</code>E</code>' that
1010   * indicates how the decimal point will be shifted.  Thus the
1011   * <code>"4E+9"</code> above is just a short way of writing
1012   * <code>4000000000</code>, and the <code>"0.73e-7"</code> is short
1013   * for <code>0.000000073</code>.)
1014   * <p>
1015   * The <code>BigDecimal</code> constructed from the String is in a
1016   * standard form, with no blanks, as though the
1017   * {@link #add(BigDecimal)} method had been used to add zero to the
1018   * number with unlimited precision.
1019   * If the string uses exponential notation (that is, includes an
1020   * <code>e</code> or an <code>E</code>), then the
1021   * <code>BigDecimal</code> number will be expressed in scientific
1022   * notation (where the power of ten is adjusted so there is a single
1023   * non-zero digit to the left of the decimal point); in this case if
1024   * the number is zero then it will be expressed as the single digit 0,
1025   * and if non-zero it will have an exponent unless that exponent would
1026   * be 0.  The exponent must fit in nine digits both before and after it
1027   * is expressed in scientific notation.
1028   * <p>
1029   * Any digits in the parameter must be decimal; that is,
1030   * <code>Character.digit(c, 10)</code> (where </code>c</code> is the
1031   * character in question) would not return -1.
1032   *
1033   * @param string The <code>String</code> to be converted.
1034   * @throws NumberFormatException if the parameter is not a valid
1035   * number.
1036   * @stable ICU 2.0
1037   */
1038  
1039  public BigDecimal(java.lang.String string){
1040   this(string.toCharArray(),0,string.length());
1041   return;}
1042
1043  /* <sgml> Make a default BigDecimal object for local use. </sgml> */
1044  
1045  private BigDecimal(){super();
1046   return;
1047   }
1048
1049  /* ---------------------------------------------------------------- */
1050  /* Operator methods [methods which take a context parameter]        */
1051  /* ---------------------------------------------------------------- */
1052  
1053  /**
1054   * Returns a plain <code>BigDecimal</code> whose value is the absolute
1055   * value of this <code>BigDecimal</code>.
1056   * <p>
1057   * The same as {@link #abs(MathContext)}, where the context is
1058   * <code>new MathContext(0, MathContext.PLAIN)</code>.
1059   * <p>
1060   * The length of the decimal part (the scale) of the result will
1061   * be <code>this.scale()</code>
1062   *
1063   * @return A <code>BigDecimal</code> whose value is the absolute
1064   *         value of this <code>BigDecimal</code>.
1065   * @stable ICU 2.0
1066   */
1067  
1068  public com.ibm.icu.math.BigDecimal abs(){
1069   return this.abs(plainMC);
1070   }
1071
1072  /**
1073   * Returns a <code>BigDecimal</code> whose value is the absolute value
1074   * of this <code>BigDecimal</code>.
1075   * <p>
1076   * If the current object is zero or positive, then the same result as
1077   * invoking the {@link #plus(MathContext)} method with the same
1078   * parameter is returned.
1079   * Otherwise, the same result as invoking the
1080   * {@link #negate(MathContext)} method with the same parameter is
1081   * returned.
1082   *
1083   * @param  set The <code>MathContext</code> arithmetic settings.
1084   * @return     A <code>BigDecimal</code> whose value is the absolute
1085   *             value of this <code>BigDecimal</code>.
1086   * @stable ICU 2.0
1087   */
1088  
1089  public com.ibm.icu.math.BigDecimal abs(com.ibm.icu.math.MathContext set){
1090   if (this.ind==isneg) 
1091    return this.negate(set);
1092   return this.plus(set);
1093   }
1094
1095  /**
1096   * Returns a plain <code>BigDecimal</code> whose value is
1097   * <code>this+rhs</code>, using fixed point arithmetic.
1098   * <p>
1099   * The same as {@link #add(BigDecimal, MathContext)},
1100   * where the <code>BigDecimal</code> is <code>rhs</code>,
1101   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1102   * <p>
1103   * The length of the decimal part (the scale) of the result will be
1104   * the maximum of the scales of the two operands.
1105   *
1106   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1107   *             the addition.
1108   * @return     A <code>BigDecimal</code> whose value is
1109   *             <code>this+rhs</code>, using fixed point arithmetic.
1110   * @stable ICU 2.0
1111   */
1112  
1113  public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs){
1114   return this.add(rhs,plainMC);
1115   }
1116
1117  /**
1118   * Returns a <code>BigDecimal</code> whose value is <code>this+rhs</code>.
1119   * <p>
1120   * Implements the addition (<b><code>+</code></b>) operator
1121   * (as defined in the decimal documentation, see {@link BigDecimal
1122   * class header}),
1123   * and returns the result as a <code>BigDecimal</code> object.
1124   *
1125   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1126   *             the addition.
1127   * @param  set The <code>MathContext</code> arithmetic settings.
1128   * @return     A <code>BigDecimal</code> whose value is
1129   *             <code>this+rhs</code>.
1130   * @stable ICU 2.0
1131   */
1132  
1133  public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1134   com.ibm.icu.math.BigDecimal lhs;
1135   int reqdig;
1136   com.ibm.icu.math.BigDecimal res;
1137   byte usel[];
1138   int usellen;
1139   byte user[];
1140   int userlen;
1141   int newlen=0;
1142   int tlen=0;
1143   int mult=0;
1144   byte t[]=null;
1145   int ia=0;
1146   int ib=0;
1147   int ea=0;
1148   int eb=0;
1149   byte ca=0;
1150   byte cb=0;
1151   /* determine requested digits and form */
1152   if (set.lostDigits) 
1153    checkdigits(rhs,set.digits);
1154   lhs=this; // name for clarity and proxy
1155   
1156   /* Quick exit for add floating 0 */
1157   // plus() will optimize to return same object if possible
1158   if (lhs.ind==0) 
1159    if (set.form!=com.ibm.icu.math.MathContext.PLAIN) 
1160     return rhs.plus(set);
1161   if (rhs.ind==0) 
1162    if (set.form!=com.ibm.icu.math.MathContext.PLAIN) 
1163     return lhs.plus(set);
1164   
1165   /* Prepare numbers (round, unless unlimited precision) */
1166   reqdig=set.digits; // local copy (heavily used)
1167   if (reqdig>0) 
1168    {
1169     if (lhs.mant.length>reqdig) 
1170      lhs=clone(lhs).round(set);
1171     if (rhs.mant.length>reqdig) 
1172      rhs=clone(rhs).round(set);
1173    // [we could reuse the new LHS for result in this case]
1174    }
1175   
1176   res=new com.ibm.icu.math.BigDecimal(); // build result here
1177   
1178   /* Now see how much we have to pad or truncate lhs or rhs in order
1179      to align the numbers.  If one number is much larger than the
1180      other, then the smaller cannot affect the answer [but we may
1181      still need to pad with up to DIGITS trailing zeros]. */
1182   // Note sign may be 0 if digits (reqdig) is 0
1183   // usel and user will be the byte arrays passed to the adder; we'll
1184   // use them on all paths except quick exits
1185   usel=lhs.mant;
1186   usellen=lhs.mant.length;
1187   user=rhs.mant;
1188   userlen=rhs.mant.length;
1189   {do{/*select*/
1190   if (lhs.exp==rhs.exp)
1191    {/* no padding needed */
1192     // This is the most common, and fastest, path
1193     res.exp=lhs.exp;
1194    }
1195   else if (lhs.exp>rhs.exp)
1196    { // need to pad lhs and/or truncate rhs
1197     newlen=(usellen+lhs.exp)-rhs.exp;
1198     /* If, after pad, lhs would be longer than rhs by digits+1 or
1199        more (and digits>0) then rhs cannot affect answer, so we only
1200        need to pad up to a length of DIGITS+1. */
1201     if (newlen>=((userlen+reqdig)+1)) 
1202      if (reqdig>0) 
1203       {
1204        // LHS is sufficient
1205        res.mant=usel;
1206        res.exp=lhs.exp;
1207        res.ind=lhs.ind;
1208        if (usellen<reqdig) 
1209         { // need 0 padding
1210          res.mant=extend(lhs.mant,reqdig);
1211          res.exp=res.exp-((reqdig-usellen));
1212         }
1213        return res.finish(set,false);
1214       }
1215     // RHS may affect result
1216     res.exp=rhs.exp; // expected final exponent
1217     if (newlen>(reqdig+1)) 
1218      if (reqdig>0) 
1219       {
1220        // LHS will be max; RHS truncated
1221        tlen=(newlen-reqdig)-1; // truncation length
1222        userlen=userlen-tlen;
1223        res.exp=res.exp+tlen;
1224        newlen=reqdig+1;
1225       }
1226     if (newlen>usellen) 
1227      usellen=newlen; // need to pad LHS
1228    }
1229   else{ // need to pad rhs and/or truncate lhs
1230    newlen=(userlen+rhs.exp)-lhs.exp;
1231    if (newlen>=((usellen+reqdig)+1)) 
1232     if (reqdig>0) 
1233      {
1234       // RHS is sufficient
1235       res.mant=user;
1236       res.exp=rhs.exp;
1237       res.ind=rhs.ind;
1238       if (userlen<reqdig) 
1239        { // need 0 padding
1240         res.mant=extend(rhs.mant,reqdig);
1241         res.exp=res.exp-((reqdig-userlen));
1242        }
1243       return res.finish(set,false);
1244      }
1245    // LHS may affect result
1246    res.exp=lhs.exp; // expected final exponent
1247    if (newlen>(reqdig+1)) 
1248     if (reqdig>0) 
1249      {
1250       // RHS will be max; LHS truncated
1251       tlen=(newlen-reqdig)-1; // truncation length
1252       usellen=usellen-tlen;
1253       res.exp=res.exp+tlen;
1254       newlen=reqdig+1;
1255      }
1256    if (newlen>userlen) 
1257     userlen=newlen; // need to pad RHS
1258   }
1259   }while(false);}/*padder*/
1260   
1261   /* OK, we have aligned mantissas.  Now add or subtract. */
1262   // 1998.06.27 Sign may now be 0 [e.g., 0.000] .. treat as positive
1263   // 1999.05.27 Allow for 00 on lhs [is not larger than 2 on rhs]
1264   // 1999.07.10 Allow for 00 on rhs [is not larger than 2 on rhs]
1265   if (lhs.ind==iszero) 
1266    res.ind=ispos;
1267   else 
1268    res.ind=lhs.ind; // likely sign, all paths
1269   if (((lhs.ind==isneg)?1:0)==((rhs.ind==isneg)?1:0))  // same sign, 0 non-negative
1270    mult=1;
1271   else 
1272    {do{ // different signs, so subtraction is needed
1273     mult=-1; // will cause subtract
1274     /* Before we can subtract we must determine which is the larger,
1275        as our add/subtract routine only handles non-negative results
1276        so we may need to swap the operands. */
1277     {do{/*select*/
1278     if (rhs.ind==iszero){
1279      // original A bigger
1280     }else if ((usellen<userlen)|(lhs.ind==iszero))
1281      { // original B bigger
1282       t=usel;
1283       usel=user;
1284       user=t; // swap
1285       tlen=usellen;
1286       usellen=userlen;
1287       userlen=tlen; // ..
1288       res.ind=(byte)-res.ind; // and set sign
1289      }
1290     else if (usellen>userlen){
1291      // original A bigger
1292     }else{
1293      {/* logical lengths the same */ // need compare
1294       /* may still need to swap: compare the strings */
1295       ia=0;
1296       ib=0;
1297       ea=usel.length-1;
1298       eb=user.length-1;
1299       {compare:for(;;){
1300        if (ia<=ea) 
1301         ca=usel[ia];
1302        else 
1303         {
1304          if (ib>eb) 
1305           {/* identical */
1306            if (set.form!=com.ibm.icu.math.MathContext.PLAIN) 
1307             return ZERO;
1308            // [if PLAIN we must do the subtract, in case of 0.000 results]
1309            break compare;
1310           }
1311          ca=(byte)0;
1312         }
1313        if (ib<=eb) 
1314         cb=user[ib];
1315        else 
1316         cb=(byte)0;
1317        if (ca!=cb) 
1318         {
1319          if (ca<cb) 
1320           {/* swap needed */
1321            t=usel;
1322            usel=user;
1323            user=t; // swap
1324            tlen=usellen;
1325            usellen=userlen;
1326            userlen=tlen; // ..
1327            res.ind=(byte)-res.ind;
1328           }
1329          break compare;
1330         }
1331        /* mantissas the same, so far */
1332        ia++;
1333        ib++;
1334        }
1335       }/*compare*/
1336      } // lengths the same
1337     }
1338     }while(false);}/*swaptest*/
1339    }while(false);}/*signdiff*/
1340   
1341   /* here, A is > B if subtracting */
1342   // add [A+B*1] or subtract [A+(B*-1)]
1343   res.mant=byteaddsub(usel,usellen,user,userlen,mult,false);
1344   // [reuse possible only after chop; accounting makes not worthwhile]
1345   
1346   // Finish() rounds before stripping leading 0's, then sets form, etc.
1347   return res.finish(set,false);
1348   }
1349
1350  /**
1351   * Compares this <code>BigDecimal</code> to another, using unlimited
1352   * precision.
1353   * <p>
1354   * The same as {@link #compareTo(BigDecimal, MathContext)},
1355   * where the <code>BigDecimal</code> is <code>rhs</code>,
1356   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1357   *
1358   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1359   *             the comparison.
1360   * @return     An <code>int</code> whose value is -1, 0, or 1 as
1361   *             <code>this</code> is numerically less than, equal to,
1362   *             or greater than <code>rhs</code>.
1363   * @see    #compareTo(Object)
1364   * @stable ICU 2.0
1365   */
1366  
1367  public int compareTo(com.ibm.icu.math.BigDecimal rhs){
1368   return this.compareTo(rhs,plainMC);
1369   }
1370
1371  /**
1372   * Compares this <code>BigDecimal</code> to another.
1373   * <p>
1374   * Implements numeric comparison,
1375   * (as defined in the decimal documentation, see {@link BigDecimal
1376   * class header}),
1377   * and returns a result of type <code>int</code>.
1378   * <p>
1379   * The result will be:
1380   * <table cellpadding=2><tr>
1381   * <td align=right><b>-1</b></td>
1382   * <td>if the current object is less than the first parameter</td>
1383   * </tr><tr>
1384   * <td align=right><b>0</b></td>
1385   * <td>if the current object is equal to the first parameter</td>
1386   * </tr><tr>
1387   * <td align=right><b>1</b></td>
1388   * <td>if the current object is greater than the first parameter.</td>
1389   * </tr></table>
1390   * <p>
1391   * A {@link #compareTo(Object)} method is also provided.
1392   *
1393   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1394   *             the comparison.
1395   * @param  set The <code>MathContext</code> arithmetic settings.
1396   * @return     An <code>int</code> whose value is -1, 0, or 1 as
1397   *             <code>this</code> is numerically less than, equal to,
1398   *             or greater than <code>rhs</code>.
1399   * @see    #compareTo(Object)
1400   * @stable ICU 2.0
1401   */
1402  
1403  public int compareTo(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1404   int thislength=0;
1405   int i=0;
1406   com.ibm.icu.math.BigDecimal newrhs;
1407   // rhs=null will raise NullPointerException, as per Comparable interface
1408   if (set.lostDigits) 
1409    checkdigits(rhs,set.digits);
1410   // [add will recheck in slowpath cases .. but would report -rhs]
1411   if ((this.ind==rhs.ind)&(this.exp==rhs.exp)) 
1412    {
1413     /* sign & exponent the same [very common] */
1414     thislength=this.mant.length;
1415     if (thislength<rhs.mant.length) 
1416      return (byte)-this.ind;
1417     if (thislength>rhs.mant.length) 
1418      return this.ind;
1419     /* lengths are the same; we can do a straight mantissa compare
1420        unless maybe rounding [rounding is very unusual] */
1421     if ((thislength<=set.digits)|(set.digits==0)) 
1422      {
1423       {int $6=thislength;i=0;for(;$6>0;$6--,i++){
1424        if (this.mant[i]<rhs.mant[i]) 
1425         return (byte)-this.ind;
1426        if (this.mant[i]>rhs.mant[i]) 
1427         return this.ind;
1428        }
1429       }/*i*/
1430       return 0; // identical
1431      }
1432    /* drop through for full comparison */
1433    }
1434   else 
1435    {
1436     /* More fastpaths possible */
1437     if (this.ind<rhs.ind) 
1438      return -1;
1439     if (this.ind>rhs.ind) 
1440      return 1;
1441    }
1442   /* carry out a subtract to make the comparison */
1443   newrhs=clone(rhs); // safe copy
1444   newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
1445   return this.add(newrhs,set).ind; // add, and return sign of result
1446   }
1447
1448  /**
1449   * Returns a plain <code>BigDecimal</code> whose value is
1450   * <code>this/rhs</code>, using fixed point arithmetic.
1451   * <p>
1452   * The same as {@link #divide(BigDecimal, int)},
1453   * where the <code>BigDecimal</code> is <code>rhs</code>,
1454   * and the rounding mode is {@link MathContext#ROUND_HALF_UP}.
1455   *
1456   * The length of the decimal part (the scale) of the result will be
1457   * the same as the scale of the current object, if the latter were
1458   * formatted without exponential notation.
1459   *
1460   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1461   *             the division.
1462   * @return     A plain <code>BigDecimal</code> whose value is
1463   *             <code>this/rhs</code>, using fixed point arithmetic.
1464   * @throws ArithmeticException if <code>rhs</code> is zero.
1465   * @stable ICU 2.0
1466   */
1467  
1468  public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs){
1469   return this.dodivide('D',rhs,plainMC,-1);
1470   }
1471
1472  /**
1473   * Returns a plain <code>BigDecimal</code> whose value is
1474   * <code>this/rhs</code>, using fixed point arithmetic and a
1475   * rounding mode.
1476   * <p>
1477   * The same as {@link #divide(BigDecimal, int, int)},
1478   * where the <code>BigDecimal</code> is <code>rhs</code>,
1479   * and the second parameter is <code>this.scale()</code>, and
1480   * the third is <code>round</code>.
1481   * <p>
1482   * The length of the decimal part (the scale) of the result will
1483   * therefore be the same as the scale of the current object, if the
1484   * latter were formatted without exponential notation.
1485   * <p>
1486   * @param  rhs   The <code>BigDecimal</code> for the right hand side of
1487   *               the division.
1488   * @param  round The <code>int</code> rounding mode to be used for
1489   *               the division (see the {@link MathContext} class).
1490   * @return       A plain <code>BigDecimal</code> whose value is
1491   *               <code>this/rhs</code>, using fixed point arithmetic
1492   *               and the specified rounding mode.
1493   * @throws IllegalArgumentException if <code>round</code> is not a
1494   *               valid rounding mode.
1495   * @throws ArithmeticException if <code>rhs</code> is zero.
1496   * @throws ArithmeticException if <code>round</code> is {@link
1497   *               MathContext#ROUND_UNNECESSARY} and
1498   *               <code>this.scale()</code> is insufficient to
1499   *               represent the result exactly.
1500   * @stable ICU 2.0
1501   */
1502  
1503  public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int round){
1504   com.ibm.icu.math.MathContext set;
1505   set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round, too]
1506   return this.dodivide('D',rhs,set,-1); // take scale from LHS
1507   }
1508
1509  /**
1510   * Returns a plain <code>BigDecimal</code> whose value is
1511   * <code>this/rhs</code>, using fixed point arithmetic and a
1512   * given scale and rounding mode.
1513   * <p>
1514   * The same as {@link #divide(BigDecimal, MathContext)},
1515   * where the <code>BigDecimal</code> is <code>rhs</code>,
1516   * <code>new MathContext(0, MathContext.PLAIN, false, round)</code>,
1517   * except that the length of the decimal part (the scale) to be used
1518   * for the result is explicit rather than being taken from
1519   * <code>this</code>.
1520   * <p>
1521   * The length of the decimal part (the scale) of the result will be
1522   * the same as the scale of the current object, if the latter were
1523   * formatted without exponential notation.
1524   * <p>
1525   * @param  rhs   The <code>BigDecimal</code> for the right hand side of
1526   *               the division.
1527   * @param  scale The <code>int</code> scale to be used for the result.
1528   * @param  round The <code>int</code> rounding mode to be used for
1529   *               the division (see the {@link MathContext} class).
1530   * @return       A plain <code>BigDecimal</code> whose value is
1531   *               <code>this/rhs</code>, using fixed point arithmetic
1532   *               and the specified rounding mode.
1533   * @throws IllegalArgumentException if <code>round</code> is not a
1534   *               valid rounding mode.
1535   * @throws ArithmeticException if <code>rhs</code> is zero.
1536   * @throws ArithmeticException if <code>scale</code> is negative.
1537   * @throws ArithmeticException if <code>round</code> is {@link
1538   *               MathContext#ROUND_UNNECESSARY} and <code>scale</code>
1539   *               is insufficient to represent the result exactly.
1540   * @stable ICU 2.0
1541   */
1542  
1543  public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int scale,int round){
1544   com.ibm.icu.math.MathContext set;
1545   if (scale<0) 
1546    throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
1547   set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round]
1548   return this.dodivide('D',rhs,set,scale);
1549   }
1550
1551  /**
1552   * Returns a <code>BigDecimal</code> whose value is <code>this/rhs</code>.
1553   * <p>
1554   * Implements the division (<b><code>/</code></b>) operator
1555   * (as defined in the decimal documentation, see {@link BigDecimal
1556   * class header}),
1557   * and returns the result as a <code>BigDecimal</code> object.
1558   *
1559   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1560   *             the division.
1561   * @param  set The <code>MathContext</code> arithmetic settings.
1562   * @return     A <code>BigDecimal</code> whose value is
1563   *             <code>this/rhs</code>.
1564   * @throws ArithmeticException if <code>rhs</code> is zero.
1565   * @stable ICU 2.0
1566   */
1567  
1568  public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1569   return this.dodivide('D',rhs,set,-1);
1570   }
1571
1572  /**
1573   * Returns a plain <code>BigDecimal</code> whose value is the integer
1574   * part of <code>this/rhs</code>.
1575   * <p>
1576   * The same as {@link #divideInteger(BigDecimal, MathContext)},
1577   * where the <code>BigDecimal</code> is <code>rhs</code>,
1578   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1579   *
1580   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1581   *             the integer division.
1582   * @return     A <code>BigDecimal</code> whose value is the integer
1583   *             part of <code>this/rhs</code>.
1584   * @throws ArithmeticException if <code>rhs</code> is zero.
1585   * @stable ICU 2.0
1586   */
1587  
1588  public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs){
1589   // scale 0 to drop .000 when plain
1590   return this.dodivide('I',rhs,plainMC,0);
1591   }
1592
1593  /**
1594   * Returns a <code>BigDecimal</code> whose value is the integer
1595   * part of <code>this/rhs</code>.
1596   * <p>
1597   * Implements the integer division operator
1598   * (as defined in the decimal documentation, see {@link BigDecimal
1599   * class header}),
1600   * and returns the result as a <code>BigDecimal</code> object.
1601   *
1602   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1603   *             the integer division.
1604   * @param  set The <code>MathContext</code> arithmetic settings.
1605   * @return     A <code>BigDecimal</code> whose value is the integer
1606   *             part of <code>this/rhs</code>.
1607   * @throws ArithmeticException if <code>rhs</code> is zero.
1608   * @throws ArithmeticException if the result will not fit in the
1609   *             number of digits specified for the context.
1610   * @stable ICU 2.0
1611   */
1612  
1613  public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1614   // scale 0 to drop .000 when plain
1615   return this.dodivide('I',rhs,set,0);
1616   }
1617
1618  /**
1619   * Returns a plain <code>BigDecimal</code> whose value is
1620   * the maximum of <code>this</code> and <code>rhs</code>.
1621   * <p>
1622   * The same as {@link #max(BigDecimal, MathContext)},
1623   * where the <code>BigDecimal</code> is <code>rhs</code>,
1624   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1625   *
1626   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1627   *             the comparison.
1628   * @return     A <code>BigDecimal</code> whose value is
1629   *             the maximum of <code>this</code> and <code>rhs</code>.
1630   * @stable ICU 2.0
1631   */
1632  
1633  public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs){
1634   return this.max(rhs,plainMC);
1635   }
1636
1637  /**
1638   * Returns a <code>BigDecimal</code> whose value is
1639   * the maximum of <code>this</code> and <code>rhs</code>.
1640   * <p>
1641   * Returns the larger of the current object and the first parameter.
1642   * <p>
1643   * If calling the {@link #compareTo(BigDecimal, MathContext)} method
1644   * with the same parameters would return <code>1</code> or
1645   * <code>0</code>, then the result of calling the
1646   * {@link #plus(MathContext)} method on the current object (using the
1647   * same <code>MathContext</code> parameter) is returned.
1648   * Otherwise, the result of calling the {@link #plus(MathContext)}
1649   * method on the first parameter object (using the same
1650   * <code>MathContext</code> parameter) is returned.
1651   *
1652   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1653   *             the comparison.
1654   * @param  set The <code>MathContext</code> arithmetic settings.
1655   * @return     A <code>BigDecimal</code> whose value is
1656   *             the maximum of <code>this</code> and <code>rhs</code>.
1657   * @stable ICU 2.0
1658   */
1659  
1660  public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1661   if ((this.compareTo(rhs,set))>=0) 
1662    return this.plus(set);
1663   else 
1664    return rhs.plus(set);
1665   }
1666
1667  /**
1668   * Returns a plain <code>BigDecimal</code> whose value is
1669   * the minimum of <code>this</code> and <code>rhs</code>.
1670   * <p>
1671   * The same as {@link #min(BigDecimal, MathContext)},
1672   * where the <code>BigDecimal</code> is <code>rhs</code>,
1673   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1674   *
1675   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1676   *             the comparison.
1677   * @return     A <code>BigDecimal</code> whose value is
1678   *             the minimum of <code>this</code> and <code>rhs</code>.
1679   * @stable ICU 2.0
1680   */
1681  
1682  public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs){
1683   return this.min(rhs,plainMC);
1684   }
1685
1686  /**
1687   * Returns a <code>BigDecimal</code> whose value is
1688   * the minimum of <code>this</code> and <code>rhs</code>.
1689   * <p>
1690   * Returns the smaller of the current object and the first parameter.
1691   * <p>
1692   * If calling the {@link #compareTo(BigDecimal, MathContext)} method
1693   * with the same parameters would return <code>-1</code> or
1694   * <code>0</code>, then the result of calling the
1695   * {@link #plus(MathContext)} method on the current object (using the
1696   * same <code>MathContext</code> parameter) is returned.
1697   * Otherwise, the result of calling the {@link #plus(MathContext)}
1698   * method on the first parameter object (using the same
1699   * <code>MathContext</code> parameter) is returned.
1700   *
1701   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1702   *             the comparison.
1703   * @param  set The <code>MathContext</code> arithmetic settings.
1704   * @return     A <code>BigDecimal</code> whose value is
1705   *             the minimum of <code>this</code> and <code>rhs</code>.
1706   * @stable ICU 2.0
1707   */
1708  
1709  public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1710   if ((this.compareTo(rhs,set))<=0) 
1711    return this.plus(set);
1712   else 
1713    return rhs.plus(set);
1714   }
1715
1716  /**
1717   * Returns a plain <code>BigDecimal</code> whose value is
1718   * <code>this*rhs</code>, using fixed point arithmetic.
1719   * <p>
1720   * The same as {@link #add(BigDecimal, MathContext)},
1721   * where the <code>BigDecimal</code> is <code>rhs</code>,
1722   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1723   * <p>
1724   * The length of the decimal part (the scale) of the result will be
1725   * the sum of the scales of the operands, if they were formatted
1726   * without exponential notation.
1727   *
1728   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1729   *             the multiplication.
1730   * @return     A <code>BigDecimal</code> whose value is
1731   *             <code>this*rhs</code>, using fixed point arithmetic.
1732   * @stable ICU 2.0
1733   */
1734  
1735  public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs){
1736   return this.multiply(rhs,plainMC);
1737   }
1738
1739  /**
1740   * Returns a <code>BigDecimal</code> whose value is <code>this*rhs</code>.
1741   * <p>
1742   * Implements the multiplication (<b><code>*</code></b>) operator
1743   * (as defined in the decimal documentation, see {@link BigDecimal
1744   * class header}),
1745   * and returns the result as a <code>BigDecimal</code> object.
1746   *
1747   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1748   *             the multiplication.
1749   * @param  set The <code>MathContext</code> arithmetic settings.
1750   * @return     A <code>BigDecimal</code> whose value is
1751   *             <code>this*rhs</code>.
1752   * @stable ICU 2.0
1753   */
1754  
1755  public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
1756   com.ibm.icu.math.BigDecimal lhs;
1757   int padding;
1758   int reqdig;
1759   byte multer[]=null;
1760   byte multand[]=null;
1761   int multandlen;
1762   int acclen=0;
1763   com.ibm.icu.math.BigDecimal res;
1764   byte acc[];
1765   int n=0;
1766   byte mult=0;
1767   if (set.lostDigits) 
1768    checkdigits(rhs,set.digits);
1769   lhs=this; // name for clarity and proxy
1770   
1771   /* Prepare numbers (truncate, unless unlimited precision) */
1772   padding=0; // trailing 0's to add
1773   reqdig=set.digits; // local copy
1774   if (reqdig>0) 
1775    {
1776     if (lhs.mant.length>reqdig) 
1777      lhs=clone(lhs).round(set);
1778     if (rhs.mant.length>reqdig) 
1779      rhs=clone(rhs).round(set);
1780    // [we could reuse the new LHS for result in this case]
1781    }
1782   else 
1783    {/* unlimited */
1784     // fixed point arithmetic will want every trailing 0; we add these
1785     // after the calculation rather than before, for speed.
1786     if (lhs.exp>0) 
1787      padding=padding+lhs.exp;
1788     if (rhs.exp>0) 
1789      padding=padding+rhs.exp;
1790    }
1791   
1792   // For best speed, as in DMSRCN, we use the shorter number as the
1793   // multiplier and the longer as the multiplicand.
1794   // 1999.12.22: We used to special case when the result would fit in
1795   //             a long, but with Java 1.3 this gave no advantage.
1796   if (lhs.mant.length<rhs.mant.length) 
1797    {
1798     multer=lhs.mant;
1799     multand=rhs.mant;
1800    }
1801   else 
1802    {
1803     multer=rhs.mant;
1804     multand=lhs.mant;
1805    }
1806   
1807   /* Calculate how long result byte array will be */
1808   multandlen=(multer.length+multand.length)-1; // effective length
1809   // optimize for 75% of the cases where a carry is expected...
1810   if ((multer[0]*multand[0])>9) 
1811    acclen=multandlen+1;
1812   else 
1813    acclen=multandlen;
1814   
1815   /* Now the main long multiplication loop */
1816   res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
1817   acc=new byte[acclen]; // accumulator, all zeros
1818   // 1998.07.01: calculate from left to right so that accumulator goes
1819   // to likely final length on first addition; this avoids a one-digit
1820   // extension (and object allocation) each time around the loop.
1821   // Initial number therefore has virtual zeros added to right.
1822   {int $7=multer.length;n=0;for(;$7>0;$7--,n++){
1823    mult=multer[n];
1824    if (mult!=0) 
1825     { // [optimization]
1826      // accumulate [accumulator is reusable array]
1827      acc=byteaddsub(acc,acc.length,multand,multandlen,mult,true);
1828     }
1829    // divide multiplicand by 10 for next digit to right
1830    multandlen--; // 'virtual length'
1831    }
1832   }/*n*/
1833   
1834   res.ind=(byte)(lhs.ind*rhs.ind); // final sign
1835   res.exp=(lhs.exp+rhs.exp)-padding; // final exponent
1836   // [overflow is checked by finish]
1837   
1838   /* add trailing zeros to the result, if necessary */
1839   if (padding==0) 
1840    res.mant=acc;
1841   else 
1842    res.mant=extend(acc,acc.length+padding); // add trailing 0s
1843   return res.finish(set,false);
1844   }
1845
1846  /**
1847   * Returns a plain <code>BigDecimal</code> whose value is
1848   * <code>-this</code>.
1849   * <p>
1850   * The same as {@link #negate(MathContext)}, where the context is
1851   * <code>new MathContext(0, MathContext.PLAIN)</code>.
1852   * <p>
1853   * The length of the decimal part (the scale) of the result will be
1854   * be <code>this.scale()</code>
1855   *
1856   *
1857   * @return A <code>BigDecimal</code> whose value is
1858   *         <code>-this</code>.
1859   * @stable ICU 2.0
1860   */
1861  
1862  public com.ibm.icu.math.BigDecimal negate(){
1863   return this.negate(plainMC);
1864   }
1865
1866  /**
1867   * Returns a <code>BigDecimal</code> whose value is <code>-this</code>.
1868   * <p>
1869   * Implements the negation (Prefix <b><code>-</code></b>) operator
1870   * (as defined in the decimal documentation, see {@link BigDecimal
1871   * class header}),
1872   * and returns the result as a <code>BigDecimal</code> object.
1873   *
1874   * @param  set The <code>MathContext</code> arithmetic settings.
1875   * @return A <code>BigDecimal</code> whose value is
1876   *         <code>-this</code>.
1877   * @stable ICU 2.0
1878   */
1879  
1880  public com.ibm.icu.math.BigDecimal negate(com.ibm.icu.math.MathContext set){
1881   com.ibm.icu.math.BigDecimal res;
1882   // Originally called minus(), changed to matched Java precedents
1883   // This simply clones, flips the sign, and possibly rounds
1884   if (set.lostDigits) 
1885    checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
1886   res=clone(this); // safe copy
1887   res.ind=(byte)-res.ind;
1888   return res.finish(set,false);
1889   }
1890
1891  /**
1892   * Returns a plain <code>BigDecimal</code> whose value is
1893   * <code>+this</code>.
1894   * Note that <code>this</code> is not necessarily a
1895   * plain <code>BigDecimal</code>, but the result will always be.
1896   * <p>
1897   * The same as {@link #plus(MathContext)}, where the context is
1898   * <code>new MathContext(0, MathContext.PLAIN)</code>.
1899   * <p>
1900   * The length of the decimal part (the scale) of the result will be
1901   * be <code>this.scale()</code>
1902   *
1903   * @return A <code>BigDecimal</code> whose value is
1904   *         <code>+this</code>.
1905   * @stable ICU 2.0
1906   */
1907  
1908  public com.ibm.icu.math.BigDecimal plus(){
1909   return this.plus(plainMC);
1910   }
1911
1912  /**
1913   * Returns a <code>BigDecimal</code> whose value is
1914   * <code>+this</code>.
1915   * <p>
1916   * Implements the plus (Prefix <b><code>+</code></b>) operator
1917   * (as defined in the decimal documentation, see {@link BigDecimal
1918   * class header}),
1919   * and returns the result as a <code>BigDecimal</code> object.
1920   * <p>
1921   * This method is useful for rounding or otherwise applying a context
1922   * to a decimal value.
1923   *
1924   * @param  set The <code>MathContext</code> arithmetic settings.
1925   * @return A <code>BigDecimal</code> whose value is
1926   *         <code>+this</code>.
1927   * @stable ICU 2.0
1928   */
1929  
1930  public com.ibm.icu.math.BigDecimal plus(com.ibm.icu.math.MathContext set){
1931   // This clones and forces the result to the new settings
1932   // May return same object
1933   if (set.lostDigits) 
1934    checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
1935   // Optimization: returns same object for some common cases
1936   if (set.form==com.ibm.icu.math.MathContext.PLAIN) 
1937    if (this.form==com.ibm.icu.math.MathContext.PLAIN) 
1938     {
1939      if (this.mant.length<=set.digits) 
1940       return this;
1941      if (set.digits==0) 
1942       return this;
1943     }
1944   return clone(this).finish(set,false);
1945   }
1946
1947  /**
1948   * Returns a plain <code>BigDecimal</code> whose value is
1949   * <code>this**rhs</code>, using fixed point arithmetic.
1950   * <p>
1951   * The same as {@link #pow(BigDecimal, MathContext)},
1952   * where the <code>BigDecimal</code> is <code>rhs</code>,
1953   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
1954   * <p>
1955   * The parameter is the power to which the <code>this</code> will be
1956   * raised; it must be in the range 0 through 999999999, and must
1957   * have a decimal part of zero.  Note that these restrictions may be
1958   * removed in the future, so they should not be used as a test for a
1959   * whole number.
1960   * <p>
1961   * In addition, the power must not be negative, as no
1962   * <code>MathContext</code> is used and so the result would then
1963   * always be 0.
1964   *
1965   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1966   *             the operation (the power).
1967   * @return     A <code>BigDecimal</code> whose value is
1968   *             <code>this**rhs</code>, using fixed point arithmetic.
1969   * @throws ArithmeticException if <code>rhs</code> is out of range or
1970   *             is not a whole number.
1971   * @stable ICU 2.0
1972   */
1973  
1974  public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs){
1975   return this.pow(rhs,plainMC);
1976   }
1977  // The name for this method is inherited from the precedent set by the
1978  // BigInteger and Math classes.
1979  
1980  /**
1981   * Returns a <code>BigDecimal</code> whose value is <code>this**rhs</code>.
1982   * <p>
1983   * Implements the power (<b><code>**</code></b>) operator
1984   * (as defined in the decimal documentation, see {@link BigDecimal
1985   * class header}),
1986   * and returns the result as a <code>BigDecimal</code> object.
1987   * <p>
1988   * The first parameter is the power to which the <code>this</code>
1989   * will be raised; it must be in the range -999999999 through
1990   * 999999999, and must have a decimal part of zero.  Note that these
1991   * restrictions may be removed in the future, so they should not be
1992   * used as a test for a whole number.
1993   * <p>
1994   * If the <code>digits</code> setting of the <code>MathContext</code>
1995   * parameter is 0, the power must be zero or positive.
1996   *
1997   * @param  rhs The <code>BigDecimal</code> for the right hand side of
1998   *             the operation (the power).
1999   * @param  set The <code>MathContext</code> arithmetic settings.
2000   * @return     A <code>BigDecimal</code> whose value is
2001   *             <code>this**rhs</code>.
2002   * @throws ArithmeticException if <code>rhs</code> is out of range or
2003   *             is not a whole number.
2004   * @stable ICU 2.0
2005   */
2006  
2007  public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2008   int n;
2009   com.ibm.icu.math.BigDecimal lhs;
2010   int reqdig;
2011   int workdigits=0;
2012   int L=0;
2013   com.ibm.icu.math.MathContext workset;
2014   com.ibm.icu.math.BigDecimal res;
2015   boolean seenbit;
2016   int i=0;
2017   if (set.lostDigits) 
2018    checkdigits(rhs,set.digits);
2019   n=rhs.intcheck(MinArg,MaxArg); // check RHS by the rules
2020   lhs=this; // clarified name
2021   
2022   reqdig=set.digits; // local copy (heavily used)
2023   if (reqdig==0) 
2024    {
2025     if (rhs.ind==isneg) 
2026      throw new java.lang.ArithmeticException("Negative power:"+" "+rhs.toString());
2027     workdigits=0;
2028    }
2029   else 
2030    {/* non-0 digits */
2031     if ((rhs.mant.length+rhs.exp)>reqdig) 
2032      throw new java.lang.ArithmeticException("Too many digits:"+" "+rhs.toString());
2033     
2034     /* Round the lhs to DIGITS if need be */
2035     if (lhs.mant.length>reqdig) 
2036      lhs=clone(lhs).round(set);
2037     
2038     /* L for precision calculation [see ANSI X3.274-1996] */
2039     L=rhs.mant.length+rhs.exp; // length without decimal zeros/exp
2040     workdigits=(reqdig+L)+1; // calculate the working DIGITS
2041    }
2042   
2043   /* Create a copy of set for working settings */
2044   // Note: no need to check for lostDigits again.
2045   // 1999.07.17 Note: this construction must follow RHS check
2046   workset=new com.ibm.icu.math.MathContext(workdigits,set.form,false,set.roundingMode);
2047   
2048   res=ONE; // accumulator
2049   if (n==0) 
2050    return res; // x**0 == 1
2051   if (n<0) 
2052    n=(int)-n; // [rhs.ind records the sign]
2053   seenbit=false; // set once we've seen a 1-bit
2054   {i=1;i:for(;;i++){ // for each bit [top bit ignored]
2055    n=n+n; // shift left 1 bit
2056    if (n<0) 
2057     { // top bit is set
2058      seenbit=true; // OK, we're off
2059      res=res.multiply(lhs,workset); // acc=acc*x
2060     }
2061    if (i==31) 
2062     break i; // that was the last bit
2063    if ((!seenbit)) 
2064     continue i; // we don't have to square 1
2065    res=res.multiply(res,workset); // acc=acc*acc [square]
2066    }
2067   }/*i*/ // 32 bits
2068   if (rhs.ind<0)  // was a **-n [hence digits>0]
2069    res=ONE.divide(res,workset); // .. so acc=1/acc
2070   return res.finish(set,true); // round and strip [original digits]
2071   }
2072
2073  /**
2074   * Returns a plain <code>BigDecimal</code> whose value is
2075   * the remainder of <code>this/rhs</code>, using fixed point arithmetic.
2076   * <p>
2077   * The same as {@link #remainder(BigDecimal, MathContext)},
2078   * where the <code>BigDecimal</code> is <code>rhs</code>,
2079   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
2080   * <p>
2081   * This is not the modulo operator -- the result may be negative.
2082   *
2083   * @param  rhs The <code>BigDecimal</code> for the right hand side of
2084   *             the remainder operation.
2085   * @return     A <code>BigDecimal</code> whose value is the remainder
2086   *             of <code>this/rhs</code>, using fixed point arithmetic.
2087   * @throws ArithmeticException if <code>rhs</code> is zero.
2088   * @stable ICU 2.0
2089   */
2090  
2091  public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs){
2092   return this.dodivide('R',rhs,plainMC,-1);
2093   }
2094
2095  /**
2096   * Returns a <code>BigDecimal</code> whose value is the remainder of
2097   * <code>this/rhs</code>.
2098   * <p>
2099   * Implements the remainder operator
2100   * (as defined in the decimal documentation, see {@link BigDecimal
2101   * class header}),
2102   * and returns the result as a <code>BigDecimal</code> object.
2103   * <p>
2104   * This is not the modulo operator -- the result may be negative.
2105   *
2106   * @param  rhs The <code>BigDecimal</code> for the right hand side of
2107   *             the remainder operation.
2108   * @param  set The <code>MathContext</code> arithmetic settings.
2109   * @return     A <code>BigDecimal</code> whose value is the remainder
2110   *             of <code>this+rhs</code>.
2111   * @throws ArithmeticException if <code>rhs</code> is zero.
2112   * @throws ArithmeticException if the integer part of the result will
2113   *             not fit in the number of digits specified for the
2114   *             context.
2115   * @stable ICU 2.0
2116   */
2117  
2118  public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2119   return this.dodivide('R',rhs,set,-1);
2120   }
2121
2122  /**
2123   * Returns a plain <code>BigDecimal</code> whose value is
2124   * <code>this-rhs</code>, using fixed point arithmetic.
2125   * <p>
2126   * The same as {@link #subtract(BigDecimal, MathContext)},
2127   * where the <code>BigDecimal</code> is <code>rhs</code>,
2128   * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
2129   * <p>
2130   * The length of the decimal part (the scale) of the result will be
2131   * the maximum of the scales of the two operands.
2132   *
2133   * @param  rhs The <code>BigDecimal</code> for the right hand side of
2134   *             the subtraction.
2135   * @return     A <code>BigDecimal</code> whose value is
2136   *             <code>this-rhs</code>, using fixed point arithmetic.
2137   * @stable ICU 2.0
2138   */
2139  
2140  public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs){
2141   return this.subtract(rhs,plainMC);
2142   }
2143
2144  /**
2145   * Returns a <code>BigDecimal</code> whose value is <code>this-rhs</code>.
2146   * <p>
2147   * Implements the subtraction (<b><code>-</code></b>) operator
2148   * (as defined in the decimal documentation, see {@link BigDecimal
2149   * class header}),
2150   * and returns the result as a <code>BigDecimal</code> object.
2151   *
2152   * @param  rhs The <code>BigDecimal</code> for the right hand side of
2153   *             the subtraction.
2154   * @param  set The <code>MathContext</code> arithmetic settings.
2155   * @return     A <code>BigDecimal</code> whose value is
2156   *             <code>this-rhs</code>.
2157   * @stable ICU 2.0
2158   */
2159  
2160  public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
2161   com.ibm.icu.math.BigDecimal newrhs;
2162   if (set.lostDigits) 
2163    checkdigits(rhs,set.digits);
2164   // [add will recheck .. but would report -rhs]
2165   /* carry out the subtraction */
2166   // we could fastpath -0, but it is too rare.
2167   newrhs=clone(rhs); // safe copy
2168   newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
2169   return this.add(newrhs,set); // arithmetic
2170   }
2171
2172  /* ---------------------------------------------------------------- */
2173  /* Other methods                                                    */
2174  /* ---------------------------------------------------------------- */
2175  
2176  /**
2177   * Converts this <code>BigDecimal</code> to a <code>byte</code>.
2178   * If the <code>BigDecimal</code> has a non-zero decimal part or is
2179   * out of the possible range for a <code>byte</code> (8-bit signed
2180   * integer) result then an <code>ArithmeticException</code> is thrown.
2181   *
2182   * @return A <code>byte</code> equal in value to <code>this</code>.
2183   * @throws ArithmeticException if <code>this</code> has a non-zero
2184   *                 decimal part, or will not fit in a <code>byte</code>.
2185   * @stable ICU 2.0
2186   */
2187  
2188  public byte byteValueExact(){
2189   int num;
2190   num=this.intValueExact(); // will check decimal part too
2191   if ((num>127)|(num<(-128))) 
2192    throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
2193   return (byte)num;
2194   }
2195
2196  /**
2197   * Compares this <code>BigDecimal</code> with the value of the parameter.
2198   * <p>
2199   * If the parameter is <code>null</code>, or is not an instance of the
2200   * <code>BigDecimal</code> type, an exception is thrown.
2201   * Otherwise, the parameter is cast to type <code>BigDecimal</code>
2202   * and the result of the {@link #compareTo(BigDecimal)} method,
2203   * using the cast parameter, is returned.
2204   * <p>
2205   * The {@link #compareTo(BigDecimal, MathContext)} method should be
2206   * used when a <code>MathContext</code> is needed for the comparison.
2207   *
2208   * @param  rhsobj The <code>Object</code> for the right hand side of
2209   *             the comparison.
2210   * @return     An <code>int</code> whose value is -1, 0, or 1 as
2211   *             <code>this</code> is numerically less than, equal to,
2212   *             or greater than <code>rhs</code>.
2213   * @throws ClassCastException if <code>rhs</code> cannot be cast to
2214   *                 a <code>BigDecimal</code> object.
2215   * @see    #compareTo(BigDecimal)
2216   * @stable ICU 2.0
2217   */
2218  
2219  public int compareTo(java.lang.Object rhsobj){
2220   // the cast in the next line will raise ClassCastException if necessary
2221   return compareTo((com.ibm.icu.math.BigDecimal)rhsobj,plainMC);
2222   }
2223
2224  /**
2225   * Converts this <code>BigDecimal</code> to a <code>double</code>.
2226   * If the <code>BigDecimal</code> is out of the possible range for a
2227   * <code>double</code> (64-bit signed floating point) result then an
2228   * <code>ArithmeticException</code> is thrown.
2229   * <p>
2230   * The double produced is identical to result of expressing the
2231   * <code>BigDecimal</code> as a <code>String</code> and then
2232   * converting it using the <code>Double(String)</code> constructor;
2233   * this can result in values of <code>Double.NEGATIVE_INFINITY</code>
2234   * or <code>Double.POSITIVE_INFINITY</code>.
2235   *
2236   * @return A <code>double</code> corresponding to <code>this</code>.
2237   * @stable ICU 2.0
2238   */
2239  
2240  public double doubleValue(){
2241   // We go via a String [as does BigDecimal in JDK 1.2]
2242   // Next line could possibly raise NumberFormatException
2243   return java.lang.Double.valueOf(this.toString()).doubleValue();
2244   }
2245
2246  /**
2247   * Compares this <code>BigDecimal</code> with <code>rhs</code> for
2248   * equality.
2249   * <p>
2250   * If the parameter is <code>null</code>, or is not an instance of the
2251   * BigDecimal type, or is not exactly equal to the current
2252   * <code>BigDecimal</code> object, then <i>false</i> is returned.
2253   * Otherwise, <i>true</i> is returned.
2254   * <p>
2255   * "Exactly equal", here, means that the <code>String</code>
2256   * representations of the <code>BigDecimal</code> numbers are
2257   * identical (they have the same characters in the same sequence).
2258   * <p>
2259   * The {@link #compareTo(BigDecimal, MathContext)} method should be
2260   * used for more general comparisons.
2261   * @param  obj The <code>Object</code> for the right hand side of
2262   *             the comparison.
2263   * @return     A <code>boolean</code> whose value <i>true</i> if and
2264   *             only if the operands have identical string representations.
2265   * @throws ClassCastException if <code>rhs</code> cannot be cast to
2266   *                 a <code>BigDecimal</code> object.
2267   * @stable ICU 2.0
2268   * @see    #compareTo(Object)
2269   * @see    #compareTo(BigDecimal)
2270   * @see    #compareTo(BigDecimal, MathContext)
2271   */
2272  
2273  public boolean equals(java.lang.Object obj){
2274   com.ibm.icu.math.BigDecimal rhs;
2275   int i=0;
2276   char lca[]=null;
2277   char rca[]=null;
2278   // We are equal iff toString of both are exactly the same
2279   if (obj==null) 
2280    return false; // not equal
2281   if ((!(((obj instanceof com.ibm.icu.math.BigDecimal))))) 
2282    return false; // not a decimal
2283   rhs=(com.ibm.icu.math.BigDecimal)obj; // cast; we know it will work
2284   if (this.ind!=rhs.ind) 
2285    return false; // different signs never match
2286   if (((this.mant.length==rhs.mant.length)&(this.exp==rhs.exp))&(this.form==rhs.form)) 
2287    
2288    { // mantissas say all
2289     // here with equal-length byte arrays to compare
2290     {int $8=this.mant.length;i=0;for(;$8>0;$8--,i++){
2291      if (this.mant[i]!=rhs.mant[i]) 
2292       return false;
2293      }
2294     }/*i*/
2295    }
2296   else 
2297    { // need proper layout
2298     lca=this.layout(); // layout to character array
2299     rca=rhs.layout();
2300     if (lca.length!=rca.length) 
2301      return false; // mismatch
2302     // here with equal-length character arrays to compare
2303     {int $9=lca.length;i=0;for(;$9>0;$9--,i++){
2304      if (lca[i]!=rca[i]) 
2305       return false;
2306      }
2307     }/*i*/
2308    }
2309   return true; // arrays have identical content
2310   }
2311
2312  /**
2313   * Converts this <code>BigDecimal</code> to a <code>float</code>.
2314   * If the <code>BigDecimal</code> is out of the possible range for a
2315   * <code>float</code> (32-bit signed floating point) result then an
2316   * <code>ArithmeticException</code> is thrown.
2317   * <p>
2318   * The float produced is identical to result of expressing the
2319   * <code>BigDecimal</code> as a <code>String</code> and then
2320   * converting it using the <code>Float(String)</code> constructor;
2321   * this can result in values of <code>Float.NEGATIVE_INFINITY</code>
2322   * or <code>Float.POSITIVE_INFINITY</code>.
2323   *
2324   * @return A <code>float</code> corresponding to <code>this</code>.
2325   * @stable ICU 2.0
2326   */
2327  
2328  public float floatValue(){
2329   return java.lang.Float.valueOf(this.toString()).floatValue();
2330   }
2331
2332  /**
2333   * Returns the <code>String</code> representation of this
2334   * <code>BigDecimal</code>, modified by layout parameters.
2335   * <p>
2336   * <i>This method is provided as a primitive for use by more
2337   * sophisticated classes, such as <code>DecimalFormat</code>, that
2338   * can apply locale-sensitive editing of the result.  The level of
2339   * formatting that it provides is a necessary part of the BigDecimal
2340   * class as it is sensitive to and must follow the calculation and
2341   * rounding rules for BigDecimal arithmetic.
2342   * However, if the function is provided elsewhere, it may be removed
2343   * from this class. </i>
2344   * <p>
2345   * The parameters, for both forms of the <code>format</code> method
2346   * are all of type <code>int</code>.
2347   * A value of -1 for any parameter indicates that the default action
2348   * or value for that parameter should be used.
2349   * <p>
2350   * The parameters, <code>before</code> and <code>after</code>,
2351   * specify the number of characters to be used for the integer part
2352   * and decimal part of the result respectively.  Exponential notation
2353   * is not used. If either parameter is -1 (which indicates the default
2354   * action), the number of characters used will be exactly as many as
2355   * are needed for that part.
2356   * <p>
2357   * <code>before</code> must be a positive number; if it is larger than
2358   * is needed to contain the integer part, that part is padded on the
2359   * left with blanks to the requested length. If <code>before</code> is
2360   * not large enough to contain the integer part of the number
2361   * (including the sign, for negative numbers) an exception is thrown.
2362   * <p>
2363   * <code>after</code> must be a non-negative number; if it is not the
2364   * same size as the decimal part of the number, the number will be
2365   * rounded (or extended with zeros) to fit.  Specifying 0 for
2366   * <code>after</code> will cause the number to be rounded to an
2367   * integer (that is, it will have no decimal part or decimal point).
2368   * The rounding method will be the default,
2369   * <code>MathContext.ROUND_HALF_UP</code>.
2370   * <p>
2371   * Other rounding methods, and the use of exponential notation, can
2372   * be selected by using {@link #format(int,int,int,int,int,int)}.
2373   * Using the two-parameter form of the method has exactly the same
2374   * effect as using the six-parameter form with the final four
2375   * parameters all being -1.
2376   *
2377   * @param  before The <code>int</code> specifying the number of places
2378   *                before the decimal point.  Use -1 for 'as many as
2379   *                are needed'.
2380   * @param  after  The <code>int</code> specifying the number of places
2381   *                after the decimal point.  Use -1 for 'as many as are
2382   *                needed'.
2383   * @return        A <code>String</code> representing this
2384   *                <code>BigDecimal</code>, laid out according to the
2385   *                specified parameters
2386   * @throws ArithmeticException if the number cannot be laid out as
2387   *                requested.
2388   * @throws IllegalArgumentException if a parameter is out of range.
2389   * @stable ICU 2.0
2390   * @see    #toString
2391   * @see    #toCharArray
2392   */
2393  
2394  public java.lang.String format(int before,int after){
2395   return format(before,after,-1,-1,com.ibm.icu.math.MathContext.SCIENTIFIC,ROUND_HALF_UP);
2396   }
2397
2398  /**
2399   * Returns the <code>String</code> representation of this
2400   * <code>BigDecimal</code>, modified by layout parameters and allowing
2401   * exponential notation.
2402   * <p>
2403   * <i>This method is provided as a primitive for use by more
2404   * sophisticated classes, such as <code>DecimalFormat</code>, that
2405   * can apply locale-sensitive editing of the result.  The level of
2406   * formatting that it provides is a necessary part of the BigDecimal
2407   * class as it is sensitive to and must follow the calculation and
2408   * rounding rules for BigDecimal arithmetic.
2409   * However, if the function is provided elsewhere, it may be removed
2410   * from this class. </i>
2411   * <p>
2412   * The parameters are all of type <code>int</code>.
2413   * A value of -1 for any parameter indicates that the default action
2414   * or value for that parameter should be used.
2415   * <p>
2416   * The first two parameters (<code>before</code> and
2417   * <code>after</code>) specify the number of characters to be used for
2418   * the integer part and decimal part of the result respectively, as
2419   * defined for {@link #format(int,int)}.
2420   * If either of these is -1 (which indicates the default action), the
2421   * number of characters used will be exactly as many as are needed for
2422   * that part.
2423   * <p>
2424   * The remaining parameters control the use of exponential notation
2425   * and rounding.  Three (<code>explaces</code>, <code>exdigits</code>,
2426   * and <code>exform</code>) control the exponent part of the result.
2427   * As before, the default action for any of these parameters may be
2428   * selected by using the value -1.
2429   * <p>
2430   * <code>explaces</code> must be a positive number; it sets the number
2431   * of places (digits after the sign of the exponent) to be used for
2432   * any exponent part, the default (when <code>explaces</code> is -1)
2433   * being to use as many as are needed.
2434   * If <code>explaces</code> is not -1, space is always reserved for
2435   * an exponent; if one is not needed (for example, if the exponent
2436   * will be 0) then <code>explaces</code>+2 blanks are appended to the
2437   * result.
2438   * <!-- (This preserves vertical alignment of similarly formatted
2439   *       numbers in a monospace font.) -->
2440   * If <code>explaces</code> is not -1 and is not large enough to
2441   * contain the exponent, an exception is thrown.
2442   * <p>
2443   * <code>exdigits</code> sets the trigger point for use of exponential
2444   * notation. If, before any rounding, the number of places needed
2445   * before the decimal point exceeds <code>exdigits</code>, or if the
2446   * absolute value of the result is less than <code>0.000001</code>,
2447   * then exponential form will be used, provided that
2448   * <code>exdigits</code> was specified.
2449   * When <code>exdigits</code> is -1, exponential notation will never
2450   * be used. If 0 is specified for <code>exdigits</code>, exponential
2451   * notation is always used unless the exponent would be 0.
2452   * <p>
2453   * <code>exform</code> sets the form for exponential notation (if
2454   * needed).
2455   * It  may be either {@link MathContext#SCIENTIFIC} or
2456   * {@link MathContext#ENGINEERING}.
2457   * If the latter, engineering, form is requested, up to three digits
2458   * (plus sign, if negative) may be needed for the integer part of the
2459   * result (<code>before</code>).  Otherwise, only one digit (plus
2460   * sign, if negative) is needed.
2461   * <p>
2462   * Finally, the sixth argument, <code>exround</code>, selects the
2463   * rounding algorithm to be used, and must be one of the values
2464   * indicated by a public constant in the {@link MathContext} class
2465   * whose name starts with <code>ROUND_</code>.
2466   * The default (<code>ROUND_HALF_UP</code>) may also be selected by
2467   * using the value -1, as before.
2468   * <p>
2469   * The special value <code>MathContext.ROUND_UNNECESSARY</code> may be
2470   * used to detect whether non-zero digits are discarded -- if
2471   * <code>exround</code> has this value than if non-zero digits would
2472   * be discarded (rounded) during formatting then an
2473   * <code>ArithmeticException</code> is thrown.
2474   *
2475   * @param  before   The <code>int</code> specifying the number of places
2476   *                  before the decimal point.
2477   *                  Use -1 for 'as many as are needed'.
2478   * @param  after    The <code>int</code> specifying the number of places
2479   *                  after the decimal point.
2480   *                  Use -1 for 'as many as are needed'.
2481   * @param  explaces The <code>int</code> specifying the number of places
2482   *                  to be used for any exponent.
2483   *                  Use -1 for 'as many as are needed'.
2484   * @param  exdigits The <code>int</code> specifying the trigger
2485   *                  (digits before the decimal point) which if
2486   *                  exceeded causes exponential notation to be used.
2487   *                  Use 0 to force exponential notation.
2488   *                  Use -1 to force plain notation (no exponential
2489   *                  notation).
2490   * @param  exformint   The <code>int</code> specifying the form of
2491   *                  exponential notation to be used
2492   *                  ({@link MathContext#SCIENTIFIC} or
2493   *                  {@link MathContext#ENGINEERING}).
2494   * @param  exround  The <code>int</code> specifying the rounding mode
2495   *                  to use.
2496   *                  Use -1 for the default, {@link MathContext#ROUND_HALF_UP}.
2497   * @return          A <code>String</code> representing this
2498   *                  <code>BigDecimal</code>, laid out according to the
2499   *                  specified parameters
2500   * @throws ArithmeticException if the number cannot be laid out as
2501   *                  requested.
2502   * @throws IllegalArgumentException if a parameter is out of range.
2503   * @see    #toString
2504   * @see    #toCharArray
2505   * @stable ICU 2.0
2506   */
2507  
2508  public java.lang.String format(int before,int after,int explaces,int exdigits,int exformint,int exround){
2509   com.ibm.icu.math.BigDecimal num;
2510   int mag=0;
2511   int thisafter=0;
2512   int lead=0;
2513   byte newmant[]=null;
2514   int chop=0;
2515   int need=0;
2516   int oldexp=0;
2517   char a[];
2518   int p=0;
2519   char newa[]=null;
2520   int i=0;
2521   int places=0;
2522   
2523   
2524   /* Check arguments */
2525   if ((before<(-1))|(before==0)) 
2526    badarg("format",1,java.lang.String.valueOf(before));
2527   if (after<(-1)) 
2528    badarg("format",2,java.lang.String.valueOf(after));
2529   if ((explaces<(-1))|(explaces==0)) 
2530    badarg("format",3,java.lang.String.valueOf(explaces));
2531   if (exdigits<(-1)) 
2532    badarg("format",4,java.lang.String.valueOf(explaces));
2533   {/*select*/
2534   if (exformint==com.ibm.icu.math.MathContext.SCIENTIFIC){
2535   }else if (exformint==com.ibm.icu.math.MathContext.ENGINEERING){
2536   }else if (exformint==(-1))
2537    exformint=com.ibm.icu.math.MathContext.SCIENTIFIC;
2538    // note PLAIN isn't allowed
2539   else{
2540    badarg("format",5,java.lang.String.valueOf(exformint));
2541   }
2542   }
2543   // checking the rounding mode is done by trying to construct a
2544   // MathContext object with that mode; it will fail if bad
2545   if (exround!=ROUND_HALF_UP) 
2546    {try{ // if non-default...
2547     if (exround==(-1)) 
2548      exround=ROUND_HALF_UP;
2549     else 
2550      new com.ibm.icu.math.MathContext(9,com.ibm.icu.math.MathContext.SCIENTIFIC,false,exround);
2551    }
2552    catch (java.lang.IllegalArgumentException $10){
2553     badarg("format",6,java.lang.String.valueOf(exround));
2554    }}
2555   
2556   num=clone(this); // make private copy
2557   
2558   /* Here:
2559      num       is BigDecimal to format
2560      before    is places before point [>0]
2561      after     is places after point  [>=0]
2562      explaces  is exponent places     [>0]
2563      exdigits  is exponent digits     [>=0]
2564      exformint is exponent form       [one of two]
2565      exround   is rounding mode       [one of eight]
2566      'before' through 'exdigits' are -1 if not specified
2567   */
2568   
2569   /* determine form */
2570   {do{/*select*/
2571   if (exdigits==(-1))
2572    num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2573   else if (num.ind==iszero)
2574    num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2575   else{
2576    // determine whether triggers
2577    mag=num.exp+num.mant.length;
2578    if (mag>exdigits) 
2579     num.form=(byte)exformint;
2580    else 
2581     if (mag<(-5)) 
2582      num.form=(byte)exformint;
2583     else 
2584      num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
2585   }
2586   }while(false);}/*setform*/
2587   
2588   /* If 'after' was specified then we may need to adjust the
2589      mantissa.  This is a little tricky, as we must conform to the
2590      rules of exponential layout if necessary (e.g., we cannot end up
2591      with 10.0 if scientific). */
2592   if (after>=0) 
2593    {setafter:for(;;){
2594     // calculate the current after-length
2595     {/*select*/
2596     if (num.form==com.ibm.icu.math.MathContext.PLAIN)
2597      thisafter=(int)-num.exp; // has decimal part
2598     else if (num.form==com.ibm.icu.math.MathContext.SCIENTIFIC)
2599      thisafter=num.mant.length-1;
2600     else{ // engineering
2601      lead=(((num.exp+num.mant.length)-1))%3; // exponent to use
2602      if (lead<0) 
2603       lead=3+lead; // negative exponent case
2604      lead++; // number of leading digits
2605      if (lead>=num.mant.length) 
2606       thisafter=0;
2607      else 
2608       thisafter=num.mant.length-lead;
2609     }
2610     }
2611     if (thisafter==after) 
2612      break setafter; // we're in luck
2613     if (thisafter<after) 
2614      { // need added trailing zeros
2615       // [thisafter can be negative]
2616       newmant=extend(num.mant,(num.mant.length+after)-thisafter);
2617       num.mant=newmant;
2618       num.exp=num.exp-((after-thisafter)); // adjust exponent
2619       if (num.exp<MinExp) 
2620        throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+num.exp);
2621       break setafter;
2622      }
2623     // We have too many digits after the decimal point; this could
2624     // cause a carry, which could change the mantissa...
2625     // Watch out for implied leading zeros in PLAIN case
2626     chop=thisafter-after; // digits to lop [is >0]
2627     if (chop>num.mant.length) 
2628      { // all digits go, no chance of carry
2629       // carry on with zero
2630       num.mant=ZERO.mant;
2631       num.ind=iszero;
2632       num.exp=0;
2633       continue setafter; // recheck: we may need trailing zeros
2634      }
2635     // we have a digit to inspect from existing mantissa
2636     // round the number as required
2637     need=num.mant.length-chop; // digits to end up with [may be 0]
2638     oldexp=num.exp; // save old exponent
2639     num.round(need,exround);
2640     // if the exponent grew by more than the digits we chopped, then
2641     // we must have had a carry, so will need to recheck the layout
2642     if ((num.exp-oldexp)==chop) 
2643      break setafter; // number did not have carry
2644     // mantissa got extended .. so go around and check again
2645     }
2646    }/*setafter*/
2647   
2648   a=num.layout(); // lay out, with exponent if required, etc.
2649   
2650   /* Here we have laid-out number in 'a' */
2651   // now apply 'before' and 'explaces' as needed
2652   if (before>0) 
2653    {
2654     // look for '.' or 'E'
2655     {int $11=a.length;p=0;p:for(;$11>0;$11--,p++){
2656      if (a[p]=='.') 
2657       break p;
2658      if (a[p]=='E') 
2659       break p;
2660      }
2661     }/*p*/
2662     // p is now offset of '.', 'E', or character after end of array
2663     // that is, the current length of before part
2664     if (p>before) 
2665      badarg("format",1,java.lang.String.valueOf(before)); // won't fit
2666     if (p<before) 
2667      { // need leading blanks
2668       newa=new char[(a.length+before)-p];
2669       {int $12=before-p;i=0;for(;$12>0;$12--,i++){
2670        newa[i]=' ';
2671        }
2672       }/*i*/
2673       java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,i,a.length);
2674       a=newa;
2675      }
2676    // [if p=before then it's just the right length]
2677    }
2678   
2679   if (explaces>0) 
2680    {
2681     // look for 'E' [cannot be at offset 0]
2682     {int $13=a.length-1;p=a.length-1;p:for(;$13>0;$13--,p--){
2683      if (a[p]=='E') 
2684       break p;
2685      }
2686     }/*p*/
2687     // p is now offset of 'E', or 0
2688     if (p==0) 
2689      { // no E part; add trailing blanks
2690       newa=new char[(a.length+explaces)+2];
2691       java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,a.length);
2692       {int $14=explaces+2;i=a.length;for(;$14>0;$14--,i++){
2693        newa[i]=' ';
2694        }
2695       }/*i*/
2696       a=newa;
2697      }
2698     else 
2699      {/* found E */ // may need to insert zeros
2700       places=(a.length-p)-2; // number so far
2701       if (places>explaces) 
2702        badarg("format",3,java.lang.String.valueOf(explaces));
2703       if (places<explaces) 
2704        { // need to insert zeros
2705         newa=new char[(a.length+explaces)-places];
2706         java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,p+2); // through E and sign
2707         {int $15=explaces-places;i=p+2;for(;$15>0;$15--,i++){
2708          newa[i]='0';
2709          }
2710         }/*i*/
2711         java.lang.System.arraycopy((java.lang.Object)a,p+2,(java.lang.Object)newa,i,places); // remainder of exponent
2712         a=newa;
2713        }
2714      // [if places=explaces then it's just the right length]
2715      }
2716    }
2717   return new java.lang.String(a);
2718   }
2719
2720  /**
2721   * Returns the hashcode for this <code>BigDecimal</code>.
2722   * This hashcode is suitable for use by the
2723   * <code>java.util.Hashtable</code> class.
2724   * <p>
2725   * Note that two <code>BigDecimal</code> objects are only guaranteed
2726   * to produce the same hashcode if they are exactly equal (that is,
2727   * the <code>String</code> representations of the
2728   * <code>BigDecimal</code> numbers are identical -- they have the same
2729   * characters in the same sequence).
2730   *
2731   * @return An <code>int</code> that is the hashcode for <code>this</code>.
2732   * @stable ICU 2.0
2733   */
2734  
2735  public int hashCode(){
2736   // Maybe calculate ourselves, later.  If so, note that there can be
2737   // more than one internal representation for a given toString() result.
2738   return this.toString().hashCode();
2739   }
2740
2741  /**
2742   * Converts this <code>BigDecimal</code> to an <code>int</code>.
2743   * If the <code>BigDecimal</code> has a non-zero decimal part it is
2744   * discarded. If the <code>BigDecimal</code> is out of the possible
2745   * range for an <code>int</code> (32-bit signed integer) result then
2746   * only the low-order 32 bits are used. (That is, the number may be
2747   * <i>decapitated</i>.)  To avoid unexpected errors when these
2748   * conditions occur, use the {@link #intValueExact} method.
2749   *
2750   * @return An <code>int</code> converted from <code>this</code>,
2751   *         truncated and decapitated if necessary.
2752   * @stable ICU 2.0
2753   */
2754  
2755  public int intValue(){
2756   return toBigInteger().intValue();
2757   }
2758
2759  /**
2760   * Converts this <code>BigDecimal</code> to an <code>int</code>.
2761   * If the <code>BigDecimal</code> has a non-zero decimal part or is
2762   * out of the possible range for an <code>int</code> (32-bit signed
2763   * integer) result then an <code>ArithmeticException</code> is thrown.
2764   *
2765   * @return An <code>int</code> equal in value to <code>this</code>.
2766   * @throws ArithmeticException if <code>this</code> has a non-zero
2767   *                 decimal part, or will not fit in an
2768   *                 <code>int</code>.
2769   * @stable ICU 2.0
2770   */
2771  
2772  public int intValueExact(){
2773   int lodigit;
2774   int useexp=0;
2775   int result;
2776   int i=0;
2777   int topdig=0;
2778   // This does not use longValueExact() as the latter can be much
2779   // slower.
2780   // intcheck (from pow) relies on this to check decimal part
2781   if (ind==iszero) 
2782    return 0; // easy, and quite common
2783   /* test and drop any trailing decimal part */
2784   lodigit=mant.length-1;
2785   if (exp<0) 
2786    {
2787     lodigit=lodigit+exp; // reduces by -(-exp)
2788     /* all decimal places must be 0 */
2789     if ((!(allzero(mant,lodigit+1)))) 
2790      throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
2791     if (lodigit<0) 
2792      return 0; // -1<this<1
2793     useexp=0;
2794    }
2795   else 
2796    {/* >=0 */
2797     if ((exp+lodigit)>9)  // early exit
2798      throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
2799     useexp=exp;
2800    }
2801   /* convert the mantissa to binary, inline for speed */
2802   result=0;
2803   {int $16=lodigit+useexp;i=0;for(;i<=$16;i++){
2804    result=result*10;
2805    if (i<=lodigit) 
2806     result=result+mant[i];
2807    }
2808   }/*i*/
2809   
2810   /* Now, if the risky length, check for overflow */
2811   if ((lodigit+useexp)==9) 
2812    {
2813     // note we cannot just test for -ve result, as overflow can move a
2814     // zero into the top bit [consider 5555555555]
2815     topdig=result/1000000000; // get top digit, preserving sign
2816     if (topdig!=mant[0]) 
2817      { // digit must match and be positive
2818       // except in the special case ...
2819       if (result==java.lang.Integer.MIN_VALUE)  // looks like the special
2820        if (ind==isneg)  // really was negative
2821         if (mant[0]==2) 
2822          return result; // really had top digit 2
2823       throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
2824      }
2825    }
2826   
2827   /* Looks good */
2828   if (ind==ispos) 
2829    return result;
2830   return (int)-result;
2831   }
2832
2833  /**
2834   * Converts this <code>BigDecimal</code> to a <code>long</code>.
2835   * If the <code>BigDecimal</code> has a non-zero decimal part it is
2836   * discarded. If the <code>BigDecimal</code> is out of the possible
2837   * range for a <code>long</code> (64-bit signed integer) result then
2838   * only the low-order 64 bits are used. (That is, the number may be
2839   * <i>decapitated</i>.)  To avoid unexpected errors when these
2840   * conditions occur, use the {@link #longValueExact} method.
2841   *
2842   * @return A <code>long</code> converted from <code>this</code>,
2843   *         truncated and decapitated if necessary.
2844   * @stable ICU 2.0
2845   */
2846  
2847  public long longValue(){
2848   return toBigInteger().longValue();
2849   }
2850
2851  /**
2852   * Converts this <code>BigDecimal</code> to a <code>long</code>.
2853   * If the <code>BigDecimal</code> has a non-zero decimal part or is
2854   * out of the possible range for a <code>long</code> (64-bit signed
2855   * integer) result then an <code>ArithmeticException</code> is thrown.
2856   *
2857   * @return A <code>long</code> equal in value to <code>this</code>.
2858   * @throws ArithmeticException if <code>this</code> has a non-zero
2859   *                 decimal part, or will not fit in a
2860   *                 <code>long</code>.
2861   * @stable ICU 2.0
2862   */
2863  
2864  public long longValueExact(){
2865   int lodigit;
2866   int cstart=0;
2867   int useexp=0;
2868   long result;
2869   int i=0;
2870   long topdig=0;
2871   // Identical to intValueExact except for result=long, and exp>=20 test
2872   if (ind==0) 
2873    return 0; // easy, and quite common
2874   lodigit=mant.length-1; // last included digit
2875   if (exp<0) 
2876    {
2877     lodigit=lodigit+exp; // -(-exp)
2878     /* all decimal places must be 0 */
2879     if (lodigit<0) 
2880      cstart=0;
2881     else 
2882      cstart=lodigit+1;
2883     if ((!(allzero(mant,cstart)))) 
2884      throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
2885     if (lodigit<0) 
2886      return 0; // -1<this<1
2887     useexp=0;
2888    }
2889   else 
2890    {/* >=0 */
2891     if ((exp+mant.length)>18)  // early exit
2892      throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
2893     useexp=exp;
2894    }
2895   
2896   /* convert the mantissa to binary, inline for speed */
2897   // note that we could safely use the 'test for wrap to negative'
2898   // algorithm here, but instead we parallel the intValueExact
2899   // algorithm for ease of checking and maintenance.
2900   result=(long)0;
2901   {int $17=lodigit+useexp;i=0;for(;i<=$17;i++){
2902    result=result*10;
2903    if (i<=lodigit) 
2904     result=result+mant[i];
2905    }
2906   }/*i*/
2907   
2908   /* Now, if the risky length, check for overflow */
2909   if ((lodigit+useexp)==18) 
2910    {
2911     topdig=result/1000000000000000000L; // get top digit, preserving sign
2912     if (topdig!=mant[0]) 
2913      { // digit must match and be positive
2914       // except in the special case ...
2915       if (result==java.lang.Long.MIN_VALUE)  // looks like the special
2916        if (ind==isneg)  // really was negative
2917         if (mant[0]==9) 
2918          return result; // really had top digit 9
2919       throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
2920      }
2921    }
2922   
2923   /* Looks good */
2924   if (ind==ispos) 
2925    return result;
2926   return (long)-result;
2927   }
2928
2929  /**
2930   * Returns a plain <code>BigDecimal</code> whose decimal point has
2931   * been moved to the left by a specified number of positions.
2932   * The parameter, <code>n</code>, specifies the number of positions to
2933   * move the decimal point.
2934   * That is, if <code>n</code> is 0 or positive, the number returned is
2935   * given by:
2936   * <p><code>
2937   * this.multiply(TEN.pow(new BigDecimal(-n)))
2938   * </code>
2939   * <p>
2940   * <code>n</code> may be negative, in which case the method returns
2941   * the same result as <code>movePointRight(-n)</code>.
2942   *
2943   * @param  n The <code>int</code> specifying the number of places to
2944   *           move the decimal point leftwards.
2945   * @return   A <code>BigDecimal</code> derived from
2946   *           <code>this</code>, with the decimal point moved
2947   *           <code>n</code> places to the left.
2948   * @stable ICU 2.0
2949   */
2950  
2951  public com.ibm.icu.math.BigDecimal movePointLeft(int n){
2952   com.ibm.icu.math.BigDecimal res;
2953   // very little point in optimizing for shift of 0
2954   res=clone(this);
2955   res.exp=res.exp-n;
2956   return res.finish(plainMC,false); // finish sets form and checks exponent
2957   }
2958
2959  /**
2960   * Returns a plain <code>BigDecimal</code> whose decimal point has
2961   * been moved to the right by a specified number of positions.
2962   * The parameter, <code>n</code>, specifies the number of positions to
2963   * move the decimal point.
2964   * That is, if <code>n</code> is 0 or positive, the number returned is
2965   * given by:
2966   * <p><code>
2967   * this.multiply(TEN.pow(new BigDecimal(n)))
2968   * </code>
2969   * <p>
2970   * <code>n</code> may be negative, in which case the method returns
2971   * the same result as <code>movePointLeft(-n)</code>.
2972   *
2973   * @param  n The <code>int</code> specifying the number of places to
2974   *           move the decimal point rightwards.
2975   * @return   A <code>BigDecimal</code> derived from
2976   *           <code>this</code>, with the decimal point moved
2977   *           <code>n</code> places to the right.
2978   * @stable ICU 2.0
2979   */
2980  
2981  public com.ibm.icu.math.BigDecimal movePointRight(int n){
2982   com.ibm.icu.math.BigDecimal res;
2983   res=clone(this);
2984   res.exp=res.exp+n;
2985   return res.finish(plainMC,false);
2986   }
2987
2988  /**
2989   * Returns the scale of this <code>BigDecimal</code>.
2990   * Returns a non-negative <code>int</code> which is the scale of the
2991   * number. The scale is the number of digits in the decimal part of
2992   * the number if the number were formatted without exponential
2993   * notation.
2994   *
2995   * @return An <code>int</code> whose value is the scale of this
2996   *         <code>BigDecimal</code>.
2997   * @stable ICU 2.0
2998   */
2999  
3000  public int scale(){
3001   if (exp>=0) 
3002    return 0; // scale can never be negative
3003   return (int)-exp;
3004   }
3005
3006  /**
3007   * Returns a plain <code>BigDecimal</code> with a given scale.
3008   * <p>
3009   * If the given scale (which must be zero or positive) is the same as
3010   * or greater than the length of the decimal part (the scale) of this
3011   * <code>BigDecimal</code> then trailing zeros will be added to the
3012   * decimal part as necessary.
3013   * <p>
3014   * If the given scale is less than the length of the decimal part (the
3015   * scale) of this <code>BigDecimal</code> then trailing digits
3016   * will be removed, and in this case an
3017   * <code>ArithmeticException</code> is thrown if any discarded digits
3018   * are non-zero.
3019   * <p>
3020   * The same as {@link #setScale(int, int)}, where the first parameter
3021   * is the scale, and the second is
3022   * <code>MathContext.ROUND_UNNECESSARY</code>.
3023   *
3024   * @param  scale The <code>int</code> specifying the scale of the
3025   *               resulting <code>BigDecimal</code>.
3026   * @return       A plain <code>BigDecimal</code> with the given scale.
3027   * @throws ArithmeticException if <code>scale</code> is negative.
3028   * @throws ArithmeticException if reducing scale would discard
3029   *               non-zero digits.
3030   * @stable ICU 2.0
3031   */
3032  
3033  public com.ibm.icu.math.BigDecimal setScale(int scale){
3034   return setScale(scale,ROUND_UNNECESSARY);
3035   }
3036
3037  /**
3038   * Returns a plain <code>BigDecimal</code> with a given scale.
3039   * <p>
3040   * If the given scale (which must be zero or positive) is the same as
3041   * or greater than the length of the decimal part (the scale) of this
3042   * <code>BigDecimal</code> then trailing zeros will be added to the
3043   * decimal part as necessary.
3044   * <p>
3045   * If the given scale is less than the length of the decimal part (the
3046   * scale) of this <code>BigDecimal</code> then trailing digits
3047   * will be removed, and the rounding mode given by the second
3048   * parameter is used to determine if the remaining digits are
3049   * affected by a carry.
3050   * In this case, an <code>IllegalArgumentException</code> is thrown if
3051   * <code>round</code> is not a valid rounding mode.
3052   * <p>
3053   * If <code>round</code> is <code>MathContext.ROUND_UNNECESSARY</code>,
3054   * an <code>ArithmeticException</code> is thrown if any discarded
3055   * digits are non-zero.
3056   *
3057   * @param  scale The <code>int</code> specifying the scale of the
3058   *               resulting <code>BigDecimal</code>.
3059   * @param  round The <code>int</code> rounding mode to be used for
3060   *               the division (see the {@link MathContext} class).
3061   * @return       A plain <code>BigDecimal</code> with the given scale.
3062   * @throws IllegalArgumentException if <code>round</code> is not a
3063   *               valid rounding mode.
3064   * @throws ArithmeticException if <code>scale</code> is negative.
3065   * @throws ArithmeticException if <code>round</code> is
3066   *               <code>MathContext.ROUND_UNNECESSARY</code>, and
3067   *               reducing scale would discard non-zero digits.
3068   * @stable ICU 2.0
3069   */
3070  
3071  public com.ibm.icu.math.BigDecimal setScale(int scale,int round){
3072   int ourscale;
3073   com.ibm.icu.math.BigDecimal res;
3074   int padding=0;
3075   int newlen=0;
3076   // at present this naughtily only checks the round value if it is
3077   // needed (used), for speed
3078   ourscale=this.scale();
3079   if (ourscale==scale)  // already correct scale
3080    if (this.form==com.ibm.icu.math.MathContext.PLAIN)  // .. and form
3081     return this;
3082   res=clone(this); // need copy
3083   if (ourscale<=scale) 
3084    { // simply zero-padding/changing form
3085     // if ourscale is 0 we may have lots of 0s to add
3086     if (ourscale==0) 
3087      padding=res.exp+scale;
3088     else 
3089      padding=scale-ourscale;
3090     res.mant=extend(res.mant,res.mant.length+padding);
3091     res.exp=(int)-scale; // as requested
3092    }
3093   else 
3094    {/* ourscale>scale: shortening, probably */
3095     if (scale<0) 
3096      throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
3097     // [round() will raise exception if invalid round]
3098     newlen=res.mant.length-((ourscale-scale)); // [<=0 is OK]
3099     res=res.round(newlen,round); // round to required length
3100     // This could have shifted left if round (say) 0.9->1[.0]
3101     // Repair if so by adding a zero and reducing exponent
3102     if (res.exp!=((int)-scale)) 
3103      {
3104       res.mant=extend(res.mant,res.mant.length+1);
3105       res.exp=res.exp-1;
3106      }
3107    }
3108   res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // by definition
3109   return res;
3110   }
3111
3112  /**
3113   * Converts this <code>BigDecimal</code> to a <code>short</code>.
3114   * If the <code>BigDecimal</code> has a non-zero decimal part or is
3115   * out of the possible range for a <code>short</code> (16-bit signed
3116   * integer) result then an <code>ArithmeticException</code> is thrown.
3117   *
3118   * @return A <code>short</code> equal in value to <code>this</code>.
3119   * @throws ArithmeticException if <code>this</code> has a non-zero
3120   *                 decimal part, or will not fit in a
3121   *                 <code>short</code>.
3122   * @stable ICU 2.0
3123   */
3124  
3125  public short shortValueExact(){
3126   int num;
3127   num=this.intValueExact(); // will check decimal part too
3128   if ((num>32767)|(num<(-32768))) 
3129    throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
3130   return (short)num;
3131   }
3132
3133  /**
3134   * Returns the sign of this <code>BigDecimal</code>, as an
3135   * <code>int</code>.
3136   * This returns the <i>signum</i> function value that represents the
3137   * sign of this <code>BigDecimal</code>.
3138   * That is, -1 if the <code>BigDecimal</code> is negative, 0 if it is
3139   * numerically equal to zero, or 1 if it is positive.
3140   *
3141   * @return An <code>int</code> which is -1 if the
3142   *         <code>BigDecimal</code> is negative, 0 if it is
3143   *         numerically equal to zero, or 1 if it is positive.
3144   * @stable ICU 2.0
3145   */
3146  
3147  public int signum(){
3148   return (int)this.ind; // [note this assumes values for ind.]
3149   }
3150
3151 //#if defined(FOUNDATION10)
3152 //#else
3153  /**
3154   * Converts this <code>BigDecimal</code> to a
3155   * <code>java.math.BigDecimal</code>.
3156   * <p>
3157   * This is an exact conversion; the result is the same as if the
3158   * <code>BigDecimal</code> were formatted as a plain number without
3159   * any rounding or exponent and then the
3160   * <code>java.math.BigDecimal(java.lang.String)</code> constructor
3161   * were used to construct the result.
3162   * <p>
3163   * <i>(Note: this method is provided only in the
3164   * <code>com.ibm.icu.math</code> version of the BigDecimal class.
3165   * It would not be present in a <code>java.math</code> version.)</i>
3166   *
3167   * @return The <code>java.math.BigDecimal</code> equal in value
3168   *         to this <code>BigDecimal</code>.
3169   * @stable ICU 2.0
3170   */
3171  
3172  public java.math.BigDecimal toBigDecimal(){
3173   return new java.math.BigDecimal(this.unscaledValue(),this.scale());
3174   }
3175 //#endif
3176
3177  /**
3178   * Converts this <code>BigDecimal</code> to a
3179   * <code>java.math.BigInteger</code>.
3180   * <p>
3181   * Any decimal part is truncated (discarded).
3182   * If an exception is desired should the decimal part be non-zero,
3183   * use {@link #toBigIntegerExact()}.
3184   *
3185   * @return The <code>java.math.BigInteger</code> equal in value
3186   *         to the integer part of this <code>BigDecimal</code>.
3187   * @stable ICU 2.0
3188   */
3189  
3190  public java.math.BigInteger toBigInteger(){
3191   com.ibm.icu.math.BigDecimal res=null;
3192   int newlen=0;
3193   byte newmant[]=null;
3194   {/*select*/
3195   if ((exp>=0)&(form==com.ibm.icu.math.MathContext.PLAIN))
3196    res=this; // can layout simply
3197   else if (exp>=0)
3198    {
3199     res=clone(this); // safe copy
3200     res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // .. and request PLAIN
3201    }
3202   else{
3203    { // exp<0; scale to be truncated
3204     // we could use divideInteger, but we may as well be quicker
3205     if (((int)-this.exp)>=this.mant.length) 
3206      res=ZERO; // all blows away
3207     else 
3208      {
3209       res=clone(this); // safe copy
3210       newlen=res.mant.length+res.exp;
3211       newmant=new byte[newlen]; // [shorter]
3212       java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,newlen);
3213       res.mant=newmant;
3214       res.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
3215       res.exp=0;
3216      }
3217    }
3218   }
3219   }
3220   return new BigInteger(new java.lang.String(res.layout()));
3221   }
3222
3223  /**
3224   * Converts this <code>BigDecimal</code> to a
3225   * <code>java.math.BigInteger</code>.
3226   * <p>
3227   * An exception is thrown if the decimal part (if any) is non-zero.
3228   *
3229   * @return The <code>java.math.BigInteger</code> equal in value
3230   *         to the integer part of this <code>BigDecimal</code>.
3231   * @throws ArithmeticException if <code>this</code> has a non-zero
3232   *         decimal part.
3233   * @stable ICU 2.0
3234   */
3235  
3236  public java.math.BigInteger toBigIntegerExact(){
3237   /* test any trailing decimal part */
3238   if (exp<0) 
3239    { // possible decimal part
3240     /* all decimal places must be 0; note exp<0 */
3241     if ((!(allzero(mant,mant.length+exp)))) 
3242      throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
3243    }
3244   return toBigInteger();
3245   }
3246
3247  /**
3248   * Returns the <code>BigDecimal</code> as a character array.
3249   * The result of this method is the same as using the
3250   * sequence <code>toString().toCharArray()</code>, but avoids creating
3251   * the intermediate <code>String</code> and <code>char[]</code>
3252   * objects.
3253   *
3254   * @return The <code>char[]</code> array corresponding to this
3255   *         <code>BigDecimal</code>.
3256   * @stable ICU 2.0
3257   */
3258  
3259  public char[] toCharArray(){
3260   return layout();
3261   }
3262
3263  /**
3264   * Returns the <code>BigDecimal</code> as a <code>String</code>.
3265   * This returns a <code>String</code> that exactly represents this
3266   * <code>BigDecimal</code>, as defined in the decimal documentation
3267   * (see {@link BigDecimal class header}).
3268   * <p>
3269   * By definition, using the {@link #BigDecimal(String)} constructor
3270   * on the result <code>String</code> will create a
3271   * <code>BigDecimal</code> that is exactly equal to the original
3272   * <code>BigDecimal</code>.
3273   *
3274   * @return The <code>String</code> exactly corresponding to this
3275   *         <code>BigDecimal</code>.
3276   * @see    #format(int, int)
3277   * @see    #format(int, int, int, int, int, int)
3278   * @see    #toCharArray()
3279   * @stable ICU 2.0
3280   */
3281  
3282  public java.lang.String toString(){
3283   return new java.lang.String(layout());
3284   }
3285
3286  /**
3287   * Returns the number as a <code>BigInteger</code> after removing the
3288   * scale.
3289   * That is, the number is expressed as a plain number, any decimal
3290   * point is then removed (retaining the digits of any decimal part),
3291   * and the result is then converted to a <code>BigInteger</code>.
3292   *
3293   * @return The <code>java.math.BigInteger</code> equal in value to
3294   *         this <code>BigDecimal</code> multiplied by ten to the
3295   *         power of <code>this.scale()</code>.
3296   * @stable ICU 2.0
3297   */
3298  
3299  public java.math.BigInteger unscaledValue(){
3300   com.ibm.icu.math.BigDecimal res=null;
3301   if (exp>=0) 
3302    res=this;
3303   else 
3304    {
3305     res=clone(this); // safe copy
3306     res.exp=0; // drop scale
3307    }
3308   return res.toBigInteger();
3309   }
3310
3311  /**
3312   * Translates a <code>double</code> to a <code>BigDecimal</code>.
3313   * <p>
3314   * Returns a <code>BigDecimal</code> which is the decimal
3315   * representation of the 64-bit signed binary floating point
3316   * parameter. If the parameter is infinite, or is not a number (NaN),
3317   * a <code>NumberFormatException</code> is thrown.
3318   * <p>
3319   * The number is constructed as though <code>num</code> had been
3320   * converted to a <code>String</code> using the
3321   * <code>Double.toString()</code> method and the
3322   * {@link #BigDecimal(java.lang.String)} constructor had then been used.
3323   * This is typically not an exact conversion.
3324   *
3325   * @param  dub The <code>double</code> to be translated.
3326   * @return     The <code>BigDecimal</code> equal in value to
3327   *             <code>dub</code>.
3328   * @throws NumberFormatException if the parameter is infinite or
3329   *             not a number.
3330   * @stable ICU 2.0
3331   */
3332  
3333  public static com.ibm.icu.math.BigDecimal valueOf(double dub){
3334   // Reminder: a zero double returns '0.0', so we cannot fastpath to
3335   // use the constant ZERO.  This might be important enough to justify
3336   // a factory approach, a cache, or a few private constants, later.
3337   return new com.ibm.icu.math.BigDecimal((new java.lang.Double(dub)).toString());
3338   }
3339
3340  /**
3341   * Translates a <code>long</code> to a <code>BigDecimal</code>.
3342   * That is, returns a plain <code>BigDecimal</code> whose value is
3343   * equal to the given <code>long</code>.
3344   *
3345   * @param  lint The <code>long</code> to be translated.
3346   * @return      The <code>BigDecimal</code> equal in value to
3347   *              <code>lint</code>.
3348   * @stable ICU 2.0
3349   */
3350  
3351  public static com.ibm.icu.math.BigDecimal valueOf(long lint){
3352   return valueOf(lint,0);
3353   }
3354
3355  /**
3356   * Translates a <code>long</code> to a <code>BigDecimal</code> with a
3357   * given scale.
3358   * That is, returns a plain <code>BigDecimal</code> whose unscaled
3359   * value is equal to the given <code>long</code>, adjusted by the
3360   * second parameter, <code>scale</code>.
3361   * <p>
3362   * The result is given by:
3363   * <p><code>
3364   * (new BigDecimal(lint)).divide(TEN.pow(new BigDecimal(scale)))
3365   * </code>
3366   * <p>
3367   * A <code>NumberFormatException</code> is thrown if <code>scale</code>
3368   * is negative.
3369   *
3370   * @param  lint  The <code>long</code> to be translated.
3371   * @param  scale The <code>int</code> scale to be applied.
3372   * @return       The <code>BigDecimal</code> equal in value to
3373   *               <code>lint</code>.
3374   * @throws NumberFormatException if the scale is negative.
3375   * @stable ICU 2.0
3376   */
3377  
3378  public static com.ibm.icu.math.BigDecimal valueOf(long lint,int scale){
3379   com.ibm.icu.math.BigDecimal res=null;
3380   {/*select*/
3381   if (lint==0)
3382    res=ZERO;
3383   else if (lint==1)
3384    res=ONE;
3385   else if (lint==10)
3386    res=TEN;
3387   else{
3388    res=new com.ibm.icu.math.BigDecimal(lint);
3389   }
3390   }
3391   if (scale==0) 
3392    return res;
3393   if (scale<0) 
3394    throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
3395   res=clone(res); // safe copy [do not mutate]
3396   res.exp=(int)-scale; // exponent is -scale
3397   return res;
3398   }
3399
3400  /* ---------------------------------------------------------------- */
3401  /* Private methods                                                  */
3402  /* ---------------------------------------------------------------- */
3403  
3404  /* <sgml> Return char array value of a BigDecimal (conversion from
3405        BigDecimal to laid-out canonical char array).
3406     <p>The mantissa will either already have been rounded (following an
3407        operation) or will be of length appropriate (in the case of
3408        construction from an int, for example).
3409     <p>We must not alter the mantissa, here.
3410     <p>'form' describes whether we are to use exponential notation (and
3411        if so, which), or if we are to lay out as a plain/pure numeric.
3412     </sgml> */
3413  
3414  private char[] layout(){
3415   char cmant[];
3416   int i=0;
3417   java.lang.StringBuffer sb=null;
3418   int euse=0;
3419   int sig=0;
3420   char csign=0;
3421   char rec[]=null;
3422   int needsign;
3423   int mag;
3424   int len=0;
3425   cmant=new char[mant.length]; // copy byte[] to a char[]
3426   {int $18=mant.length;i=0;for(;$18>0;$18--,i++){
3427    cmant[i]=(char)(mant[i]+((int)('0')));
3428    }
3429   }/*i*/
3430   
3431   if (form!=com.ibm.icu.math.MathContext.PLAIN) 
3432    {/* exponential notation needed */
3433     sb=new java.lang.StringBuffer(cmant.length+15); // -x.xxxE+999999999
3434     if (ind==isneg) 
3435      sb.append('-');
3436     euse=(exp+cmant.length)-1; // exponent to use
3437     /* setup sig=significant digits and copy to result */
3438     if (form==com.ibm.icu.math.MathContext.SCIENTIFIC) 
3439      { // [default]
3440       sb.append(cmant[0]); // significant character
3441       if (cmant.length>1)  // have decimal part
3442        sb.append('.').append(cmant,1,cmant.length-1);
3443      }
3444     else 
3445      {do{
3446       sig=euse%3; // common
3447       if (sig<0) 
3448        sig=3+sig; // negative exponent
3449       euse=euse-sig;
3450       sig++;
3451       if (sig>=cmant.length) 
3452        { // zero padding may be needed
3453         sb.append(cmant,0,cmant.length);
3454         {int $19=sig-cmant.length;for(;$19>0;$19--){
3455          sb.append('0');
3456          }
3457         }
3458        }
3459       else 
3460        { // decimal point needed
3461         sb.append(cmant,0,sig).append('.').append(cmant,sig,cmant.length-sig);
3462        }
3463      }while(false);}/*engineering*/
3464     if (euse!=0) 
3465      {
3466       if (euse<0) 
3467        {
3468         csign='-';
3469         euse=(int)-euse;
3470        }
3471       else 
3472        csign='+';
3473       sb.append('E').append(csign).append(euse);
3474      }
3475     rec=new char[sb.length()];
3476     Utility.getChars(sb, 0,sb.length(),rec,0);
3477     return rec;
3478    }
3479   
3480   /* Here for non-exponential (plain) notation */
3481   if (exp==0) 
3482    {/* easy */
3483     if (ind>=0) 
3484      return cmant; // non-negative integer
3485     rec=new char[cmant.length+1];
3486     rec[0]='-';
3487     java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,1,cmant.length);
3488     return rec;
3489    }
3490   
3491   /* Need a '.' and/or some zeros */
3492   needsign=(int)((ind==isneg)?1:0); // space for sign?  0 or 1
3493   
3494   /* MAG is the position of the point in the mantissa (index of the
3495      character it follows) */
3496   mag=exp+cmant.length;
3497   
3498   if (mag<1) 
3499    {/* 0.00xxxx form */
3500     len=(needsign+2)-exp; // needsign+2+(-mag)+cmant.length
3501     rec=new char[len];
3502     if (needsign!=0) 
3503      rec[0]='-';
3504     rec[needsign]='0';
3505     rec[needsign+1]='.';
3506     {int $20=(int)-mag;i=needsign+2;for(;$20>0;$20--,i++){ // maybe none
3507      rec[i]='0';
3508      }
3509     }/*i*/
3510     java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,(needsign+2)-mag,cmant.length);
3511     return rec;
3512    }
3513   
3514   if (mag>cmant.length) 
3515    {/* xxxx0000 form */
3516     len=needsign+mag;
3517     rec=new char[len];
3518     if (needsign!=0) 
3519      rec[0]='-';
3520     java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,cmant.length);
3521     {int $21=mag-cmant.length;i=needsign+cmant.length;for(;$21>0;$21--,i++){ // never 0
3522      rec[i]='0';
3523      }
3524     }/*i*/
3525     return rec;
3526    }
3527   
3528   /* decimal point is in the middle of the mantissa */
3529   len=(needsign+1)+cmant.length;
3530   rec=new char[len];
3531   if (needsign!=0) 
3532    rec[0]='-';
3533   java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,mag);
3534   rec[needsign+mag]='.';
3535   java.lang.System.arraycopy((java.lang.Object)cmant,mag,(java.lang.Object)rec,(needsign+mag)+1,cmant.length-mag);
3536   return rec;
3537   }
3538
3539  /* <sgml> Checks a BigDecimal argument to ensure it's a true integer
3540        in a given range.
3541     <p>If OK, returns it as an int. </sgml> */
3542  // [currently only used by pow]
3543  
3544  private int intcheck(int min,int max){
3545   int i;
3546   i=this.intValueExact(); // [checks for non-0 decimal part]
3547   // Use same message as though intValueExact failed due to size
3548   if ((i<min)|(i>max)) 
3549    throw new java.lang.ArithmeticException("Conversion overflow:"+" "+i);
3550   return i;
3551   }
3552
3553  /* <sgml> Carry out division operations. </sgml> */
3554  /*
3555     Arg1 is operation code: D=divide, I=integer divide, R=remainder
3556     Arg2 is the rhs.
3557     Arg3 is the context.
3558     Arg4 is explicit scale iff code='D' or 'I' (-1 if none).
3559  
3560     Underlying algorithm (complications for Remainder function and
3561     scaled division are omitted for clarity):
3562  
3563       Test for x/0 and then 0/x
3564       Exp =Exp1 - Exp2
3565       Exp =Exp +len(var1) -len(var2)
3566       Sign=Sign1 * Sign2
3567       Pad accumulator (Var1) to double-length with 0's (pad1)
3568       Pad Var2 to same length as Var1
3569       B2B=1st two digits of var2, +1 to allow for roundup
3570       have=0
3571       Do until (have=digits+1 OR residue=0)
3572         if exp<0 then if integer divide/residue then leave
3573         this_digit=0
3574         Do forever
3575            compare numbers
3576            if <0 then leave inner_loop
3577            if =0 then (- quick exit without subtract -) do
3578               this_digit=this_digit+1; output this_digit
3579               leave outer_loop; end
3580            Compare lengths of numbers (mantissae):
3581            If same then CA=first_digit_of_Var1
3582                    else CA=first_two_digits_of_Var1
3583            mult=ca*10/b2b   -- Good and safe guess at divisor
3584            if mult=0 then mult=1
3585            this_digit=this_digit+mult
3586            subtract
3587            end inner_loop
3588          if have\=0 | this_digit\=0 then do
3589            output this_digit
3590            have=have+1; end
3591          var2=var2/10
3592          exp=exp-1
3593          end outer_loop
3594       exp=exp+1   -- set the proper exponent
3595       if have=0 then generate answer=0
3596       Return to FINISHED
3597       Result defined by MATHV1
3598  
3599     For extended commentary, see DMSRCN.
3600   */
3601  
3602  private com.ibm.icu.math.BigDecimal dodivide(char code,com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set,int scale){
3603   com.ibm.icu.math.BigDecimal lhs;
3604   int reqdig;
3605   int newexp;
3606   com.ibm.icu.math.BigDecimal res;
3607   int newlen;
3608   byte var1[];
3609   int var1len;
3610   byte var2[];
3611   int var2len;
3612   int b2b;
3613   int have;
3614   int thisdigit=0;
3615   int i=0;
3616   byte v2=0;
3617   int ba=0;
3618   int mult=0;
3619   int start=0;
3620   int padding=0;
3621   int d=0;
3622   byte newvar1[]=null;
3623   byte lasthave=0;
3624   int actdig=0;
3625   byte newmant[]=null;
3626   
3627   if (set.lostDigits) 
3628    checkdigits(rhs,set.digits);
3629   lhs=this; // name for clarity
3630   
3631   // [note we must have checked lostDigits before the following checks]
3632   if (rhs.ind==0) 
3633    throw new java.lang.ArithmeticException("Divide by 0"); // includes 0/0
3634   if (lhs.ind==0) 
3635    { // 0/x => 0 [possibly with .0s]
3636     if (set.form!=com.ibm.icu.math.MathContext.PLAIN) 
3637      return ZERO;
3638     if (scale==(-1)) 
3639      return lhs;
3640     return lhs.setScale(scale);
3641    }
3642   
3643   /* Prepare numbers according to BigDecimal rules */
3644   reqdig=set.digits; // local copy (heavily used)
3645   if (reqdig>0) 
3646    {
3647     if (lhs.mant.length>reqdig) 
3648      lhs=clone(lhs).round(set);
3649     if (rhs.mant.length>reqdig) 
3650      rhs=clone(rhs).round(set);
3651    }
3652   else 
3653    {/* scaled divide */
3654     if (scale==(-1)) 
3655      scale=lhs.scale();
3656     // set reqdig to be at least large enough for the computation
3657     reqdig=lhs.mant.length; // base length
3658     // next line handles both positive lhs.exp and also scale mismatch
3659     if (scale!=((int)-lhs.exp)) 
3660      reqdig=(reqdig+scale)+lhs.exp;
3661     reqdig=(reqdig-((rhs.mant.length-1)))-rhs.exp; // reduce by RHS effect
3662     if (reqdig<lhs.mant.length) 
3663      reqdig=lhs.mant.length; // clamp
3664     if (reqdig<rhs.mant.length) 
3665      reqdig=rhs.mant.length; // ..
3666    }
3667   
3668   /* precalculate exponent */
3669   newexp=((lhs.exp-rhs.exp)+lhs.mant.length)-rhs.mant.length;
3670   /* If new exponent -ve, then some quick exits are possible */
3671   if (newexp<0) 
3672    if (code!='D') 
3673     {
3674      if (code=='I') 
3675       return ZERO; // easy - no integer part
3676      /* Must be 'R'; remainder is [finished clone of] input value */
3677      return clone(lhs).finish(set,false);
3678     }
3679   
3680   /* We need slow division */
3681   res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
3682   res.ind=(byte)(lhs.ind*rhs.ind); // final sign (for D/I)
3683   res.exp=newexp; // initial exponent (for D/I)
3684   res.mant=new byte[reqdig+1]; // where build the result
3685   
3686   /* Now [virtually pad the mantissae with trailing zeros */
3687   // Also copy the LHS, which will be our working array
3688   newlen=(reqdig+reqdig)+1;
3689   var1=extend(lhs.mant,newlen); // always makes longer, so new safe array
3690   var1len=newlen; // [remaining digits are 0]
3691   
3692   var2=rhs.mant;
3693   var2len=newlen;
3694   
3695   /* Calculate first two digits of rhs (var2), +1 for later estimations */
3696   b2b=(var2[0]*10)+1;
3697   if (var2.length>1) 
3698    b2b=b2b+var2[1];
3699   
3700   /* start the long-division loops */
3701   have=0;
3702   {outer:for(;;){
3703    thisdigit=0;
3704    /* find the next digit */
3705    {inner:for(;;){
3706     if (var1len<var2len) 
3707      break inner; // V1 too low
3708     if (var1len==var2len) 
3709      { // compare needed
3710       {compare:do{ // comparison
3711        {int $22=var1len;i=0;for(;$22>0;$22--,i++){
3712         // var1len is always <= var1.length
3713         if (i<var2.length) 
3714          v2=var2[i];
3715         else 
3716          v2=(byte)0;
3717         if (var1[i]<v2) 
3718          break inner; // V1 too low
3719         if (var1[i]>v2) 
3720          break compare; // OK to subtract
3721         }
3722        }/*i*/
3723        /* reach here if lhs and rhs are identical; subtraction will
3724           increase digit by one, and the residue will be 0 so we
3725           are done; leave the loop with residue set to 0 (in case
3726           code is 'R' or ROUND_UNNECESSARY or a ROUND_HALF_xxxx is
3727           being checked) */
3728        thisdigit++;
3729        res.mant[have]=(byte)thisdigit;
3730        have++;
3731        var1[0]=(byte)0; // residue to 0 [this is all we'll test]
3732        // var1len=1      -- [optimized out]
3733        break outer;
3734       }while(false);}/*compare*/
3735       /* prepare for subtraction.  Estimate BA (lengths the same) */
3736       ba=(int)var1[0]; // use only first digit
3737      } // lengths the same
3738     else 
3739      {/* lhs longer than rhs */
3740       /* use first two digits for estimate */
3741       ba=var1[0]*10;
3742       if (var1len>1) 
3743        ba=ba+var1[1];
3744      }
3745     /* subtraction needed; V1>=V2 */
3746     mult=(ba*10)/b2b;
3747     if (mult==0) 
3748      mult=1;
3749     thisdigit=thisdigit+mult;
3750     // subtract; var1 reusable
3751     var1=byteaddsub(var1,var1len,var2,var2len,(int)-mult,true);
3752     if (var1[0]!=0) 
3753      continue inner; // maybe another subtract needed
3754     /* V1 now probably has leading zeros, remove leading 0's and try
3755        again. (It could be longer than V2) */
3756     {int $23=var1len-2;start=0;start:for(;start<=$23;start++){
3757      if (var1[start]!=0) 
3758       break start;
3759      var1len--;
3760      }
3761     }/*start*/
3762     if (start==0) 
3763      continue inner;
3764     // shift left
3765     java.lang.System.arraycopy((java.lang.Object)var1,start,(java.lang.Object)var1,0,var1len);
3766     }
3767    }/*inner*/
3768    
3769    /* We have the next digit */
3770    if ((have!=0)|(thisdigit!=0)) 
3771     { // put the digit we got
3772      res.mant[have]=(byte)thisdigit;
3773      have++;
3774      if (have==(reqdig+1)) 
3775       break outer; // we have all we need
3776      if (var1[0]==0) 
3777       break outer; // residue now 0
3778     }
3779    /* can leave now if a scaled divide and exponent is small enough */
3780    if (scale>=0) 
3781     if (((int)-res.exp)>scale) 
3782      break outer;
3783    /* can leave now if not Divide and no integer part left  */
3784    if (code!='D') 
3785     if (res.exp<=0) 
3786      break outer;
3787    res.exp=res.exp-1; // reduce the exponent
3788    /* to get here, V1 is less than V2, so divide V2 by 10 and go for
3789       the next digit */
3790    var2len--;
3791    }
3792   }/*outer*/
3793   
3794   /* here when we have finished dividing, for some reason */
3795   // have is the number of digits we collected in res.mant
3796   if (have==0) 
3797    have=1; // res.mant[0] is 0; we always want a digit
3798   
3799   if ((code=='I')|(code=='R')) 
3800    {/* check for integer overflow needed */
3801     if ((have+res.exp)>reqdig) 
3802      throw new java.lang.ArithmeticException("Integer overflow");
3803     
3804     if (code=='R') 
3805      {do{
3806       /* We were doing Remainder -- return the residue */
3807       if (res.mant[0]==0)  // no integer part was found
3808        return clone(lhs).finish(set,false); // .. so return lhs, canonical
3809       if (var1[0]==0) 
3810        return ZERO; // simple 0 residue
3811       res.ind=lhs.ind; // sign is always as LHS
3812       /* Calculate the exponent by subtracting the number of padding zeros
3813          we added and adding the original exponent */
3814       padding=((reqdig+reqdig)+1)-lhs.mant.length;
3815       res.exp=(res.exp-padding)+lhs.exp;
3816       
3817       /* strip insignificant padding zeros from residue, and create/copy
3818          the resulting mantissa if need be */
3819       d=var1len;
3820       {i=d-1;i:for(;i>=1;i--){if(!((res.exp<lhs.exp)&(res.exp<rhs.exp)))break;
3821        if (var1[i]!=0) 
3822         break i;
3823        d--;
3824        res.exp=res.exp+1;
3825        }
3826       }/*i*/
3827       if (d<var1.length) 
3828        {/* need to reduce */
3829         newvar1=new byte[d];
3830         java.lang.System.arraycopy((java.lang.Object)var1,0,(java.lang.Object)newvar1,0,d); // shorten
3831         var1=newvar1;
3832        }
3833       res.mant=var1;
3834       return res.finish(set,false);
3835      }while(false);}/*remainder*/
3836    }
3837    
3838   else 
3839    {/* 'D' -- no overflow check needed */
3840     // If there was a residue then bump the final digit (iff 0 or 5)
3841     // so that the residue is visible for ROUND_UP, ROUND_HALF_xxx and
3842     // ROUND_UNNECESSARY checks (etc.) later.
3843     // [if we finished early, the residue will be 0]
3844     if (var1[0]!=0) 
3845      { // residue not 0
3846       lasthave=res.mant[have-1];
3847       if (((lasthave%5))==0) 
3848        res.mant[have-1]=(byte)(lasthave+1);
3849      }
3850    }
3851   
3852   /* Here for Divide or Integer Divide */
3853   // handle scaled results first ['I' always scale 0, optional for 'D']
3854   if (scale>=0) 
3855    {do{
3856     // say 'scale have res.exp len' scale have res.exp res.mant.length
3857     if (have!=res.mant.length) 
3858      // already padded with 0's, so just adjust exponent
3859      res.exp=res.exp-((res.mant.length-have));
3860     // calculate number of digits we really want [may be 0]
3861     actdig=res.mant.length-((((int)-res.exp)-scale));
3862     res.round(actdig,set.roundingMode); // round to desired length
3863     // This could have shifted left if round (say) 0.9->1[.0]
3864     // Repair if so by adding a zero and reducing exponent
3865     if (res.exp!=((int)-scale)) 
3866      {
3867       res.mant=extend(res.mant,res.mant.length+1);
3868       res.exp=res.exp-1;
3869      }
3870     return res.finish(set,true); // [strip if not PLAIN]
3871    }while(false);}/*scaled*/
3872   
3873   // reach here only if a non-scaled
3874   if (have==res.mant.length) 
3875    { // got digits+1 digits
3876     res.round(set);
3877     have=reqdig;
3878    }
3879   else 
3880    {/* have<=reqdig */
3881     if (res.mant[0]==0) 
3882      return ZERO; // fastpath
3883     // make the mantissa truly just 'have' long
3884     // [we could let finish do this, during strip, if we adjusted
3885     // the exponent; however, truncation avoids the strip loop]
3886     newmant=new byte[have]; // shorten
3887     java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,have);
3888     res.mant=newmant;
3889    }
3890   return res.finish(set,true);
3891   }
3892
3893  
3894  /* <sgml> Report a conversion exception. </sgml> */
3895  
3896  private void bad(char s[]){
3897   throw new java.lang.NumberFormatException("Not a number:"+" "+java.lang.String.valueOf(s));
3898   }
3899
3900  /* <sgml> Report a bad argument to a method. </sgml>
3901     Arg1 is method name
3902     Arg2 is argument position
3903     Arg3 is what was found */
3904  
3905  private void badarg(java.lang.String name,int pos,java.lang.String value){
3906   throw new java.lang.IllegalArgumentException("Bad argument"+" "+pos+" "+"to"+" "+name+":"+" "+value);
3907   }
3908
3909  /* <sgml> Extend byte array to given length, padding with 0s.  If no
3910     extension is required then return the same array. </sgml>
3911  
3912     Arg1 is the source byte array
3913     Arg2 is the new length (longer)
3914     */
3915  
3916  private static final byte[] extend(byte inarr[],int newlen){
3917   byte newarr[];
3918   if (inarr.length==newlen) 
3919    return inarr;
3920   newarr=new byte[newlen];
3921   java.lang.System.arraycopy((java.lang.Object)inarr,0,(java.lang.Object)newarr,0,inarr.length);
3922   // 0 padding is carried out by the JVM on allocation initialization
3923   return newarr;
3924   }
3925
3926  /* <sgml> Add or subtract two >=0 integers in byte arrays
3927     <p>This routine performs the calculation:
3928     <pre>
3929     C=A+(B*M)
3930     </pre>
3931     Where M is in the range -9 through +9
3932     <p>
3933     If M<0 then A>=B must be true, so the result is always
3934     non-negative.
3935  
3936     Leading zeros are not removed after a subtraction.  The result is
3937     either the same length as the longer of A and B, or 1 longer than
3938     that (if a carry occurred).
3939  
3940     A is not altered unless Arg6 is 1.
3941     B is never altered.
3942  
3943     Arg1 is A
3944     Arg2 is A length to use (if longer than A, pad with 0's)
3945     Arg3 is B
3946     Arg4 is B length to use (if longer than B, pad with 0's)
3947     Arg5 is M, the multiplier
3948     Arg6 is 1 if A can be used to build the result (if it fits)
3949  
3950     This routine is severely performance-critical; *any* change here
3951     must be measured (timed) to assure no performance degradation.
3952     */
3953  // 1996.02.20 -- enhanced version of DMSRCN algorithm (1981)
3954  // 1997.10.05 -- changed to byte arrays (from char arrays)
3955  // 1998.07.01 -- changed to allow destructive reuse of LHS
3956  // 1998.07.01 -- changed to allow virtual lengths for the arrays
3957  // 1998.12.29 -- use lookaside for digit/carry calculation
3958  // 1999.08.07 -- avoid multiply when mult=1, and make db an int
3959  // 1999.12.22 -- special case m=-1, also drop 0 special case
3960  
3961  private static final byte[] byteaddsub(byte a[],int avlen,byte b[],int bvlen,int m,boolean reuse){
3962   int alength;
3963   int blength;
3964   int ap;
3965   int bp;
3966   int maxarr;
3967   byte reb[];
3968   boolean quickm;
3969   int digit;
3970   int op=0;
3971   int dp90=0;
3972   byte newarr[];
3973   int i=0;
3974   
3975   
3976   
3977   
3978   // We'll usually be right if we assume no carry
3979   alength=a.length; // physical lengths
3980   blength=b.length; // ..
3981   ap=avlen-1; // -> final (rightmost) digit
3982   bp=bvlen-1; // ..
3983   maxarr=bp;
3984   if (maxarr<ap) 
3985    maxarr=ap;
3986   reb=(byte[])null; // result byte array
3987   if (reuse) 
3988    if ((maxarr+1)==alength) 
3989     reb=a; // OK to reuse A
3990   if (reb==null) 
3991    reb=new byte[maxarr+1]; // need new array
3992   
3993   quickm=false; // 1 if no multiply needed
3994   if (m==1) 
3995    quickm=true; // most common
3996   else 
3997    if (m==(-1)) 
3998     quickm=true; // also common
3999   
4000   digit=0; // digit, with carry or borrow
4001   {op=maxarr;op:for(;op>=0;op--){
4002    if (ap>=0) 
4003     {
4004      if (ap<alength) 
4005       digit=digit+a[ap]; // within A
4006      ap--;
4007     }
4008    if (bp>=0) 
4009     {
4010      if (bp<blength) 
4011       { // within B
4012        if (quickm) 
4013         {
4014          if (m>0) 
4015           digit=digit+b[bp]; // most common
4016          else 
4017           digit=digit-b[bp]; // also common
4018         }
4019        else 
4020         digit=digit+(b[bp]*m);
4021       }
4022      bp--;
4023     }
4024    /* result so far (digit) could be -90 through 99 */
4025    if (digit<10) 
4026     if (digit>=0) 
4027      {do{ // 0-9
4028       reb[op]=(byte)digit;
4029       digit=0; // no carry
4030       continue op;
4031      }while(false);}/*quick*/
4032    dp90=digit+90;
4033    reb[op]=bytedig[dp90]; // this digit
4034    digit=bytecar[dp90]; // carry or borrow
4035    }
4036   }/*op*/
4037   
4038   if (digit==0) 
4039    return reb; // no carry
4040   // following line will become an Assert, later
4041   // if digit<0 then signal ArithmeticException("internal.error ["digit"]")
4042   
4043   /* We have carry -- need to make space for the extra digit */
4044   newarr=(byte[])null;
4045   if (reuse) 
4046    if ((maxarr+2)==a.length) 
4047     newarr=a; // OK to reuse A
4048   if (newarr==null) 
4049    newarr=new byte[maxarr+2];
4050   newarr[0]=(byte)digit; // the carried digit ..
4051   // .. and all the rest [use local loop for short numbers]
4052   if (maxarr<10) 
4053    {int $24=maxarr+1;i=0;for(;$24>0;$24--,i++){
4054     newarr[i+1]=reb[i];
4055     }
4056    }/*i*/
4057   else 
4058    java.lang.System.arraycopy((java.lang.Object)reb,0,(java.lang.Object)newarr,1,maxarr+1);
4059   return newarr;
4060   }
4061
4062  /* <sgml> Initializer for digit array properties (lookaside). </sgml>
4063     Returns the digit array, and initializes the carry array. */
4064  
4065  private static final byte[] diginit(){
4066   byte work[];
4067   int op=0;
4068   int digit=0;
4069   work=new byte[(90+99)+1];
4070   {op=0;op:for(;op<=(90+99);op++){
4071    digit=op-90;
4072    if (digit>=0) 
4073     {
4074      work[op]=(byte)(digit%10);
4075      bytecar[op]=(byte)(digit/10); // calculate carry
4076      continue op;
4077     }
4078    // borrowing...
4079    digit=digit+100; // yes, this is right [consider -50]
4080    work[op]=(byte)(digit%10);
4081    bytecar[op]=(byte)((digit/10)-10); // calculate borrow [NB: - after %]
4082    }
4083   }/*op*/
4084   return work;
4085   }
4086
4087  /* <sgml> Create a copy of BigDecimal object for local use.
4088     <p>This does NOT make a copy of the mantissa array.
4089     </sgml>
4090     Arg1 is the BigDecimal to clone (non-null)
4091     */
4092  
4093  private static final com.ibm.icu.math.BigDecimal clone(com.ibm.icu.math.BigDecimal dec){
4094   com.ibm.icu.math.BigDecimal copy;
4095   copy=new com.ibm.icu.math.BigDecimal();
4096   copy.ind=dec.ind;
4097   copy.exp=dec.exp;
4098   copy.form=dec.form;
4099   copy.mant=dec.mant;
4100   return copy;
4101   }
4102
4103  /* <sgml> Check one or two numbers for lost digits. </sgml>
4104     Arg1 is RHS (or null, if none)
4105     Arg2 is current DIGITS setting
4106     returns quietly or throws an exception */
4107  
4108  private void checkdigits(com.ibm.icu.math.BigDecimal rhs,int dig){
4109   if (dig==0) 
4110    return; // don't check if digits=0
4111   // first check lhs...
4112   if (this.mant.length>dig) 
4113    if ((!(allzero(this.mant,dig)))) 
4114     throw new java.lang.ArithmeticException("Too many digits:"+" "+this.toString());
4115   if (rhs==null) 
4116    return; // monadic
4117   if (rhs.mant.length>dig) 
4118    if ((!(allzero(rhs.mant,dig)))) 
4119     throw new java.lang.ArithmeticException("Too many digits:"+" "+rhs.toString());
4120   }
4121
4122  /* <sgml> Round to specified digits, if necessary. </sgml>
4123     Arg1 is requested MathContext [with length and rounding mode]
4124     returns this, for convenience */
4125  
4126  private com.ibm.icu.math.BigDecimal round(com.ibm.icu.math.MathContext set){
4127   return round(set.digits,set.roundingMode);
4128   }
4129
4130  /* <sgml> Round to specified digits, if necessary.
4131     Arg1 is requested length (digits to round to)
4132             [may be <=0 when called from format, dodivide, etc.]
4133     Arg2 is rounding mode
4134     returns this, for convenience
4135  
4136     ind and exp are adjusted, but not cleared for a mantissa of zero
4137  
4138     The length of the mantissa returned will be Arg1, except when Arg1
4139     is 0, in which case the returned mantissa length will be 1.
4140     </sgml>
4141     */
4142  
4143  private com.ibm.icu.math.BigDecimal round(int len,int mode){
4144   int adjust;
4145   int sign;
4146   byte oldmant[];
4147   boolean reuse=false;
4148   byte first=0;
4149   int increment;
4150   byte newmant[]=null;
4151   adjust=mant.length-len;
4152   if (adjust<=0) 
4153    return this; // nowt to do
4154   
4155   exp=exp+adjust; // exponent of result
4156   sign=(int)ind; // save [assumes -1, 0, 1]
4157   oldmant=mant; // save
4158   if (len>0) 
4159    {
4160     // remove the unwanted digits
4161     mant=new byte[len];
4162     java.lang.System.arraycopy((java.lang.Object)oldmant,0,(java.lang.Object)mant,0,len);
4163     reuse=true; // can reuse mantissa
4164     first=oldmant[len]; // first of discarded digits
4165    }
4166   else 
4167    {/* len<=0 */
4168     mant=ZERO.mant;
4169     ind=iszero;
4170     reuse=false; // cannot reuse mantissa
4171     if (len==0) 
4172      first=oldmant[0];
4173     else 
4174      first=(byte)0; // [virtual digit]
4175    }
4176   
4177   // decide rounding adjustment depending on mode, sign, and discarded digits
4178   increment=0; // bumper
4179   {do{/*select*/
4180   if (mode==ROUND_HALF_UP)
4181    { // default first [most common]
4182     if (first>=5) 
4183      increment=sign;
4184    }
4185   else if (mode==ROUND_UNNECESSARY)
4186    { // default for setScale()
4187     // discarding any non-zero digits is an error
4188     if ((!(allzero(oldmant,len)))) 
4189      throw new java.lang.ArithmeticException("Rounding necessary");
4190    }
4191   else if (mode==ROUND_HALF_DOWN)
4192    { // 0.5000 goes down
4193     if (first>5) 
4194      increment=sign;
4195     else 
4196      if (first==5) 
4197       if ((!(allzero(oldmant,len+1)))) 
4198        increment=sign;
4199    }
4200   else if (mode==ROUND_HALF_EVEN)
4201    { // 0.5000 goes down if left digit even
4202     if (first>5) 
4203      increment=sign;
4204     else 
4205      if (first==5) 
4206       {
4207        if ((!(allzero(oldmant,len+1)))) 
4208         increment=sign;
4209        else /* 0.5000 */
4210         if ((((mant[mant.length-1])%2))==1) 
4211          increment=sign;
4212       }
4213    }
4214   else if (mode==ROUND_DOWN){
4215    // never increment
4216   }else if (mode==ROUND_UP)
4217    { // increment if discarded non-zero
4218     if ((!(allzero(oldmant,len)))) 
4219      increment=sign;
4220    }
4221   else if (mode==ROUND_CEILING)
4222    { // more positive
4223     if (sign>0) 
4224      if ((!(allzero(oldmant,len)))) 
4225       increment=sign;
4226    }
4227   else if (mode==ROUND_FLOOR)
4228    { // more negative
4229     if (sign<0) 
4230      if ((!(allzero(oldmant,len)))) 
4231       increment=sign;
4232    }
4233   else{
4234    throw new java.lang.IllegalArgumentException("Bad round value:"+" "+mode);
4235   }
4236   }while(false);}/*modes*/
4237   
4238   if (increment!=0) 
4239    {do{
4240     if (ind==iszero) 
4241      {
4242       // we must not subtract from 0, but result is trivial anyway
4243       mant=ONE.mant;
4244       ind=(byte)increment;
4245      }
4246     else 
4247      {
4248       // mantissa is non-0; we can safely add or subtract 1
4249       if (ind==isneg) 
4250        increment=(int)-increment;
4251       newmant=byteaddsub(mant,mant.length,ONE.mant,1,increment,reuse);
4252       if (newmant.length>mant.length) 
4253        { // had a carry
4254         // drop rightmost digit and raise exponent
4255         exp++;
4256         // mant is already the correct length
4257         java.lang.System.arraycopy((java.lang.Object)newmant,0,(java.lang.Object)mant,0,mant.length);
4258        }
4259       else 
4260        mant=newmant;
4261      }
4262    }while(false);}/*bump*/
4263   // rounding can increase exponent significantly
4264   if (exp>MaxExp) 
4265    throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+exp);
4266   return this;
4267   }
4268
4269  /* <sgml> Test if rightmost digits are all 0.
4270     Arg1 is a mantissa array to test
4271     Arg2 is the offset of first digit to check
4272             [may be negative; if so, digits to left are 0's]
4273     returns 1 if all the digits starting at Arg2 are 0
4274  
4275     Arg2 may be beyond array bounds, in which case 1 is returned
4276     </sgml> */
4277  
4278  private static final boolean allzero(byte array[],int start){
4279   int i=0;
4280   if (start<0) 
4281    start=0;
4282   {int $25=array.length-1;i=start;for(;i<=$25;i++){
4283    if (array[i]!=0) 
4284     return false;
4285    }
4286   }/*i*/
4287   return true;
4288   }
4289
4290  /* <sgml> Carry out final checks and canonicalization
4291     <p>
4292     This finishes off the current number by:
4293       1. Rounding if necessary (NB: length includes leading zeros)
4294       2. Stripping trailing zeros (if requested and \PLAIN)
4295       3. Stripping leading zeros (always)
4296       4. Selecting exponential notation (if required)
4297       5. Converting a zero result to just '0' (if \PLAIN)
4298     In practice, these operations overlap and share code.
4299     It always sets form.
4300     </sgml>
4301     Arg1 is requested MathContext (length to round to, trigger, and FORM)
4302     Arg2 is 1 if trailing insignificant zeros should be removed after
4303          round (for division, etc.), provided that set.form isn't PLAIN.
4304    returns this, for convenience
4305    */
4306  
4307  private com.ibm.icu.math.BigDecimal finish(com.ibm.icu.math.MathContext set,boolean strip){
4308   int d=0;
4309   int i=0;
4310   byte newmant[]=null;
4311   int mag=0;
4312   int sig=0;
4313   /* Round if mantissa too long and digits requested */
4314   if (set.digits!=0) 
4315    if (this.mant.length>set.digits) 
4316     this.round(set);
4317   
4318   /* If strip requested (and standard formatting), remove
4319      insignificant trailing zeros. */
4320   if (strip) 
4321    if (set.form!=com.ibm.icu.math.MathContext.PLAIN) 
4322     {
4323      d=this.mant.length;
4324      /* see if we need to drop any trailing zeros */
4325      {i=d-1;i:for(;i>=1;i--){
4326       if (this.mant[i]!=0) 
4327        break i;
4328       d--;
4329       exp++;
4330       }
4331      }/*i*/
4332      if (d<this.mant.length) 
4333       {/* need to reduce */
4334        newmant=new byte[d];
4335        java.lang.System.arraycopy((java.lang.Object)this.mant,0,(java.lang.Object)newmant,0,d);
4336        this.mant=newmant;
4337       }
4338     }
4339   
4340   form=(byte)com.ibm.icu.math.MathContext.PLAIN; // preset
4341   
4342   /* Now check for leading- and all- zeros in mantissa */
4343   {int $26=this.mant.length;i=0;for(;$26>0;$26--,i++){
4344    if (this.mant[i]!=0) 
4345     {
4346      // non-0 result; ind will be correct
4347      // remove leading zeros [e.g., after subtract]
4348      if (i>0) 
4349       {do{
4350        newmant=new byte[this.mant.length-i];
4351        java.lang.System.arraycopy((java.lang.Object)this.mant,i,(java.lang.Object)newmant,0,this.mant.length-i);
4352        this.mant=newmant;
4353       }while(false);}/*delead*/
4354      // now determine form if not PLAIN
4355      mag=exp+mant.length;
4356      if (mag>0) 
4357       { // most common path
4358        if (mag>set.digits) 
4359         if (set.digits!=0) 
4360          form=(byte)set.form;
4361        if ((mag-1)<=MaxExp) 
4362         return this; // no overflow; quick return
4363       }
4364      else 
4365       if (mag<(-5)) 
4366        form=(byte)set.form;
4367      /* check for overflow */
4368      mag--;
4369      if ((mag<MinExp)|(mag>MaxExp)) 
4370       {overflow:do{
4371        // possible reprieve if form is engineering
4372        if (form==com.ibm.icu.math.MathContext.ENGINEERING) 
4373         {
4374          sig=mag%3; // leftover
4375          if (sig<0) 
4376           sig=3+sig; // negative exponent
4377          mag=mag-sig; // exponent to use
4378          // 1999.06.29: second test here must be MaxExp
4379          if (mag>=MinExp) 
4380           if (mag<=MaxExp) 
4381            break overflow;
4382         }
4383        throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+mag);
4384       }while(false);}/*overflow*/
4385      return this;
4386     }
4387    }
4388   }/*i*/
4389   
4390   // Drop through to here only if mantissa is all zeros
4391   ind=iszero;
4392   {/*select*/
4393   if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
4394    exp=0; // standard result; go to '0'
4395   else if (exp>0)
4396    exp=0; // +ve exponent also goes to '0'
4397   else{
4398    // a plain number with -ve exponent; preserve and check exponent
4399    if (exp<MinExp) 
4400     throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+exp);
4401   }
4402   }
4403   mant=ZERO.mant; // canonical mantissa
4404   return this;
4405   }
4406  }