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