2 /* Generated from 'BigDecimal.nrx' 8 Sep 2000 11:10:50 [v2.00] */
\r
3 /* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
\r
4 package com.ibm.icu.math;
\r
5 import java.math.BigInteger;
\r
6 import com.ibm.icu.impl.Utility;
\r
7 import com.ibm.icu.lang.UCharacter;
\r
9 /* ------------------------------------------------------------------ */
\r
10 /* BigDecimal -- Decimal arithmetic for Java */
\r
11 /* ------------------------------------------------------------------ */
\r
12 /* Copyright IBM Corporation, 1996-2009. All Rights Reserved. */
\r
14 /* The BigDecimal class provides immutable arbitrary-precision */
\r
15 /* floating point (including integer) decimal numbers. */
\r
17 /* As the numbers are decimal, there is an exact correspondence */
\r
18 /* between an instance of a BigDecimal object and its String */
\r
19 /* representation; the BigDecimal class provides direct conversions */
\r
20 /* to and from String and character array objects, and well as */
\r
21 /* conversions to and from the Java primitive types (which may not */
\r
23 /* ------------------------------------------------------------------ */
\r
26 /* 1. A BigDecimal object is never changed in value once constructed; */
\r
27 /* this avoids the need for locking. Note in particular that the */
\r
28 /* mantissa array may be shared between many BigDecimal objects, */
\r
29 /* so that once exposed it must not be altered. */
\r
31 /* 2. This class looks at MathContext class fields directly (for */
\r
32 /* performance). It must not and does not change them. */
\r
34 /* 3. Exponent checking is delayed until finish(), as we know */
\r
35 /* intermediate calculations cannot cause 31-bit overflow. */
\r
36 /* [This assertion depends on MAX_DIGITS in MathContext.] */
\r
38 /* 4. Comments for the public API now follow the javadoc conventions. */
\r
39 /* The NetRexx -comments option is used to pass these comments */
\r
40 /* through to the generated Java code (with -format, if desired). */
\r
42 /* 5. System.arraycopy is faster than explicit loop as follows */
\r
43 /* Mean length 4: equal */
\r
44 /* Mean length 8: x2 */
\r
45 /* Mean length 16: x3 */
\r
46 /* Mean length 24: x4 */
\r
47 /* From prior experience, we expect mean length a little below 8, */
\r
48 /* but arraycopy is still the one to use, in general, until later */
\r
49 /* measurements suggest otherwise. */
\r
51 /* 6. 'DMSRCN' referred to below is the original (1981) IBM S/370 */
\r
52 /* assembler code implementation of the algorithms below; it is */
\r
53 /* now called IXXRCN and is available with the OS/390 and VM/ESA */
\r
54 /* operating systems. */
\r
55 /* ------------------------------------------------------------------ */
\r
56 /* Change History: */
\r
57 /* 1997.09.02 Initial version (derived from netrexx.lang classes) */
\r
58 /* 1997.09.12 Add lostDigits checking */
\r
59 /* 1997.10.06 Change mantissa to a byte array */
\r
60 /* 1997.11.22 Rework power [did not prepare arguments, etc.] */
\r
61 /* 1997.12.13 multiply did not prepare arguments */
\r
62 /* 1997.12.14 add did not prepare and align arguments correctly */
\r
63 /* 1998.05.02 0.07 packaging changes suggested by Sun and Oracle */
\r
64 /* 1998.05.21 adjust remainder operator finalization */
\r
65 /* 1998.06.04 rework to pass MathContext to finish() and round() */
\r
66 /* 1998.06.06 change format to use round(); support rounding modes */
\r
67 /* 1998.06.25 rename to BigDecimal and begin merge */
\r
68 /* zero can now have trailing zeros (i.e., exp\=0) */
\r
69 /* 1998.06.28 new methods: movePointXxxx, scale, toBigInteger */
\r
70 /* unscaledValue, valueof */
\r
71 /* 1998.07.01 improve byteaddsub to allow array reuse, etc. */
\r
72 /* 1998.07.01 make null testing explicit to avoid JIT bug [Win32] */
\r
73 /* 1998.07.07 scaled division [divide(BigDecimal, int, int)] */
\r
74 /* 1998.07.08 setScale, faster equals */
\r
75 /* 1998.07.11 allow 1E6 (no sign) <sigh>; new double/float conversion */
\r
76 /* 1998.10.12 change package to com.ibm.icu.math */
\r
77 /* 1998.12.14 power operator no longer rounds RHS [to match ANSI] */
\r
78 /* add toBigDecimal() and BigDecimal(java.math.BigDecimal) */
\r
79 /* 1998.12.29 improve byteaddsub by using table lookup */
\r
80 /* 1999.02.04 lostdigits=0 behaviour rounds instead of digits+1 guard */
\r
81 /* 1999.02.05 cleaner code for BigDecimal(char[]) */
\r
82 /* 1999.02.06 add javadoc comments */
\r
83 /* 1999.02.11 format() changed from 7 to 2 method form */
\r
84 /* 1999.03.05 null pointer checking is no longer explicit */
\r
85 /* 1999.03.05 simplify; changes from discussion with J. Bloch: */
\r
86 /* null no longer permitted for MathContext; drop boolean, */
\r
87 /* byte, char, float, short constructor, deprecate double */
\r
88 /* constructor, no blanks in string constructor, add */
\r
89 /* offset and length version of char[] constructor; */
\r
90 /* add valueOf(double); drop booleanValue, charValue; */
\r
91 /* add ...Exact versions of remaining convertors */
\r
92 /* 1999.03.13 add toBigIntegerExact */
\r
93 /* 1999.03.13 1.00 release to IBM Centre for Java Technology */
\r
94 /* 1999.05.27 1.01 correct 0-0.2 bug under scaled arithmetic */
\r
95 /* 1999.06.29 1.02 constructors should not allow exponent > 9 digits */
\r
96 /* 1999.07.03 1.03 lost digits should not be checked if digits=0 */
\r
97 /* 1999.07.06 lost digits Exception message changed */
\r
98 /* 1999.07.10 1.04 more work on 0-0.2 (scaled arithmetic) */
\r
99 /* 1999.07.17 improve messages from pow method */
\r
100 /* 1999.08.08 performance tweaks */
\r
101 /* 1999.08.15 fastpath in multiply */
\r
102 /* 1999.11.05 1.05 fix problem in intValueExact [e.g., 5555555555] */
\r
103 /* 1999.12.22 1.06 remove multiply fastpath, and improve performance */
\r
104 /* 2000.01.01 copyright update [Y2K has arrived] */
\r
105 /* 2000.06.18 1.08 no longer deprecate BigDecimal(double) */
\r
106 /* ------------------------------------------------------------------ */
\r
113 * The <code>BigDecimal</code> class implements immutable
\r
114 * arbitrary-precision decimal numbers. The methods of the
\r
115 * <code>BigDecimal</code> class provide operations for fixed and
\r
116 * floating point arithmetic, comparison, format conversions, and
\r
119 * As the numbers are decimal, there is an exact correspondence between
\r
120 * an instance of a <code>BigDecimal</code> object and its
\r
121 * <code>String</code> representation; the <code>BigDecimal</code> class
\r
122 * provides direct conversions to and from <code>String</code> and
\r
123 * character array (<code>char[]</code>) objects, as well as conversions
\r
124 * to and from the Java primitive types (which may not be exact) and
\r
125 * <code>BigInteger</code>.
\r
127 * In the descriptions of constructors and methods in this documentation,
\r
128 * the value of a <code>BigDecimal</code> number object is shown as the
\r
129 * result of invoking the <code>toString()</code> method on the object.
\r
130 * The internal representation of a decimal number is neither defined
\r
131 * nor exposed, and is not permitted to affect the result of any
\r
134 * The floating point arithmetic provided by this class is defined by
\r
135 * the ANSI X3.274-1996 standard, and is also documented at
\r
136 * <code>http://www2.hursley.ibm.com/decimal</code>
\r
137 * <br><i>[This URL will change.]</i>
\r
139 * <h3>Operator methods</h3>
\r
141 * Operations on <code>BigDecimal</code> numbers are controlled by a
\r
142 * {@link MathContext} object, which provides the context (precision and
\r
143 * other information) for the operation. Methods that can take a
\r
144 * <code>MathContext</code> parameter implement the standard arithmetic
\r
145 * operators for <code>BigDecimal</code> objects and are known as
\r
146 * <i>operator methods</i>. The default settings provided by the
\r
147 * constant {@link MathContext#DEFAULT} (<code>digits=9,
\r
148 * form=SCIENTIFIC, lostDigits=false, roundingMode=ROUND_HALF_UP</code>)
\r
149 * perform general-purpose floating point arithmetic to nine digits of
\r
150 * precision. The <code>MathContext</code> parameter must not be
\r
151 * <code>null</code>.
\r
153 * Each operator method also has a version provided which does
\r
154 * not take a <code>MathContext</code> parameter. For this version of
\r
155 * each method, the context settings used are <code>digits=0,
\r
156 * form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP</code>;
\r
157 * these settings perform fixed point arithmetic with unlimited
\r
158 * precision, as defined for the original BigDecimal class in Java 1.1
\r
161 * For monadic operators, only the optional <code>MathContext</code>
\r
162 * parameter is present; the operation acts upon the current object.
\r
164 * For dyadic operators, a <code>BigDecimal</code> parameter is always
\r
165 * present; it must not be <code>null</code>.
\r
166 * The operation acts with the current object being the left-hand operand
\r
167 * and the <code>BigDecimal</code> parameter being the right-hand operand.
\r
169 * For example, adding two <code>BigDecimal</code> objects referred to
\r
170 * by the names <code>award</code> and <code>extra</code> could be
\r
171 * written as any of:
\r
174 * <br>award.add(extra, MathContext.DEFAULT)
\r
175 * <br>award.add(extra, acontext)
\r
178 * (where <code>acontext</code> is a <code>MathContext</code> object),
\r
179 * which would return a <code>BigDecimal</code> object whose value is
\r
180 * the result of adding <code>award</code> and <code>extra</code> under
\r
181 * the appropriate context settings.
\r
183 * When a <code>BigDecimal</code> operator method is used, a set of
\r
184 * rules define what the result will be (and, by implication, how the
\r
185 * result would be represented as a character string).
\r
186 * These rules are defined in the BigDecimal arithmetic documentation
\r
187 * (see the URL above), but in summary:
\r
189 * <li>Results are normally calculated with up to some maximum number of
\r
190 * significant digits.
\r
191 * For example, if the <code>MathContext</code> parameter for an operation
\r
192 * were <code>MathContext.DEFAULT</code> then the result would be
\r
193 * rounded to 9 digits; the division of 2 by 3 would then result in
\r
196 * You can change the default of 9 significant digits by providing the
\r
197 * method with a suitable <code>MathContext</code> object. This lets you
\r
198 * calculate using as many digits as you need -- thousands, if necessary.
\r
199 * Fixed point (scaled) arithmetic is indicated by using a
\r
200 * <code>digits</code> setting of 0 (or omitting the
\r
201 * <code>MathContext</code> parameter).
\r
203 * Similarly, you can change the algorithm used for rounding from the
\r
204 * default "classic" algorithm.
\r
206 * In standard arithmetic (that is, when the <code>form</code> setting
\r
207 * is not <code>PLAIN</code>), a zero result is always expressed as the
\r
208 * single digit <code>'0'</code> (that is, with no sign, decimal point,
\r
209 * or exponent part).
\r
211 * Except for the division and power operators in standard arithmetic,
\r
212 * trailing zeros are preserved (this is in contrast to binary floating
\r
213 * point operations and most electronic calculators, which lose the
\r
214 * information about trailing zeros in the fractional part of results).
\r
218 * new BigDecimal("2.40").add( new BigDecimal("2")) => "4.40"
\r
219 * <br>new BigDecimal("2.40").subtract(new BigDecimal("2")) => "0.40"
\r
220 * <br>new BigDecimal("2.40").multiply(new BigDecimal("2")) => "4.80"
\r
221 * <br>new BigDecimal("2.40").divide( new BigDecimal("2"), def) => "1.2"
\r
223 * <p>where the value on the right of the <code>=></code> would be the
\r
224 * result of the operation, expressed as a <code>String</code>, and
\r
225 * <code>def</code> (in this and following examples) refers to
\r
226 * <code>MathContext.DEFAULT</code>).
\r
227 * This preservation of trailing zeros is desirable for most
\r
228 * calculations (including financial calculations).
\r
229 * If necessary, trailing zeros may be easily removed using division by 1.
\r
231 * In standard arithmetic, exponential form is used for a result
\r
232 * depending on its value and the current setting of <code>digits</code>
\r
233 * (the default is 9 digits).
\r
234 * If the number of places needed before the decimal point exceeds the
\r
235 * <code>digits</code> setting, or the absolute value of the number is
\r
236 * less than <code>0.000001</code>, then the number will be expressed in
\r
237 * exponential notation; thus
\r
239 * new BigDecimal("1e+6").multiply(new BigDecimal("1e+6"), def)
\r
241 * <p>results in <code>1E+12</code> instead of
\r
242 * <code>1000000000000</code>, and
\r
244 * new BigDecimal("1").divide(new BigDecimal("3E+10"), def)
\r
246 * <p>results in <code>3.33333333E-11</code> instead of
\r
247 * <code>0.0000000000333333333</code>.
\r
249 * The form of the exponential notation (scientific or engineering) is
\r
250 * determined by the <code>form</code> setting.
\r
253 * The names of methods in this class follow the conventions established
\r
254 * by <code>java.lang.Number</code>, <code>java.math.BigInteger</code>,
\r
255 * and <code>java.math.BigDecimal</code> in Java 1.1 and Java 1.2.
\r
258 * @author Mike Cowlishaw
\r
262 public class BigDecimal extends java.lang.Number implements java.io.Serializable,java.lang.Comparable{
\r
263 //private static final java.lang.String $0="BigDecimal.nrx";
\r
267 /* ----- Constants ----- */
\r
268 /* properties constant public */ // useful to others
\r
270 * The <code>BigDecimal</code> constant "0".
\r
276 public static final com.ibm.icu.math.BigDecimal ZERO=new com.ibm.icu.math.BigDecimal((long)0); // use long as we want the int constructor
\r
277 // .. to be able to use this, for speed
\r
280 * The <code>BigDecimal</code> constant "1".
\r
286 public static final com.ibm.icu.math.BigDecimal ONE=new com.ibm.icu.math.BigDecimal((long)1); // use long as we want the int constructor
\r
287 // .. to be able to use this, for speed
\r
290 * The <code>BigDecimal</code> constant "10".
\r
296 public static final com.ibm.icu.math.BigDecimal TEN=new com.ibm.icu.math.BigDecimal(10);
\r
298 // the rounding modes (copied here for upwards compatibility)
\r
300 * Rounding mode to round to a more positive number.
\r
301 * @see MathContext#ROUND_CEILING
\r
304 public static final int ROUND_CEILING=com.ibm.icu.math.MathContext.ROUND_CEILING;
\r
307 * Rounding mode to round towards zero.
\r
308 * @see MathContext#ROUND_DOWN
\r
311 public static final int ROUND_DOWN=com.ibm.icu.math.MathContext.ROUND_DOWN;
\r
314 * Rounding mode to round to a more negative number.
\r
315 * @see MathContext#ROUND_FLOOR
\r
318 public static final int ROUND_FLOOR=com.ibm.icu.math.MathContext.ROUND_FLOOR;
\r
321 * Rounding mode to round to nearest neighbor, where an equidistant
\r
322 * value is rounded down.
\r
323 * @see MathContext#ROUND_HALF_DOWN
\r
326 public static final int ROUND_HALF_DOWN=com.ibm.icu.math.MathContext.ROUND_HALF_DOWN;
\r
329 * Rounding mode to round to nearest neighbor, where an equidistant
\r
330 * value is rounded to the nearest even neighbor.
\r
331 * @see MathContext#ROUND_HALF_EVEN
\r
334 public static final int ROUND_HALF_EVEN=com.ibm.icu.math.MathContext.ROUND_HALF_EVEN;
\r
337 * Rounding mode to round to nearest neighbor, where an equidistant
\r
338 * value is rounded up.
\r
339 * @see MathContext#ROUND_HALF_UP
\r
342 public static final int ROUND_HALF_UP=com.ibm.icu.math.MathContext.ROUND_HALF_UP;
\r
345 * Rounding mode to assert that no rounding is necessary.
\r
346 * @see MathContext#ROUND_UNNECESSARY
\r
349 public static final int ROUND_UNNECESSARY=com.ibm.icu.math.MathContext.ROUND_UNNECESSARY;
\r
352 * Rounding mode to round away from zero.
\r
353 * @see MathContext#ROUND_UP
\r
356 public static final int ROUND_UP=com.ibm.icu.math.MathContext.ROUND_UP;
\r
358 /* properties constant private */ // locals
\r
359 private static final byte ispos=1; // ind: indicates positive (must be 1)
\r
360 private static final byte iszero=0; // ind: indicates zero (must be 0)
\r
361 private static final byte isneg=-1; // ind: indicates negative (must be -1)
\r
362 // [later could add NaN, +/- infinity, here]
\r
364 private static final int MinExp=-999999999; // minimum exponent allowed
\r
365 private static final int MaxExp=999999999; // maximum exponent allowed
\r
366 private static final int MinArg=-999999999; // minimum argument integer
\r
367 private static final int MaxArg=999999999; // maximum argument integer
\r
369 private static final com.ibm.icu.math.MathContext plainMC=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN); // context for plain unlimited math
\r
371 /* properties constant private unused */ // present but not referenced
\r
373 // Serialization version
\r
374 private static final long serialVersionUID=8245355804974198832L;
\r
376 //private static final java.lang.String copyright=" Copyright (c) IBM Corporation 1996, 2000. All rights reserved. ";
\r
378 /* properties static private */
\r
379 // Precalculated constant arrays (used by byteaddsub)
\r
380 private static byte bytecar[]=new byte[(90+99)+1]; // carry/borrow array
\r
381 private static byte bytedig[]=diginit(); // next digit array
\r
383 /* ----- Instance properties [all private and immutable] ----- */
\r
384 /* properties private */
\r
387 * The indicator. This may take the values:
\r
389 * <li>ispos -- the number is positive
\r
390 * <li>iszero -- the number is zero
\r
391 * <li>isneg -- the number is negative
\r
396 private byte ind; // assumed undefined
\r
397 // Note: some code below assumes IND = Sign [-1, 0, 1], at present.
\r
398 // We only need two bits for this, but use a byte [also permits
\r
399 // smooth future extension].
\r
402 * The formatting style. This may take the values:
\r
404 * <li>MathContext.PLAIN -- no exponent needed
\r
405 * <li>MathContext.SCIENTIFIC -- scientific notation required
\r
406 * <li>MathContext.ENGINEERING -- engineering notation required
\r
409 * This property is an optimization; it allows us to defer number
\r
410 * layout until it is actually needed as a string, hence avoiding
\r
411 * unnecessary formatting.
\r
415 private byte form=(byte)com.ibm.icu.math.MathContext.PLAIN; // assumed PLAIN
\r
416 // We only need two bits for this, at present, but use a byte
\r
417 // [again, to allow for smooth future extension]
\r
420 * The value of the mantissa.
\r
422 * Once constructed, this may become shared between several BigDecimal
\r
423 * objects, so must not be altered.
\r
425 * For efficiency (speed), this is a byte array, with each byte
\r
426 * taking a value of 0 -> 9.
\r
428 * If the first byte is 0 then the value of the number is zero (and
\r
429 * mant.length=1, except when constructed from a plain number, for
\r
434 private byte mant[]; // assumed null
\r
439 * For fixed point arithmetic, scale is <code>-exp</code>, and can
\r
442 * Note that this property can have a value less than MinExp when
\r
443 * the mantissa has more than one digit.
\r
450 /* ---------------------------------------------------------------- */
\r
452 /* ---------------------------------------------------------------- */
\r
454 //#if defined(FOUNDATION10)
\r
457 * Constructs a <code>BigDecimal</code> object from a
\r
458 * <code>java.math.BigDecimal</code>.
\r
460 * Constructs a <code>BigDecimal</code> as though the parameter had
\r
461 * been represented as a <code>String</code> (using its
\r
462 * <code>toString</code> method) and the
\r
463 * {@link #BigDecimal(java.lang.String)} constructor had then been
\r
465 * The parameter must not be <code>null</code>.
\r
467 * <i>(Note: this constructor is provided only in the
\r
468 * <code>com.ibm.icu.math</code> version of the BigDecimal class.
\r
469 * It would not be present in a <code>java.math</code> version.)</i>
\r
471 * @param bd The <code>BigDecimal</code> to be translated.
\r
475 public BigDecimal(java.math.BigDecimal bd){
\r
476 this(bd.toString());
\r
481 * Constructs a <code>BigDecimal</code> object from a
\r
482 * <code>BigInteger</code>, with scale 0.
\r
484 * Constructs a <code>BigDecimal</code> which is the exact decimal
\r
485 * representation of the <code>BigInteger</code>, with a scale of
\r
487 * The value of the <code>BigDecimal</code> is identical to the value
\r
488 * of the <code>BigInteger</code>.
\r
489 * The parameter must not be <code>null</code>.
\r
491 * The <code>BigDecimal</code> will contain only decimal digits,
\r
492 * prefixed with a leading minus sign (hyphen) if the
\r
493 * <code>BigInteger</code> is negative. A leading zero will be
\r
494 * present only if the <code>BigInteger</code> is zero.
\r
496 * @param bi The <code>BigInteger</code> to be converted.
\r
500 public BigDecimal(java.math.BigInteger bi){
\r
501 this(bi.toString(10));
\r
506 * Constructs a <code>BigDecimal</code> object from a
\r
507 * <code>BigInteger</code> and a scale.
\r
509 * Constructs a <code>BigDecimal</code> which is the exact decimal
\r
510 * representation of the <code>BigInteger</code>, scaled by the
\r
511 * second parameter, which may not be negative.
\r
512 * The value of the <code>BigDecimal</code> is the
\r
513 * <code>BigInteger</code> divided by ten to the power of the scale.
\r
514 * The <code>BigInteger</code> parameter must not be
\r
515 * <code>null</code>.
\r
517 * The <code>BigDecimal</code> will contain only decimal digits, (with
\r
518 * an embedded decimal point followed by <code>scale</code> decimal
\r
519 * digits if the scale is positive), prefixed with a leading minus
\r
520 * sign (hyphen) if the <code>BigInteger</code> is negative. A
\r
521 * leading zero will be present only if the <code>BigInteger</code> is
\r
524 * @param bi The <code>BigInteger</code> to be converted.
\r
525 * @param scale The <code>int</code> specifying the scale.
\r
526 * @throws NumberFormatException if the scale is negative.
\r
530 public BigDecimal(java.math.BigInteger bi,int scale){
\r
531 this(bi.toString(10));
\r
533 throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
\r
534 exp=(int)-scale; // exponent is -scale
\r
538 * Constructs a <code>BigDecimal</code> object from an array of characters.
\r
540 * Constructs a <code>BigDecimal</code> as though a
\r
541 * <code>String</code> had been constructed from the character array
\r
542 * and the {@link #BigDecimal(java.lang.String)} constructor had then
\r
543 * been used. The parameter must not be <code>null</code>.
\r
545 * Using this constructor is faster than using the
\r
546 * <code>BigDecimal(String)</code> constructor if the string is
\r
547 * already available in character array form.
\r
549 * @param inchars The <code>char[]</code> array containing the number
\r
551 * @throws NumberFormatException if the parameter is not a valid
\r
556 public BigDecimal(char inchars[]){
\r
557 this(inchars,0,inchars.length);
\r
561 * Constructs a <code>BigDecimal</code> object from an array of characters.
\r
563 * Constructs a <code>BigDecimal</code> as though a
\r
564 * <code>String</code> had been constructed from the character array
\r
565 * (or a subarray of that array) and the
\r
566 * {@link #BigDecimal(java.lang.String)} constructor had then been
\r
567 * used. The first parameter must not be <code>null</code>, and the
\r
568 * subarray must be wholly contained within it.
\r
570 * Using this constructor is faster than using the
\r
571 * <code>BigDecimal(String)</code> constructor if the string is
\r
572 * already available within a character array.
\r
574 * @param inchars The <code>char[]</code> array containing the number
\r
576 * @param offset The <code>int</code> offset into the array of the
\r
577 * start of the number to be converted.
\r
578 * @param length The <code>int</code> length of the number.
\r
579 * @throws NumberFormatException if the parameter is not a valid
\r
580 * number for any reason.
\r
584 public BigDecimal(char inchars[],int offset,int length){super();
\r
592 boolean eneg=false;
\r
599 // This is the primary constructor; all incoming strings end up
\r
600 // here; it uses explicit (inline) parsing for speed and to avoid
\r
601 // generating intermediate (temporary) objects of any kind.
\r
602 // 1998.06.25: exponent form built only if E/e in string
\r
603 // 1998.06.25: trailing zeros not removed for zero
\r
604 // 1999.03.06: no embedded blanks; allow offset and length
\r
606 bad(inchars); // bad conversion (empty string)
\r
607 // [bad offset will raise array bounds exception]
\r
609 /* Handle and step past sign */
\r
610 ind=ispos; // assume positive
\r
611 if (inchars[offset]==('-'))
\r
615 bad(inchars); // nothing after sign
\r
620 if (inchars[offset]==('+'))
\r
624 bad(inchars); // nothing after sign
\r
628 /* We're at the start of the number */
\r
629 exotic=false; // have extra digits
\r
630 hadexp=false; // had explicit exponent
\r
631 d=0; // count of digits found
\r
632 dotoff=-1; // offset where dot was found
\r
633 last=-1; // last character of mantissa
\r
634 {int $1=length;i=offset;i:for(;$1>0;$1--,i++){
\r
636 if (si>='0') // test for Arabic digit
\r
640 d++; // still in mantissa
\r
644 { // record and ignore
\r
646 bad(inchars); // two dots
\r
647 dotoff=i-offset; // offset into mantissa
\r
652 { // expect an extra digit
\r
653 if ((!(UCharacter.isDigit(si))))
\r
654 bad(inchars); // not a number
\r
655 // defer the base 10 check until later to avoid extra method call
\r
656 exotic=true; // will need conversion later
\r
658 d++; // still in mantissa
\r
661 /* Found 'e' or 'E' -- now process explicit exponent */
\r
662 // 1998.07.11: sign no longer required
\r
663 if ((i-offset)>(length-2))
\r
664 bad(inchars); // no room for even one digit
\r
666 if ((inchars[i+1])==('-'))
\r
672 if ((inchars[i+1])==('+'))
\r
676 // k is offset of first expected digit
\r
677 elen=length-((k-offset)); // possible number of digits
\r
678 if ((elen==0)|(elen>9))
\r
679 bad(inchars); // 0 or more than 9 digits
\r
680 {int $2=elen;j=k;for(;$2>0;$2--,j++){
\r
683 bad(inchars); // always bad
\r
685 { // maybe an exotic digit
\r
686 if ((!(UCharacter.isDigit(sj))))
\r
687 bad(inchars); // not a number
\r
688 dvalue=UCharacter.digit(sj,10); // check base
\r
690 bad(inchars); // not base 10
\r
693 dvalue=((int)(sj))-((int)('0'));
\r
694 exp=(exp*10)+dvalue;
\r
698 exp=(int)-exp; // was negative
\r
699 hadexp=true; // remember we had one
\r
700 break i; // we are done
\r
704 /* Here when all inspected */
\r
706 bad(inchars); // no mantissa digits
\r
708 exp=(exp+dotoff)-d; // adjust exponent if had dot
\r
710 /* strip leading zeros/dot (leave final if all 0's) */
\r
711 {int $3=last-1;i=offset;i:for(;i<=$3;i++){
\r
722 offset++; // step past dot
\r
727 break i;/* non-0 */
\r
730 if ((UCharacter.digit(si,10))!=0)
\r
731 break i; // non-0 or bad
\r
732 // is 0 .. strip like '0'
\r
740 /* Create the mantissa array */
\r
741 mant=new byte[d]; // we know the length
\r
742 j=offset; // input offset
\r
744 {do{ // slow: check for exotica
\r
745 {int $4=d;i=0;for(;$4>0;$4--,i++){
\r
750 mant[i]=(byte)(((int)(sj))-((int)('0')));/* easy */
\r
753 dvalue=UCharacter.digit(sj,10);
\r
755 bad(inchars); // not a number after all
\r
756 mant[i]=(byte)dvalue;
\r
761 }while(false);}/*exotica*/
\r
764 {int $5=d;i=0;for(;$5>0;$5--,i++){
\r
767 mant[i]=(byte)(((int)(inchars[j]))-((int)('0')));
\r
771 }while(false);}/*simple*/
\r
773 /* Looks good. Set the sign indicator and form, as needed. */
\r
774 // Trailing zeros are preserved
\r
775 // The rule here for form is:
\r
776 // If no E-notation, then request plain notation
\r
777 // Otherwise act as though add(0,DEFAULT) and request scientific notation
\r
778 // [form is already PLAIN]
\r
781 ind=iszero; // force to show zero
\r
782 // negative exponent is significant (e.g., -3 for 0.000) if plain
\r
784 exp=0; // positive exponent can be ignored
\r
786 { // zero becomes single digit from add
\r
793 // [ind was set earlier]
\r
794 // now determine form
\r
797 form=(byte)com.ibm.icu.math.MathContext.SCIENTIFIC;
\r
798 // 1999.06.29 check for overflow
\r
799 mag=(exp+mant.length)-1; // true exponent in scientific notation
\r
800 if ((mag<MinExp)|(mag>MaxExp))
\r
804 // say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] mant.length exp ind form
\r
809 * Constructs a <code>BigDecimal</code> object directly from a
\r
810 * <code>double</code>.
\r
812 * Constructs a <code>BigDecimal</code> which is the exact decimal
\r
813 * representation of the 64-bit signed binary floating point
\r
816 * Note that this constructor it an exact conversion; it does not give
\r
817 * the same result as converting <code>num</code> to a
\r
818 * <code>String</code> using the <code>Double.toString()</code> method
\r
819 * and then using the {@link #BigDecimal(java.lang.String)}
\r
821 * To get that result, use the static {@link #valueOf(double)}
\r
822 * method to construct a <code>BigDecimal</code> from a
\r
823 * <code>double</code>.
\r
825 * @param num The <code>double</code> to be converted.
\r
826 * @throws NumberFormatException if the parameter is infinite or
\r
831 public BigDecimal(double num){
\r
832 // 1999.03.06: use exactly the old algorithm
\r
833 // 2000.01.01: note that this constructor does give an exact result,
\r
834 // so perhaps it should not be deprecated
\r
835 // 2000.06.18: no longer deprecated
\r
836 //#if defined(FOUNDATION10)
\r
837 //## this(String.valueOf(num));
\r
839 this((new java.math.BigDecimal(num)).toString());
\r
843 * Constructs a <code>BigDecimal</code> object directly from a
\r
844 * <code>int</code>.
\r
846 * Constructs a <code>BigDecimal</code> which is the exact decimal
\r
847 * representation of the 32-bit signed binary integer parameter.
\r
848 * The <code>BigDecimal</code> will contain only decimal digits,
\r
849 * prefixed with a leading minus sign (hyphen) if the parameter is
\r
851 * A leading zero will be present only if the parameter is zero.
\r
853 * @param num The <code>int</code> to be converted.
\r
857 public BigDecimal(int num){super();
\r
860 // We fastpath commoners
\r
864 // very common single digit case
\r
876 else if (num==(-1))
\r
891 mant[0]=(byte)((int)-num);
\r
898 }while(false);}/*singledigit*/
\r
900 /* We work on negative numbers so we handle the most negative number */
\r
907 ind=isneg;/* negative */ // [0 case already handled]
\r
908 // [it is quicker, here, to pre-calculate the length with
\r
909 // one loop, then allocate exactly the right length of byte array,
\r
910 // then re-fill it with another loop]
\r
911 mun=num; // working copy
\r
918 // i is the position of the leftmost digit placed
\r
919 mant=new byte[10-i];
\r
920 {i=(10-i)-1;i:for(;;i--){
\r
921 mant[i]=(byte)-(((byte)(num%10)));
\r
931 * Constructs a <code>BigDecimal</code> object directly from a
\r
932 * <code>long</code>.
\r
934 * Constructs a <code>BigDecimal</code> which is the exact decimal
\r
935 * representation of the 64-bit signed binary integer parameter.
\r
936 * The <code>BigDecimal</code> will contain only decimal digits,
\r
937 * prefixed with a leading minus sign (hyphen) if the parameter is
\r
939 * A leading zero will be present only if the parameter is zero.
\r
941 * @param num The <code>long</code> to be converted.
\r
945 public BigDecimal(long num){super();
\r
948 // Not really worth fastpathing commoners in this constructor [also,
\r
949 // we use this to construct the static constants].
\r
950 // This is much faster than: this(String.valueOf(num).toCharArray())
\r
951 /* We work on negative num so we handle the most negative number */
\r
961 ind=isneg;/* negative */
\r
963 {i=18;i:for(;;i--){
\r
969 // i is the position of the leftmost digit placed
\r
970 mant=new byte[19-i];
\r
971 {i=(19-i)-1;i:for(;;i--){
\r
972 mant[i]=(byte)-(((byte)(num%10)));
\r
982 * Constructs a <code>BigDecimal</code> object from a <code>String</code>.
\r
984 * Constructs a <code>BigDecimal</code> from the parameter, which must
\r
985 * not be <code>null</code> and must represent a valid <i>number</i>,
\r
986 * as described formally in the documentation referred to
\r
987 * {@link BigDecimal above}.
\r
989 * In summary, numbers in <code>String</code> form must have at least
\r
990 * one digit, may have a leading sign, may have a decimal point, and
\r
991 * exponential notation may be used. They follow conventional syntax,
\r
992 * and may not contain blanks.
\r
994 * Some valid strings from which a <code>BigDecimal</code> might
\r
995 * be constructed are:
\r
998 * "12" -- A whole number
\r
999 * "-76" -- A signed whole number
\r
1000 * "12.70" -- Some decimal places
\r
1001 * "+0.003" -- Plus sign is allowed
\r
1002 * "17." -- The same as 17
\r
1003 * ".5" -- The same as 0.5
\r
1004 * "4E+9" -- Exponential notation
\r
1005 * "0.73e-7" -- Exponential notation
\r
1008 * (Exponential notation means that the number includes an optional
\r
1009 * sign and a power of ten following an '</code>E</code>' that
\r
1010 * indicates how the decimal point will be shifted. Thus the
\r
1011 * <code>"4E+9"</code> above is just a short way of writing
\r
1012 * <code>4000000000</code>, and the <code>"0.73e-7"</code> is short
\r
1013 * for <code>0.000000073</code>.)
\r
1015 * The <code>BigDecimal</code> constructed from the String is in a
\r
1016 * standard form, with no blanks, as though the
\r
1017 * {@link #add(BigDecimal)} method had been used to add zero to the
\r
1018 * number with unlimited precision.
\r
1019 * If the string uses exponential notation (that is, includes an
\r
1020 * <code>e</code> or an <code>E</code>), then the
\r
1021 * <code>BigDecimal</code> number will be expressed in scientific
\r
1022 * notation (where the power of ten is adjusted so there is a single
\r
1023 * non-zero digit to the left of the decimal point); in this case if
\r
1024 * the number is zero then it will be expressed as the single digit 0,
\r
1025 * and if non-zero it will have an exponent unless that exponent would
\r
1026 * be 0. The exponent must fit in nine digits both before and after it
\r
1027 * is expressed in scientific notation.
\r
1029 * Any digits in the parameter must be decimal; that is,
\r
1030 * <code>Character.digit(c, 10)</code> (where </code>c</code> is the
\r
1031 * character in question) would not return -1.
\r
1033 * @param string The <code>String</code> to be converted.
\r
1034 * @throws NumberFormatException if the parameter is not a valid
\r
1039 public BigDecimal(java.lang.String string){
\r
1040 this(string.toCharArray(),0,string.length());
\r
1043 /* <sgml> Make a default BigDecimal object for local use. </sgml> */
\r
1045 private BigDecimal(){super();
\r
1049 /* ---------------------------------------------------------------- */
\r
1050 /* Operator methods [methods which take a context parameter] */
\r
1051 /* ---------------------------------------------------------------- */
\r
1054 * Returns a plain <code>BigDecimal</code> whose value is the absolute
\r
1055 * value of this <code>BigDecimal</code>.
\r
1057 * The same as {@link #abs(MathContext)}, where the context is
\r
1058 * <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1060 * The length of the decimal part (the scale) of the result will
\r
1061 * be <code>this.scale()</code>
\r
1063 * @return A <code>BigDecimal</code> whose value is the absolute
\r
1064 * value of this <code>BigDecimal</code>.
\r
1068 public com.ibm.icu.math.BigDecimal abs(){
\r
1069 return this.abs(plainMC);
\r
1073 * Returns a <code>BigDecimal</code> whose value is the absolute value
\r
1074 * of this <code>BigDecimal</code>.
\r
1076 * If the current object is zero or positive, then the same result as
\r
1077 * invoking the {@link #plus(MathContext)} method with the same
\r
1078 * parameter is returned.
\r
1079 * Otherwise, the same result as invoking the
\r
1080 * {@link #negate(MathContext)} method with the same parameter is
\r
1083 * @param set The <code>MathContext</code> arithmetic settings.
\r
1084 * @return A <code>BigDecimal</code> whose value is the absolute
\r
1085 * value of this <code>BigDecimal</code>.
\r
1089 public com.ibm.icu.math.BigDecimal abs(com.ibm.icu.math.MathContext set){
\r
1090 if (this.ind==isneg)
\r
1091 return this.negate(set);
\r
1092 return this.plus(set);
\r
1096 * Returns a plain <code>BigDecimal</code> whose value is
\r
1097 * <code>this+rhs</code>, using fixed point arithmetic.
\r
1099 * The same as {@link #add(BigDecimal, MathContext)},
\r
1100 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1101 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1103 * The length of the decimal part (the scale) of the result will be
\r
1104 * the maximum of the scales of the two operands.
\r
1106 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1108 * @return A <code>BigDecimal</code> whose value is
\r
1109 * <code>this+rhs</code>, using fixed point arithmetic.
\r
1113 public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs){
\r
1114 return this.add(rhs,plainMC);
\r
1118 * Returns a <code>BigDecimal</code> whose value is <code>this+rhs</code>.
\r
1120 * Implements the addition (<b><code>+</code></b>) operator
\r
1121 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1123 * and returns the result as a <code>BigDecimal</code> object.
\r
1125 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1127 * @param set The <code>MathContext</code> arithmetic settings.
\r
1128 * @return A <code>BigDecimal</code> whose value is
\r
1129 * <code>this+rhs</code>.
\r
1133 public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1134 com.ibm.icu.math.BigDecimal lhs;
\r
1136 com.ibm.icu.math.BigDecimal res;
\r
1151 /* determine requested digits and form */
\r
1152 if (set.lostDigits)
\r
1153 checkdigits(rhs,set.digits);
\r
1154 lhs=this; // name for clarity and proxy
\r
1156 /* Quick exit for add floating 0 */
\r
1157 // plus() will optimize to return same object if possible
\r
1159 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
1160 return rhs.plus(set);
\r
1162 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
1163 return lhs.plus(set);
\r
1165 /* Prepare numbers (round, unless unlimited precision) */
\r
1166 reqdig=set.digits; // local copy (heavily used)
\r
1169 if (lhs.mant.length>reqdig)
\r
1170 lhs=clone(lhs).round(set);
\r
1171 if (rhs.mant.length>reqdig)
\r
1172 rhs=clone(rhs).round(set);
\r
1173 // [we could reuse the new LHS for result in this case]
\r
1176 res=new com.ibm.icu.math.BigDecimal(); // build result here
\r
1178 /* Now see how much we have to pad or truncate lhs or rhs in order
\r
1179 to align the numbers. If one number is much larger than the
\r
1180 other, then the smaller cannot affect the answer [but we may
\r
1181 still need to pad with up to DIGITS trailing zeros]. */
\r
1182 // Note sign may be 0 if digits (reqdig) is 0
\r
1183 // usel and user will be the byte arrays passed to the adder; we'll
\r
1184 // use them on all paths except quick exits
\r
1186 usellen=lhs.mant.length;
\r
1188 userlen=rhs.mant.length;
\r
1190 if (lhs.exp==rhs.exp)
\r
1191 {/* no padding needed */
\r
1192 // This is the most common, and fastest, path
\r
1195 else if (lhs.exp>rhs.exp)
\r
1196 { // need to pad lhs and/or truncate rhs
\r
1197 newlen=(usellen+lhs.exp)-rhs.exp;
\r
1198 /* If, after pad, lhs would be longer than rhs by digits+1 or
\r
1199 more (and digits>0) then rhs cannot affect answer, so we only
\r
1200 need to pad up to a length of DIGITS+1. */
\r
1201 if (newlen>=((userlen+reqdig)+1))
\r
1204 // LHS is sufficient
\r
1208 if (usellen<reqdig)
\r
1209 { // need 0 padding
\r
1210 res.mant=extend(lhs.mant,reqdig);
\r
1211 res.exp=res.exp-((reqdig-usellen));
\r
1213 return res.finish(set,false);
\r
1215 // RHS may affect result
\r
1216 res.exp=rhs.exp; // expected final exponent
\r
1217 if (newlen>(reqdig+1))
\r
1220 // LHS will be max; RHS truncated
\r
1221 tlen=(newlen-reqdig)-1; // truncation length
\r
1222 userlen=userlen-tlen;
\r
1223 res.exp=res.exp+tlen;
\r
1226 if (newlen>usellen)
\r
1227 usellen=newlen; // need to pad LHS
\r
1229 else{ // need to pad rhs and/or truncate lhs
\r
1230 newlen=(userlen+rhs.exp)-lhs.exp;
\r
1231 if (newlen>=((usellen+reqdig)+1))
\r
1234 // RHS is sufficient
\r
1238 if (userlen<reqdig)
\r
1239 { // need 0 padding
\r
1240 res.mant=extend(rhs.mant,reqdig);
\r
1241 res.exp=res.exp-((reqdig-userlen));
\r
1243 return res.finish(set,false);
\r
1245 // LHS may affect result
\r
1246 res.exp=lhs.exp; // expected final exponent
\r
1247 if (newlen>(reqdig+1))
\r
1250 // RHS will be max; LHS truncated
\r
1251 tlen=(newlen-reqdig)-1; // truncation length
\r
1252 usellen=usellen-tlen;
\r
1253 res.exp=res.exp+tlen;
\r
1256 if (newlen>userlen)
\r
1257 userlen=newlen; // need to pad RHS
\r
1259 }while(false);}/*padder*/
\r
1261 /* OK, we have aligned mantissas. Now add or subtract. */
\r
1262 // 1998.06.27 Sign may now be 0 [e.g., 0.000] .. treat as positive
\r
1263 // 1999.05.27 Allow for 00 on lhs [is not larger than 2 on rhs]
\r
1264 // 1999.07.10 Allow for 00 on rhs [is not larger than 2 on rhs]
\r
1265 if (lhs.ind==iszero)
\r
1268 res.ind=lhs.ind; // likely sign, all paths
\r
1269 if (((lhs.ind==isneg)?1:0)==((rhs.ind==isneg)?1:0)) // same sign, 0 non-negative
\r
1272 {do{ // different signs, so subtraction is needed
\r
1273 mult=-1; // will cause subtract
\r
1274 /* Before we can subtract we must determine which is the larger,
\r
1275 as our add/subtract routine only handles non-negative results
\r
1276 so we may need to swap the operands. */
\r
1278 if (rhs.ind==iszero){
\r
1279 // original A bigger
\r
1280 }else if ((usellen<userlen)|(lhs.ind==iszero))
\r
1281 { // original B bigger
\r
1287 userlen=tlen; // ..
\r
1288 res.ind=(byte)-res.ind; // and set sign
\r
1290 else if (usellen>userlen){
\r
1291 // original A bigger
\r
1293 {/* logical lengths the same */ // need compare
\r
1294 /* may still need to swap: compare the strings */
\r
1306 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
1308 // [if PLAIN we must do the subtract, in case of 0.000 results]
\r
1320 {/* swap needed */
\r
1326 userlen=tlen; // ..
\r
1327 res.ind=(byte)-res.ind;
\r
1331 /* mantissas the same, so far */
\r
1336 } // lengths the same
\r
1338 }while(false);}/*swaptest*/
\r
1339 }while(false);}/*signdiff*/
\r
1341 /* here, A is > B if subtracting */
\r
1342 // add [A+B*1] or subtract [A+(B*-1)]
\r
1343 res.mant=byteaddsub(usel,usellen,user,userlen,mult,false);
\r
1344 // [reuse possible only after chop; accounting makes not worthwhile]
\r
1346 // Finish() rounds before stripping leading 0's, then sets form, etc.
\r
1347 return res.finish(set,false);
\r
1351 * Compares this <code>BigDecimal</code> to another, using unlimited
\r
1354 * The same as {@link #compareTo(BigDecimal, MathContext)},
\r
1355 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1356 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1358 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1360 * @return An <code>int</code> whose value is -1, 0, or 1 as
\r
1361 * <code>this</code> is numerically less than, equal to,
\r
1362 * or greater than <code>rhs</code>.
\r
1363 * @see #compareTo(Object)
\r
1367 public int compareTo(com.ibm.icu.math.BigDecimal rhs){
\r
1368 return this.compareTo(rhs,plainMC);
\r
1372 * Compares this <code>BigDecimal</code> to another.
\r
1374 * Implements numeric comparison,
\r
1375 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1377 * and returns a result of type <code>int</code>.
\r
1379 * The result will be:
\r
1380 * <table cellpadding=2><tr>
\r
1381 * <td align=right><b>-1</b></td>
\r
1382 * <td>if the current object is less than the first parameter</td>
\r
1384 * <td align=right><b>0</b></td>
\r
1385 * <td>if the current object is equal to the first parameter</td>
\r
1387 * <td align=right><b>1</b></td>
\r
1388 * <td>if the current object is greater than the first parameter.</td>
\r
1391 * A {@link #compareTo(Object)} method is also provided.
\r
1393 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1395 * @param set The <code>MathContext</code> arithmetic settings.
\r
1396 * @return An <code>int</code> whose value is -1, 0, or 1 as
\r
1397 * <code>this</code> is numerically less than, equal to,
\r
1398 * or greater than <code>rhs</code>.
\r
1399 * @see #compareTo(Object)
\r
1403 public int compareTo(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1406 com.ibm.icu.math.BigDecimal newrhs;
\r
1407 // rhs=null will raise NullPointerException, as per Comparable interface
\r
1408 if (set.lostDigits)
\r
1409 checkdigits(rhs,set.digits);
\r
1410 // [add will recheck in slowpath cases .. but would report -rhs]
\r
1411 if ((this.ind==rhs.ind)&(this.exp==rhs.exp))
\r
1413 /* sign & exponent the same [very common] */
\r
1414 thislength=this.mant.length;
\r
1415 if (thislength<rhs.mant.length)
\r
1416 return (byte)-this.ind;
\r
1417 if (thislength>rhs.mant.length)
\r
1419 /* lengths are the same; we can do a straight mantissa compare
\r
1420 unless maybe rounding [rounding is very unusual] */
\r
1421 if ((thislength<=set.digits)|(set.digits==0))
\r
1423 {int $6=thislength;i=0;for(;$6>0;$6--,i++){
\r
1424 if (this.mant[i]<rhs.mant[i])
\r
1425 return (byte)-this.ind;
\r
1426 if (this.mant[i]>rhs.mant[i])
\r
1430 return 0; // identical
\r
1432 /* drop through for full comparison */
\r
1436 /* More fastpaths possible */
\r
1437 if (this.ind<rhs.ind)
\r
1439 if (this.ind>rhs.ind)
\r
1442 /* carry out a subtract to make the comparison */
\r
1443 newrhs=clone(rhs); // safe copy
\r
1444 newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
\r
1445 return this.add(newrhs,set).ind; // add, and return sign of result
\r
1449 * Returns a plain <code>BigDecimal</code> whose value is
\r
1450 * <code>this/rhs</code>, using fixed point arithmetic.
\r
1452 * The same as {@link #divide(BigDecimal, int)},
\r
1453 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1454 * and the rounding mode is {@link MathContext#ROUND_HALF_UP}.
\r
1456 * The length of the decimal part (the scale) of the result will be
\r
1457 * the same as the scale of the current object, if the latter were
\r
1458 * formatted without exponential notation.
\r
1460 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1462 * @return A plain <code>BigDecimal</code> whose value is
\r
1463 * <code>this/rhs</code>, using fixed point arithmetic.
\r
1464 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1468 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs){
\r
1469 return this.dodivide('D',rhs,plainMC,-1);
\r
1473 * Returns a plain <code>BigDecimal</code> whose value is
\r
1474 * <code>this/rhs</code>, using fixed point arithmetic and a
\r
1477 * The same as {@link #divide(BigDecimal, int, int)},
\r
1478 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1479 * and the second parameter is <code>this.scale()</code>, and
\r
1480 * the third is <code>round</code>.
\r
1482 * The length of the decimal part (the scale) of the result will
\r
1483 * therefore be the same as the scale of the current object, if the
\r
1484 * latter were formatted without exponential notation.
\r
1486 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1488 * @param round The <code>int</code> rounding mode to be used for
\r
1489 * the division (see the {@link MathContext} class).
\r
1490 * @return A plain <code>BigDecimal</code> whose value is
\r
1491 * <code>this/rhs</code>, using fixed point arithmetic
\r
1492 * and the specified rounding mode.
\r
1493 * @throws IllegalArgumentException if <code>round</code> is not a
\r
1494 * valid rounding mode.
\r
1495 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1496 * @throws ArithmeticException if <code>round</code> is {@link
\r
1497 * MathContext#ROUND_UNNECESSARY} and
\r
1498 * <code>this.scale()</code> is insufficient to
\r
1499 * represent the result exactly.
\r
1503 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int round){
\r
1504 com.ibm.icu.math.MathContext set;
\r
1505 set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round, too]
\r
1506 return this.dodivide('D',rhs,set,-1); // take scale from LHS
\r
1510 * Returns a plain <code>BigDecimal</code> whose value is
\r
1511 * <code>this/rhs</code>, using fixed point arithmetic and a
\r
1512 * given scale and rounding mode.
\r
1514 * The same as {@link #divide(BigDecimal, MathContext)},
\r
1515 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1516 * <code>new MathContext(0, MathContext.PLAIN, false, round)</code>,
\r
1517 * except that the length of the decimal part (the scale) to be used
\r
1518 * for the result is explicit rather than being taken from
\r
1519 * <code>this</code>.
\r
1521 * The length of the decimal part (the scale) of the result will be
\r
1522 * the same as the scale of the current object, if the latter were
\r
1523 * formatted without exponential notation.
\r
1525 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1527 * @param scale The <code>int</code> scale to be used for the result.
\r
1528 * @param round The <code>int</code> rounding mode to be used for
\r
1529 * the division (see the {@link MathContext} class).
\r
1530 * @return A plain <code>BigDecimal</code> whose value is
\r
1531 * <code>this/rhs</code>, using fixed point arithmetic
\r
1532 * and the specified rounding mode.
\r
1533 * @throws IllegalArgumentException if <code>round</code> is not a
\r
1534 * valid rounding mode.
\r
1535 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1536 * @throws ArithmeticException if <code>scale</code> is negative.
\r
1537 * @throws ArithmeticException if <code>round</code> is {@link
\r
1538 * MathContext#ROUND_UNNECESSARY} and <code>scale</code>
\r
1539 * is insufficient to represent the result exactly.
\r
1543 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,int scale,int round){
\r
1544 com.ibm.icu.math.MathContext set;
\r
1546 throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
\r
1547 set=new com.ibm.icu.math.MathContext(0,com.ibm.icu.math.MathContext.PLAIN,false,round); // [checks round]
\r
1548 return this.dodivide('D',rhs,set,scale);
\r
1552 * Returns a <code>BigDecimal</code> whose value is <code>this/rhs</code>.
\r
1554 * Implements the division (<b><code>/</code></b>) operator
\r
1555 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1557 * and returns the result as a <code>BigDecimal</code> object.
\r
1559 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1561 * @param set The <code>MathContext</code> arithmetic settings.
\r
1562 * @return A <code>BigDecimal</code> whose value is
\r
1563 * <code>this/rhs</code>.
\r
1564 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1568 public com.ibm.icu.math.BigDecimal divide(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1569 return this.dodivide('D',rhs,set,-1);
\r
1573 * Returns a plain <code>BigDecimal</code> whose value is the integer
\r
1574 * part of <code>this/rhs</code>.
\r
1576 * The same as {@link #divideInteger(BigDecimal, MathContext)},
\r
1577 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1578 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1580 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1581 * the integer division.
\r
1582 * @return A <code>BigDecimal</code> whose value is the integer
\r
1583 * part of <code>this/rhs</code>.
\r
1584 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1588 public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs){
\r
1589 // scale 0 to drop .000 when plain
\r
1590 return this.dodivide('I',rhs,plainMC,0);
\r
1594 * Returns a <code>BigDecimal</code> whose value is the integer
\r
1595 * part of <code>this/rhs</code>.
\r
1597 * Implements the integer division operator
\r
1598 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1600 * and returns the result as a <code>BigDecimal</code> object.
\r
1602 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1603 * the integer division.
\r
1604 * @param set The <code>MathContext</code> arithmetic settings.
\r
1605 * @return A <code>BigDecimal</code> whose value is the integer
\r
1606 * part of <code>this/rhs</code>.
\r
1607 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
1608 * @throws ArithmeticException if the result will not fit in the
\r
1609 * number of digits specified for the context.
\r
1613 public com.ibm.icu.math.BigDecimal divideInteger(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1614 // scale 0 to drop .000 when plain
\r
1615 return this.dodivide('I',rhs,set,0);
\r
1619 * Returns a plain <code>BigDecimal</code> whose value is
\r
1620 * the maximum of <code>this</code> and <code>rhs</code>.
\r
1622 * The same as {@link #max(BigDecimal, MathContext)},
\r
1623 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1624 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1626 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1628 * @return A <code>BigDecimal</code> whose value is
\r
1629 * the maximum of <code>this</code> and <code>rhs</code>.
\r
1633 public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs){
\r
1634 return this.max(rhs,plainMC);
\r
1638 * Returns a <code>BigDecimal</code> whose value is
\r
1639 * the maximum of <code>this</code> and <code>rhs</code>.
\r
1641 * Returns the larger of the current object and the first parameter.
\r
1643 * If calling the {@link #compareTo(BigDecimal, MathContext)} method
\r
1644 * with the same parameters would return <code>1</code> or
\r
1645 * <code>0</code>, then the result of calling the
\r
1646 * {@link #plus(MathContext)} method on the current object (using the
\r
1647 * same <code>MathContext</code> parameter) is returned.
\r
1648 * Otherwise, the result of calling the {@link #plus(MathContext)}
\r
1649 * method on the first parameter object (using the same
\r
1650 * <code>MathContext</code> parameter) is returned.
\r
1652 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1654 * @param set The <code>MathContext</code> arithmetic settings.
\r
1655 * @return A <code>BigDecimal</code> whose value is
\r
1656 * the maximum of <code>this</code> and <code>rhs</code>.
\r
1660 public com.ibm.icu.math.BigDecimal max(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1661 if ((this.compareTo(rhs,set))>=0)
\r
1662 return this.plus(set);
\r
1664 return rhs.plus(set);
\r
1668 * Returns a plain <code>BigDecimal</code> whose value is
\r
1669 * the minimum of <code>this</code> and <code>rhs</code>.
\r
1671 * The same as {@link #min(BigDecimal, MathContext)},
\r
1672 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1673 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1675 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1677 * @return A <code>BigDecimal</code> whose value is
\r
1678 * the minimum of <code>this</code> and <code>rhs</code>.
\r
1682 public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs){
\r
1683 return this.min(rhs,plainMC);
\r
1687 * Returns a <code>BigDecimal</code> whose value is
\r
1688 * the minimum of <code>this</code> and <code>rhs</code>.
\r
1690 * Returns the smaller of the current object and the first parameter.
\r
1692 * If calling the {@link #compareTo(BigDecimal, MathContext)} method
\r
1693 * with the same parameters would return <code>-1</code> or
\r
1694 * <code>0</code>, then the result of calling the
\r
1695 * {@link #plus(MathContext)} method on the current object (using the
\r
1696 * same <code>MathContext</code> parameter) is returned.
\r
1697 * Otherwise, the result of calling the {@link #plus(MathContext)}
\r
1698 * method on the first parameter object (using the same
\r
1699 * <code>MathContext</code> parameter) is returned.
\r
1701 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1703 * @param set The <code>MathContext</code> arithmetic settings.
\r
1704 * @return A <code>BigDecimal</code> whose value is
\r
1705 * the minimum of <code>this</code> and <code>rhs</code>.
\r
1709 public com.ibm.icu.math.BigDecimal min(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1710 if ((this.compareTo(rhs,set))<=0)
\r
1711 return this.plus(set);
\r
1713 return rhs.plus(set);
\r
1717 * Returns a plain <code>BigDecimal</code> whose value is
\r
1718 * <code>this*rhs</code>, using fixed point arithmetic.
\r
1720 * The same as {@link #add(BigDecimal, MathContext)},
\r
1721 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1722 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1724 * The length of the decimal part (the scale) of the result will be
\r
1725 * the sum of the scales of the operands, if they were formatted
\r
1726 * without exponential notation.
\r
1728 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1729 * the multiplication.
\r
1730 * @return A <code>BigDecimal</code> whose value is
\r
1731 * <code>this*rhs</code>, using fixed point arithmetic.
\r
1735 public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs){
\r
1736 return this.multiply(rhs,plainMC);
\r
1740 * Returns a <code>BigDecimal</code> whose value is <code>this*rhs</code>.
\r
1742 * Implements the multiplication (<b><code>*</code></b>) operator
\r
1743 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1745 * and returns the result as a <code>BigDecimal</code> object.
\r
1747 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1748 * the multiplication.
\r
1749 * @param set The <code>MathContext</code> arithmetic settings.
\r
1750 * @return A <code>BigDecimal</code> whose value is
\r
1751 * <code>this*rhs</code>.
\r
1755 public com.ibm.icu.math.BigDecimal multiply(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
1756 com.ibm.icu.math.BigDecimal lhs;
\r
1759 byte multer[]=null;
\r
1760 byte multand[]=null;
\r
1763 com.ibm.icu.math.BigDecimal res;
\r
1767 if (set.lostDigits)
\r
1768 checkdigits(rhs,set.digits);
\r
1769 lhs=this; // name for clarity and proxy
\r
1771 /* Prepare numbers (truncate, unless unlimited precision) */
\r
1772 padding=0; // trailing 0's to add
\r
1773 reqdig=set.digits; // local copy
\r
1776 if (lhs.mant.length>reqdig)
\r
1777 lhs=clone(lhs).round(set);
\r
1778 if (rhs.mant.length>reqdig)
\r
1779 rhs=clone(rhs).round(set);
\r
1780 // [we could reuse the new LHS for result in this case]
\r
1784 // fixed point arithmetic will want every trailing 0; we add these
\r
1785 // after the calculation rather than before, for speed.
\r
1787 padding=padding+lhs.exp;
\r
1789 padding=padding+rhs.exp;
\r
1792 // For best speed, as in DMSRCN, we use the shorter number as the
\r
1793 // multiplier and the longer as the multiplicand.
\r
1794 // 1999.12.22: We used to special case when the result would fit in
\r
1795 // a long, but with Java 1.3 this gave no advantage.
\r
1796 if (lhs.mant.length<rhs.mant.length)
\r
1807 /* Calculate how long result byte array will be */
\r
1808 multandlen=(multer.length+multand.length)-1; // effective length
\r
1809 // optimize for 75% of the cases where a carry is expected...
\r
1810 if ((multer[0]*multand[0])>9)
\r
1811 acclen=multandlen+1;
\r
1813 acclen=multandlen;
\r
1815 /* Now the main long multiplication loop */
\r
1816 res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
\r
1817 acc=new byte[acclen]; // accumulator, all zeros
\r
1818 // 1998.07.01: calculate from left to right so that accumulator goes
\r
1819 // to likely final length on first addition; this avoids a one-digit
\r
1820 // extension (and object allocation) each time around the loop.
\r
1821 // Initial number therefore has virtual zeros added to right.
\r
1822 {int $7=multer.length;n=0;for(;$7>0;$7--,n++){
\r
1825 { // [optimization]
\r
1826 // accumulate [accumulator is reusable array]
\r
1827 acc=byteaddsub(acc,acc.length,multand,multandlen,mult,true);
\r
1829 // divide multiplicand by 10 for next digit to right
\r
1830 multandlen--; // 'virtual length'
\r
1834 res.ind=(byte)(lhs.ind*rhs.ind); // final sign
\r
1835 res.exp=(lhs.exp+rhs.exp)-padding; // final exponent
\r
1836 // [overflow is checked by finish]
\r
1838 /* add trailing zeros to the result, if necessary */
\r
1842 res.mant=extend(acc,acc.length+padding); // add trailing 0s
\r
1843 return res.finish(set,false);
\r
1847 * Returns a plain <code>BigDecimal</code> whose value is
\r
1848 * <code>-this</code>.
\r
1850 * The same as {@link #negate(MathContext)}, where the context is
\r
1851 * <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1853 * The length of the decimal part (the scale) of the result will be
\r
1854 * be <code>this.scale()</code>
\r
1857 * @return A <code>BigDecimal</code> whose value is
\r
1858 * <code>-this</code>.
\r
1862 public com.ibm.icu.math.BigDecimal negate(){
\r
1863 return this.negate(plainMC);
\r
1867 * Returns a <code>BigDecimal</code> whose value is <code>-this</code>.
\r
1869 * Implements the negation (Prefix <b><code>-</code></b>) operator
\r
1870 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1872 * and returns the result as a <code>BigDecimal</code> object.
\r
1874 * @param set The <code>MathContext</code> arithmetic settings.
\r
1875 * @return A <code>BigDecimal</code> whose value is
\r
1876 * <code>-this</code>.
\r
1880 public com.ibm.icu.math.BigDecimal negate(com.ibm.icu.math.MathContext set){
\r
1881 com.ibm.icu.math.BigDecimal res;
\r
1882 // Originally called minus(), changed to matched Java precedents
\r
1883 // This simply clones, flips the sign, and possibly rounds
\r
1884 if (set.lostDigits)
\r
1885 checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
\r
1886 res=clone(this); // safe copy
\r
1887 res.ind=(byte)-res.ind;
\r
1888 return res.finish(set,false);
\r
1892 * Returns a plain <code>BigDecimal</code> whose value is
\r
1893 * <code>+this</code>.
\r
1894 * Note that <code>this</code> is not necessarily a
\r
1895 * plain <code>BigDecimal</code>, but the result will always be.
\r
1897 * The same as {@link #plus(MathContext)}, where the context is
\r
1898 * <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1900 * The length of the decimal part (the scale) of the result will be
\r
1901 * be <code>this.scale()</code>
\r
1903 * @return A <code>BigDecimal</code> whose value is
\r
1904 * <code>+this</code>.
\r
1908 public com.ibm.icu.math.BigDecimal plus(){
\r
1909 return this.plus(plainMC);
\r
1913 * Returns a <code>BigDecimal</code> whose value is
\r
1914 * <code>+this</code>.
\r
1916 * Implements the plus (Prefix <b><code>+</code></b>) operator
\r
1917 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1919 * and returns the result as a <code>BigDecimal</code> object.
\r
1921 * This method is useful for rounding or otherwise applying a context
\r
1922 * to a decimal value.
\r
1924 * @param set The <code>MathContext</code> arithmetic settings.
\r
1925 * @return A <code>BigDecimal</code> whose value is
\r
1926 * <code>+this</code>.
\r
1930 public com.ibm.icu.math.BigDecimal plus(com.ibm.icu.math.MathContext set){
\r
1931 // This clones and forces the result to the new settings
\r
1932 // May return same object
\r
1933 if (set.lostDigits)
\r
1934 checkdigits((com.ibm.icu.math.BigDecimal)null,set.digits);
\r
1935 // Optimization: returns same object for some common cases
\r
1936 if (set.form==com.ibm.icu.math.MathContext.PLAIN)
\r
1937 if (this.form==com.ibm.icu.math.MathContext.PLAIN)
\r
1939 if (this.mant.length<=set.digits)
\r
1941 if (set.digits==0)
\r
1944 return clone(this).finish(set,false);
\r
1948 * Returns a plain <code>BigDecimal</code> whose value is
\r
1949 * <code>this**rhs</code>, using fixed point arithmetic.
\r
1951 * The same as {@link #pow(BigDecimal, MathContext)},
\r
1952 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
1953 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
1955 * The parameter is the power to which the <code>this</code> will be
\r
1956 * raised; it must be in the range 0 through 999999999, and must
\r
1957 * have a decimal part of zero. Note that these restrictions may be
\r
1958 * removed in the future, so they should not be used as a test for a
\r
1961 * In addition, the power must not be negative, as no
\r
1962 * <code>MathContext</code> is used and so the result would then
\r
1965 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1966 * the operation (the power).
\r
1967 * @return A <code>BigDecimal</code> whose value is
\r
1968 * <code>this**rhs</code>, using fixed point arithmetic.
\r
1969 * @throws ArithmeticException if <code>rhs</code> is out of range or
\r
1970 * is not a whole number.
\r
1974 public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs){
\r
1975 return this.pow(rhs,plainMC);
\r
1977 // The name for this method is inherited from the precedent set by the
\r
1978 // BigInteger and Math classes.
\r
1981 * Returns a <code>BigDecimal</code> whose value is <code>this**rhs</code>.
\r
1983 * Implements the power (<b><code>**</code></b>) operator
\r
1984 * (as defined in the decimal documentation, see {@link BigDecimal
\r
1986 * and returns the result as a <code>BigDecimal</code> object.
\r
1988 * The first parameter is the power to which the <code>this</code>
\r
1989 * will be raised; it must be in the range -999999999 through
\r
1990 * 999999999, and must have a decimal part of zero. Note that these
\r
1991 * restrictions may be removed in the future, so they should not be
\r
1992 * used as a test for a whole number.
\r
1994 * If the <code>digits</code> setting of the <code>MathContext</code>
\r
1995 * parameter is 0, the power must be zero or positive.
\r
1997 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
1998 * the operation (the power).
\r
1999 * @param set The <code>MathContext</code> arithmetic settings.
\r
2000 * @return A <code>BigDecimal</code> whose value is
\r
2001 * <code>this**rhs</code>.
\r
2002 * @throws ArithmeticException if <code>rhs</code> is out of range or
\r
2003 * is not a whole number.
\r
2007 public com.ibm.icu.math.BigDecimal pow(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
2009 com.ibm.icu.math.BigDecimal lhs;
\r
2013 com.ibm.icu.math.MathContext workset;
\r
2014 com.ibm.icu.math.BigDecimal res;
\r
2017 if (set.lostDigits)
\r
2018 checkdigits(rhs,set.digits);
\r
2019 n=rhs.intcheck(MinArg,MaxArg); // check RHS by the rules
\r
2020 lhs=this; // clarified name
\r
2022 reqdig=set.digits; // local copy (heavily used)
\r
2025 if (rhs.ind==isneg)
\r
2026 throw new java.lang.ArithmeticException("Negative power:"+" "+rhs.toString());
\r
2030 {/* non-0 digits */
\r
2031 if ((rhs.mant.length+rhs.exp)>reqdig)
\r
2032 throw new java.lang.ArithmeticException("Too many digits:"+" "+rhs.toString());
\r
2034 /* Round the lhs to DIGITS if need be */
\r
2035 if (lhs.mant.length>reqdig)
\r
2036 lhs=clone(lhs).round(set);
\r
2038 /* L for precision calculation [see ANSI X3.274-1996] */
\r
2039 L=rhs.mant.length+rhs.exp; // length without decimal zeros/exp
\r
2040 workdigits=(reqdig+L)+1; // calculate the working DIGITS
\r
2043 /* Create a copy of set for working settings */
\r
2044 // Note: no need to check for lostDigits again.
\r
2045 // 1999.07.17 Note: this construction must follow RHS check
\r
2046 workset=new com.ibm.icu.math.MathContext(workdigits,set.form,false,set.roundingMode);
\r
2048 res=ONE; // accumulator
\r
2050 return res; // x**0 == 1
\r
2052 n=(int)-n; // [rhs.ind records the sign]
\r
2053 seenbit=false; // set once we've seen a 1-bit
\r
2054 {i=1;i:for(;;i++){ // for each bit [top bit ignored]
\r
2055 n=n+n; // shift left 1 bit
\r
2057 { // top bit is set
\r
2058 seenbit=true; // OK, we're off
\r
2059 res=res.multiply(lhs,workset); // acc=acc*x
\r
2062 break i; // that was the last bit
\r
2064 continue i; // we don't have to square 1
\r
2065 res=res.multiply(res,workset); // acc=acc*acc [square]
\r
2068 if (rhs.ind<0) // was a **-n [hence digits>0]
\r
2069 res=ONE.divide(res,workset); // .. so acc=1/acc
\r
2070 return res.finish(set,true); // round and strip [original digits]
\r
2074 * Returns a plain <code>BigDecimal</code> whose value is
\r
2075 * the remainder of <code>this/rhs</code>, using fixed point arithmetic.
\r
2077 * The same as {@link #remainder(BigDecimal, MathContext)},
\r
2078 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
2079 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
2081 * This is not the modulo operator -- the result may be negative.
\r
2083 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
2084 * the remainder operation.
\r
2085 * @return A <code>BigDecimal</code> whose value is the remainder
\r
2086 * of <code>this/rhs</code>, using fixed point arithmetic.
\r
2087 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
2091 public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs){
\r
2092 return this.dodivide('R',rhs,plainMC,-1);
\r
2096 * Returns a <code>BigDecimal</code> whose value is the remainder of
\r
2097 * <code>this/rhs</code>.
\r
2099 * Implements the remainder operator
\r
2100 * (as defined in the decimal documentation, see {@link BigDecimal
\r
2102 * and returns the result as a <code>BigDecimal</code> object.
\r
2104 * This is not the modulo operator -- the result may be negative.
\r
2106 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
2107 * the remainder operation.
\r
2108 * @param set The <code>MathContext</code> arithmetic settings.
\r
2109 * @return A <code>BigDecimal</code> whose value is the remainder
\r
2110 * of <code>this+rhs</code>.
\r
2111 * @throws ArithmeticException if <code>rhs</code> is zero.
\r
2112 * @throws ArithmeticException if the integer part of the result will
\r
2113 * not fit in the number of digits specified for the
\r
2118 public com.ibm.icu.math.BigDecimal remainder(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
2119 return this.dodivide('R',rhs,set,-1);
\r
2123 * Returns a plain <code>BigDecimal</code> whose value is
\r
2124 * <code>this-rhs</code>, using fixed point arithmetic.
\r
2126 * The same as {@link #subtract(BigDecimal, MathContext)},
\r
2127 * where the <code>BigDecimal</code> is <code>rhs</code>,
\r
2128 * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>.
\r
2130 * The length of the decimal part (the scale) of the result will be
\r
2131 * the maximum of the scales of the two operands.
\r
2133 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
2134 * the subtraction.
\r
2135 * @return A <code>BigDecimal</code> whose value is
\r
2136 * <code>this-rhs</code>, using fixed point arithmetic.
\r
2140 public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs){
\r
2141 return this.subtract(rhs,plainMC);
\r
2145 * Returns a <code>BigDecimal</code> whose value is <code>this-rhs</code>.
\r
2147 * Implements the subtraction (<b><code>-</code></b>) operator
\r
2148 * (as defined in the decimal documentation, see {@link BigDecimal
\r
2150 * and returns the result as a <code>BigDecimal</code> object.
\r
2152 * @param rhs The <code>BigDecimal</code> for the right hand side of
\r
2153 * the subtraction.
\r
2154 * @param set The <code>MathContext</code> arithmetic settings.
\r
2155 * @return A <code>BigDecimal</code> whose value is
\r
2156 * <code>this-rhs</code>.
\r
2160 public com.ibm.icu.math.BigDecimal subtract(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){
\r
2161 com.ibm.icu.math.BigDecimal newrhs;
\r
2162 if (set.lostDigits)
\r
2163 checkdigits(rhs,set.digits);
\r
2164 // [add will recheck .. but would report -rhs]
\r
2165 /* carry out the subtraction */
\r
2166 // we could fastpath -0, but it is too rare.
\r
2167 newrhs=clone(rhs); // safe copy
\r
2168 newrhs.ind=(byte)-newrhs.ind; // prepare to subtract
\r
2169 return this.add(newrhs,set); // arithmetic
\r
2172 /* ---------------------------------------------------------------- */
\r
2173 /* Other methods */
\r
2174 /* ---------------------------------------------------------------- */
\r
2177 * Converts this <code>BigDecimal</code> to a <code>byte</code>.
\r
2178 * If the <code>BigDecimal</code> has a non-zero decimal part or is
\r
2179 * out of the possible range for a <code>byte</code> (8-bit signed
\r
2180 * integer) result then an <code>ArithmeticException</code> is thrown.
\r
2182 * @return A <code>byte</code> equal in value to <code>this</code>.
\r
2183 * @throws ArithmeticException if <code>this</code> has a non-zero
\r
2184 * decimal part, or will not fit in a <code>byte</code>.
\r
2188 public byte byteValueExact(){
\r
2190 num=this.intValueExact(); // will check decimal part too
\r
2191 if ((num>127)|(num<(-128)))
\r
2192 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
2197 * Compares this <code>BigDecimal</code> with the value of the parameter.
\r
2199 * If the parameter is <code>null</code>, or is not an instance of the
\r
2200 * <code>BigDecimal</code> type, an exception is thrown.
\r
2201 * Otherwise, the parameter is cast to type <code>BigDecimal</code>
\r
2202 * and the result of the {@link #compareTo(BigDecimal)} method,
\r
2203 * using the cast parameter, is returned.
\r
2205 * The {@link #compareTo(BigDecimal, MathContext)} method should be
\r
2206 * used when a <code>MathContext</code> is needed for the comparison.
\r
2208 * @param rhsobj The <code>Object</code> for the right hand side of
\r
2210 * @return An <code>int</code> whose value is -1, 0, or 1 as
\r
2211 * <code>this</code> is numerically less than, equal to,
\r
2212 * or greater than <code>rhs</code>.
\r
2213 * @throws ClassCastException if <code>rhs</code> cannot be cast to
\r
2214 * a <code>BigDecimal</code> object.
\r
2215 * @see #compareTo(BigDecimal)
\r
2219 public int compareTo(java.lang.Object rhsobj){
\r
2220 // the cast in the next line will raise ClassCastException if necessary
\r
2221 return compareTo((com.ibm.icu.math.BigDecimal)rhsobj,plainMC);
\r
2225 * Converts this <code>BigDecimal</code> to a <code>double</code>.
\r
2226 * If the <code>BigDecimal</code> is out of the possible range for a
\r
2227 * <code>double</code> (64-bit signed floating point) result then an
\r
2228 * <code>ArithmeticException</code> is thrown.
\r
2230 * The double produced is identical to result of expressing the
\r
2231 * <code>BigDecimal</code> as a <code>String</code> and then
\r
2232 * converting it using the <code>Double(String)</code> constructor;
\r
2233 * this can result in values of <code>Double.NEGATIVE_INFINITY</code>
\r
2234 * or <code>Double.POSITIVE_INFINITY</code>.
\r
2236 * @return A <code>double</code> corresponding to <code>this</code>.
\r
2240 public double doubleValue(){
\r
2241 // We go via a String [as does BigDecimal in JDK 1.2]
\r
2242 // Next line could possibly raise NumberFormatException
\r
2243 return java.lang.Double.valueOf(this.toString()).doubleValue();
\r
2247 * Compares this <code>BigDecimal</code> with <code>rhs</code> for
\r
2250 * If the parameter is <code>null</code>, or is not an instance of the
\r
2251 * BigDecimal type, or is not exactly equal to the current
\r
2252 * <code>BigDecimal</code> object, then <i>false</i> is returned.
\r
2253 * Otherwise, <i>true</i> is returned.
\r
2255 * "Exactly equal", here, means that the <code>String</code>
\r
2256 * representations of the <code>BigDecimal</code> numbers are
\r
2257 * identical (they have the same characters in the same sequence).
\r
2259 * The {@link #compareTo(BigDecimal, MathContext)} method should be
\r
2260 * used for more general comparisons.
\r
2261 * @param obj The <code>Object</code> for the right hand side of
\r
2263 * @return A <code>boolean</code> whose value <i>true</i> if and
\r
2264 * only if the operands have identical string representations.
\r
2265 * @throws ClassCastException if <code>rhs</code> cannot be cast to
\r
2266 * a <code>BigDecimal</code> object.
\r
2268 * @see #compareTo(Object)
\r
2269 * @see #compareTo(BigDecimal)
\r
2270 * @see #compareTo(BigDecimal, MathContext)
\r
2273 public boolean equals(java.lang.Object obj){
\r
2274 com.ibm.icu.math.BigDecimal rhs;
\r
2278 // We are equal iff toString of both are exactly the same
\r
2280 return false; // not equal
\r
2281 if ((!(((obj instanceof com.ibm.icu.math.BigDecimal)))))
\r
2282 return false; // not a decimal
\r
2283 rhs=(com.ibm.icu.math.BigDecimal)obj; // cast; we know it will work
\r
2284 if (this.ind!=rhs.ind)
\r
2285 return false; // different signs never match
\r
2286 if (((this.mant.length==rhs.mant.length)&(this.exp==rhs.exp))&(this.form==rhs.form))
\r
2288 { // mantissas say all
\r
2289 // here with equal-length byte arrays to compare
\r
2290 {int $8=this.mant.length;i=0;for(;$8>0;$8--,i++){
\r
2291 if (this.mant[i]!=rhs.mant[i])
\r
2297 { // need proper layout
\r
2298 lca=this.layout(); // layout to character array
\r
2300 if (lca.length!=rca.length)
\r
2301 return false; // mismatch
\r
2302 // here with equal-length character arrays to compare
\r
2303 {int $9=lca.length;i=0;for(;$9>0;$9--,i++){
\r
2304 if (lca[i]!=rca[i])
\r
2309 return true; // arrays have identical content
\r
2313 * Converts this <code>BigDecimal</code> to a <code>float</code>.
\r
2314 * If the <code>BigDecimal</code> is out of the possible range for a
\r
2315 * <code>float</code> (32-bit signed floating point) result then an
\r
2316 * <code>ArithmeticException</code> is thrown.
\r
2318 * The float produced is identical to result of expressing the
\r
2319 * <code>BigDecimal</code> as a <code>String</code> and then
\r
2320 * converting it using the <code>Float(String)</code> constructor;
\r
2321 * this can result in values of <code>Float.NEGATIVE_INFINITY</code>
\r
2322 * or <code>Float.POSITIVE_INFINITY</code>.
\r
2324 * @return A <code>float</code> corresponding to <code>this</code>.
\r
2328 public float floatValue(){
\r
2329 return java.lang.Float.valueOf(this.toString()).floatValue();
\r
2333 * Returns the <code>String</code> representation of this
\r
2334 * <code>BigDecimal</code>, modified by layout parameters.
\r
2336 * <i>This method is provided as a primitive for use by more
\r
2337 * sophisticated classes, such as <code>DecimalFormat</code>, that
\r
2338 * can apply locale-sensitive editing of the result. The level of
\r
2339 * formatting that it provides is a necessary part of the BigDecimal
\r
2340 * class as it is sensitive to and must follow the calculation and
\r
2341 * rounding rules for BigDecimal arithmetic.
\r
2342 * However, if the function is provided elsewhere, it may be removed
\r
2343 * from this class. </i>
\r
2345 * The parameters, for both forms of the <code>format</code> method
\r
2346 * are all of type <code>int</code>.
\r
2347 * A value of -1 for any parameter indicates that the default action
\r
2348 * or value for that parameter should be used.
\r
2350 * The parameters, <code>before</code> and <code>after</code>,
\r
2351 * specify the number of characters to be used for the integer part
\r
2352 * and decimal part of the result respectively. Exponential notation
\r
2353 * is not used. If either parameter is -1 (which indicates the default
\r
2354 * action), the number of characters used will be exactly as many as
\r
2355 * are needed for that part.
\r
2357 * <code>before</code> must be a positive number; if it is larger than
\r
2358 * is needed to contain the integer part, that part is padded on the
\r
2359 * left with blanks to the requested length. If <code>before</code> is
\r
2360 * not large enough to contain the integer part of the number
\r
2361 * (including the sign, for negative numbers) an exception is thrown.
\r
2363 * <code>after</code> must be a non-negative number; if it is not the
\r
2364 * same size as the decimal part of the number, the number will be
\r
2365 * rounded (or extended with zeros) to fit. Specifying 0 for
\r
2366 * <code>after</code> will cause the number to be rounded to an
\r
2367 * integer (that is, it will have no decimal part or decimal point).
\r
2368 * The rounding method will be the default,
\r
2369 * <code>MathContext.ROUND_HALF_UP</code>.
\r
2371 * Other rounding methods, and the use of exponential notation, can
\r
2372 * be selected by using {@link #format(int,int,int,int,int,int)}.
\r
2373 * Using the two-parameter form of the method has exactly the same
\r
2374 * effect as using the six-parameter form with the final four
\r
2375 * parameters all being -1.
\r
2377 * @param before The <code>int</code> specifying the number of places
\r
2378 * before the decimal point. Use -1 for 'as many as
\r
2380 * @param after The <code>int</code> specifying the number of places
\r
2381 * after the decimal point. Use -1 for 'as many as are
\r
2383 * @return A <code>String</code> representing this
\r
2384 * <code>BigDecimal</code>, laid out according to the
\r
2385 * specified parameters
\r
2386 * @throws ArithmeticException if the number cannot be laid out as
\r
2388 * @throws IllegalArgumentException if a parameter is out of range.
\r
2391 * @see #toCharArray
\r
2394 public java.lang.String format(int before,int after){
\r
2395 return format(before,after,-1,-1,com.ibm.icu.math.MathContext.SCIENTIFIC,ROUND_HALF_UP);
\r
2399 * Returns the <code>String</code> representation of this
\r
2400 * <code>BigDecimal</code>, modified by layout parameters and allowing
\r
2401 * exponential notation.
\r
2403 * <i>This method is provided as a primitive for use by more
\r
2404 * sophisticated classes, such as <code>DecimalFormat</code>, that
\r
2405 * can apply locale-sensitive editing of the result. The level of
\r
2406 * formatting that it provides is a necessary part of the BigDecimal
\r
2407 * class as it is sensitive to and must follow the calculation and
\r
2408 * rounding rules for BigDecimal arithmetic.
\r
2409 * However, if the function is provided elsewhere, it may be removed
\r
2410 * from this class. </i>
\r
2412 * The parameters are all of type <code>int</code>.
\r
2413 * A value of -1 for any parameter indicates that the default action
\r
2414 * or value for that parameter should be used.
\r
2416 * The first two parameters (<code>before</code> and
\r
2417 * <code>after</code>) specify the number of characters to be used for
\r
2418 * the integer part and decimal part of the result respectively, as
\r
2419 * defined for {@link #format(int,int)}.
\r
2420 * If either of these is -1 (which indicates the default action), the
\r
2421 * number of characters used will be exactly as many as are needed for
\r
2424 * The remaining parameters control the use of exponential notation
\r
2425 * and rounding. Three (<code>explaces</code>, <code>exdigits</code>,
\r
2426 * and <code>exform</code>) control the exponent part of the result.
\r
2427 * As before, the default action for any of these parameters may be
\r
2428 * selected by using the value -1.
\r
2430 * <code>explaces</code> must be a positive number; it sets the number
\r
2431 * of places (digits after the sign of the exponent) to be used for
\r
2432 * any exponent part, the default (when <code>explaces</code> is -1)
\r
2433 * being to use as many as are needed.
\r
2434 * If <code>explaces</code> is not -1, space is always reserved for
\r
2435 * an exponent; if one is not needed (for example, if the exponent
\r
2436 * will be 0) then <code>explaces</code>+2 blanks are appended to the
\r
2438 * <!-- (This preserves vertical alignment of similarly formatted
\r
2439 * numbers in a monospace font.) -->
\r
2440 * If <code>explaces</code> is not -1 and is not large enough to
\r
2441 * contain the exponent, an exception is thrown.
\r
2443 * <code>exdigits</code> sets the trigger point for use of exponential
\r
2444 * notation. If, before any rounding, the number of places needed
\r
2445 * before the decimal point exceeds <code>exdigits</code>, or if the
\r
2446 * absolute value of the result is less than <code>0.000001</code>,
\r
2447 * then exponential form will be used, provided that
\r
2448 * <code>exdigits</code> was specified.
\r
2449 * When <code>exdigits</code> is -1, exponential notation will never
\r
2450 * be used. If 0 is specified for <code>exdigits</code>, exponential
\r
2451 * notation is always used unless the exponent would be 0.
\r
2453 * <code>exform</code> sets the form for exponential notation (if
\r
2455 * It may be either {@link MathContext#SCIENTIFIC} or
\r
2456 * {@link MathContext#ENGINEERING}.
\r
2457 * If the latter, engineering, form is requested, up to three digits
\r
2458 * (plus sign, if negative) may be needed for the integer part of the
\r
2459 * result (<code>before</code>). Otherwise, only one digit (plus
\r
2460 * sign, if negative) is needed.
\r
2462 * Finally, the sixth argument, <code>exround</code>, selects the
\r
2463 * rounding algorithm to be used, and must be one of the values
\r
2464 * indicated by a public constant in the {@link MathContext} class
\r
2465 * whose name starts with <code>ROUND_</code>.
\r
2466 * The default (<code>ROUND_HALF_UP</code>) may also be selected by
\r
2467 * using the value -1, as before.
\r
2469 * The special value <code>MathContext.ROUND_UNNECESSARY</code> may be
\r
2470 * used to detect whether non-zero digits are discarded -- if
\r
2471 * <code>exround</code> has this value than if non-zero digits would
\r
2472 * be discarded (rounded) during formatting then an
\r
2473 * <code>ArithmeticException</code> is thrown.
\r
2475 * @param before The <code>int</code> specifying the number of places
\r
2476 * before the decimal point.
\r
2477 * Use -1 for 'as many as are needed'.
\r
2478 * @param after The <code>int</code> specifying the number of places
\r
2479 * after the decimal point.
\r
2480 * Use -1 for 'as many as are needed'.
\r
2481 * @param explaces The <code>int</code> specifying the number of places
\r
2482 * to be used for any exponent.
\r
2483 * Use -1 for 'as many as are needed'.
\r
2484 * @param exdigits The <code>int</code> specifying the trigger
\r
2485 * (digits before the decimal point) which if
\r
2486 * exceeded causes exponential notation to be used.
\r
2487 * Use 0 to force exponential notation.
\r
2488 * Use -1 to force plain notation (no exponential
\r
2490 * @param exformint The <code>int</code> specifying the form of
\r
2491 * exponential notation to be used
\r
2492 * ({@link MathContext#SCIENTIFIC} or
\r
2493 * {@link MathContext#ENGINEERING}).
\r
2494 * @param exround The <code>int</code> specifying the rounding mode
\r
2496 * Use -1 for the default, {@link MathContext#ROUND_HALF_UP}.
\r
2497 * @return A <code>String</code> representing this
\r
2498 * <code>BigDecimal</code>, laid out according to the
\r
2499 * specified parameters
\r
2500 * @throws ArithmeticException if the number cannot be laid out as
\r
2502 * @throws IllegalArgumentException if a parameter is out of range.
\r
2504 * @see #toCharArray
\r
2508 public java.lang.String format(int before,int after,int explaces,int exdigits,int exformint,int exround){
\r
2509 com.ibm.icu.math.BigDecimal num;
\r
2513 byte newmant[]=null;
\r
2524 /* Check arguments */
\r
2525 if ((before<(-1))|(before==0))
\r
2526 badarg("format",1,java.lang.String.valueOf(before));
\r
2528 badarg("format",2,java.lang.String.valueOf(after));
\r
2529 if ((explaces<(-1))|(explaces==0))
\r
2530 badarg("format",3,java.lang.String.valueOf(explaces));
\r
2531 if (exdigits<(-1))
\r
2532 badarg("format",4,java.lang.String.valueOf(explaces));
\r
2534 if (exformint==com.ibm.icu.math.MathContext.SCIENTIFIC){
\r
2535 }else if (exformint==com.ibm.icu.math.MathContext.ENGINEERING){
\r
2536 }else if (exformint==(-1))
\r
2537 exformint=com.ibm.icu.math.MathContext.SCIENTIFIC;
\r
2538 // note PLAIN isn't allowed
\r
2540 badarg("format",5,java.lang.String.valueOf(exformint));
\r
2543 // checking the rounding mode is done by trying to construct a
\r
2544 // MathContext object with that mode; it will fail if bad
\r
2545 if (exround!=ROUND_HALF_UP)
\r
2546 {try{ // if non-default...
\r
2547 if (exround==(-1))
\r
2548 exround=ROUND_HALF_UP;
\r
2550 new com.ibm.icu.math.MathContext(9,com.ibm.icu.math.MathContext.SCIENTIFIC,false,exround);
\r
2552 catch (java.lang.IllegalArgumentException $10){
\r
2553 badarg("format",6,java.lang.String.valueOf(exround));
\r
2556 num=clone(this); // make private copy
\r
2559 num is BigDecimal to format
\r
2560 before is places before point [>0]
\r
2561 after is places after point [>=0]
\r
2562 explaces is exponent places [>0]
\r
2563 exdigits is exponent digits [>=0]
\r
2564 exformint is exponent form [one of two]
\r
2565 exround is rounding mode [one of eight]
\r
2566 'before' through 'exdigits' are -1 if not specified
\r
2569 /* determine form */
\r
2571 if (exdigits==(-1))
\r
2572 num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
\r
2573 else if (num.ind==iszero)
\r
2574 num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
\r
2576 // determine whether triggers
\r
2577 mag=num.exp+num.mant.length;
\r
2578 if (mag>exdigits)
\r
2579 num.form=(byte)exformint;
\r
2582 num.form=(byte)exformint;
\r
2584 num.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
\r
2586 }while(false);}/*setform*/
\r
2588 /* If 'after' was specified then we may need to adjust the
\r
2589 mantissa. This is a little tricky, as we must conform to the
\r
2590 rules of exponential layout if necessary (e.g., we cannot end up
\r
2591 with 10.0 if scientific). */
\r
2593 {setafter:for(;;){
\r
2594 // calculate the current after-length
\r
2596 if (num.form==com.ibm.icu.math.MathContext.PLAIN)
\r
2597 thisafter=(int)-num.exp; // has decimal part
\r
2598 else if (num.form==com.ibm.icu.math.MathContext.SCIENTIFIC)
\r
2599 thisafter=num.mant.length-1;
\r
2600 else{ // engineering
\r
2601 lead=(((num.exp+num.mant.length)-1))%3; // exponent to use
\r
2603 lead=3+lead; // negative exponent case
\r
2604 lead++; // number of leading digits
\r
2605 if (lead>=num.mant.length)
\r
2608 thisafter=num.mant.length-lead;
\r
2611 if (thisafter==after)
\r
2612 break setafter; // we're in luck
\r
2613 if (thisafter<after)
\r
2614 { // need added trailing zeros
\r
2615 // [thisafter can be negative]
\r
2616 newmant=extend(num.mant,(num.mant.length+after)-thisafter);
\r
2618 num.exp=num.exp-((after-thisafter)); // adjust exponent
\r
2619 if (num.exp<MinExp)
\r
2620 throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+num.exp);
\r
2623 // We have too many digits after the decimal point; this could
\r
2624 // cause a carry, which could change the mantissa...
\r
2625 // Watch out for implied leading zeros in PLAIN case
\r
2626 chop=thisafter-after; // digits to lop [is >0]
\r
2627 if (chop>num.mant.length)
\r
2628 { // all digits go, no chance of carry
\r
2629 // carry on with zero
\r
2630 num.mant=ZERO.mant;
\r
2633 continue setafter; // recheck: we may need trailing zeros
\r
2635 // we have a digit to inspect from existing mantissa
\r
2636 // round the number as required
\r
2637 need=num.mant.length-chop; // digits to end up with [may be 0]
\r
2638 oldexp=num.exp; // save old exponent
\r
2639 num.round(need,exround);
\r
2640 // if the exponent grew by more than the digits we chopped, then
\r
2641 // we must have had a carry, so will need to recheck the layout
\r
2642 if ((num.exp-oldexp)==chop)
\r
2643 break setafter; // number did not have carry
\r
2644 // mantissa got extended .. so go around and check again
\r
2648 a=num.layout(); // lay out, with exponent if required, etc.
\r
2650 /* Here we have laid-out number in 'a' */
\r
2651 // now apply 'before' and 'explaces' as needed
\r
2654 // look for '.' or 'E'
\r
2655 {int $11=a.length;p=0;p:for(;$11>0;$11--,p++){
\r
2662 // p is now offset of '.', 'E', or character after end of array
\r
2663 // that is, the current length of before part
\r
2665 badarg("format",1,java.lang.String.valueOf(before)); // won't fit
\r
2667 { // need leading blanks
\r
2668 newa=new char[(a.length+before)-p];
\r
2669 {int $12=before-p;i=0;for(;$12>0;$12--,i++){
\r
2673 java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,i,a.length);
\r
2676 // [if p=before then it's just the right length]
\r
2681 // look for 'E' [cannot be at offset 0]
\r
2682 {int $13=a.length-1;p=a.length-1;p:for(;$13>0;$13--,p--){
\r
2687 // p is now offset of 'E', or 0
\r
2689 { // no E part; add trailing blanks
\r
2690 newa=new char[(a.length+explaces)+2];
\r
2691 java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,a.length);
\r
2692 {int $14=explaces+2;i=a.length;for(;$14>0;$14--,i++){
\r
2699 {/* found E */ // may need to insert zeros
\r
2700 places=(a.length-p)-2; // number so far
\r
2701 if (places>explaces)
\r
2702 badarg("format",3,java.lang.String.valueOf(explaces));
\r
2703 if (places<explaces)
\r
2704 { // need to insert zeros
\r
2705 newa=new char[(a.length+explaces)-places];
\r
2706 java.lang.System.arraycopy((java.lang.Object)a,0,(java.lang.Object)newa,0,p+2); // through E and sign
\r
2707 {int $15=explaces-places;i=p+2;for(;$15>0;$15--,i++){
\r
2711 java.lang.System.arraycopy((java.lang.Object)a,p+2,(java.lang.Object)newa,i,places); // remainder of exponent
\r
2714 // [if places=explaces then it's just the right length]
\r
2717 return new java.lang.String(a);
\r
2721 * Returns the hashcode for this <code>BigDecimal</code>.
\r
2722 * This hashcode is suitable for use by the
\r
2723 * <code>java.util.Hashtable</code> class.
\r
2725 * Note that two <code>BigDecimal</code> objects are only guaranteed
\r
2726 * to produce the same hashcode if they are exactly equal (that is,
\r
2727 * the <code>String</code> representations of the
\r
2728 * <code>BigDecimal</code> numbers are identical -- they have the same
\r
2729 * characters in the same sequence).
\r
2731 * @return An <code>int</code> that is the hashcode for <code>this</code>.
\r
2735 public int hashCode(){
\r
2736 // Maybe calculate ourselves, later. If so, note that there can be
\r
2737 // more than one internal representation for a given toString() result.
\r
2738 return this.toString().hashCode();
\r
2742 * Converts this <code>BigDecimal</code> to an <code>int</code>.
\r
2743 * If the <code>BigDecimal</code> has a non-zero decimal part it is
\r
2744 * discarded. If the <code>BigDecimal</code> is out of the possible
\r
2745 * range for an <code>int</code> (32-bit signed integer) result then
\r
2746 * only the low-order 32 bits are used. (That is, the number may be
\r
2747 * <i>decapitated</i>.) To avoid unexpected errors when these
\r
2748 * conditions occur, use the {@link #intValueExact} method.
\r
2750 * @return An <code>int</code> converted from <code>this</code>,
\r
2751 * truncated and decapitated if necessary.
\r
2755 public int intValue(){
\r
2756 return toBigInteger().intValue();
\r
2760 * Converts this <code>BigDecimal</code> to an <code>int</code>.
\r
2761 * If the <code>BigDecimal</code> has a non-zero decimal part or is
\r
2762 * out of the possible range for an <code>int</code> (32-bit signed
\r
2763 * integer) result then an <code>ArithmeticException</code> is thrown.
\r
2765 * @return An <code>int</code> equal in value to <code>this</code>.
\r
2766 * @throws ArithmeticException if <code>this</code> has a non-zero
\r
2767 * decimal part, or will not fit in an
\r
2768 * <code>int</code>.
\r
2772 public int intValueExact(){
\r
2778 // This does not use longValueExact() as the latter can be much
\r
2780 // intcheck (from pow) relies on this to check decimal part
\r
2782 return 0; // easy, and quite common
\r
2783 /* test and drop any trailing decimal part */
\r
2784 lodigit=mant.length-1;
\r
2787 lodigit=lodigit+exp; // reduces by -(-exp)
\r
2788 /* all decimal places must be 0 */
\r
2789 if ((!(allzero(mant,lodigit+1))))
\r
2790 throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
\r
2792 return 0; // -1<this<1
\r
2797 if ((exp+lodigit)>9) // early exit
\r
2798 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
2801 /* convert the mantissa to binary, inline for speed */
\r
2803 {int $16=lodigit+useexp;i=0;for(;i<=$16;i++){
\r
2806 result=result+mant[i];
\r
2810 /* Now, if the risky length, check for overflow */
\r
2811 if ((lodigit+useexp)==9)
\r
2813 // note we cannot just test for -ve result, as overflow can move a
\r
2814 // zero into the top bit [consider 5555555555]
\r
2815 topdig=result/1000000000; // get top digit, preserving sign
\r
2816 if (topdig!=mant[0])
\r
2817 { // digit must match and be positive
\r
2818 // except in the special case ...
\r
2819 if (result==java.lang.Integer.MIN_VALUE) // looks like the special
\r
2820 if (ind==isneg) // really was negative
\r
2822 return result; // really had top digit 2
\r
2823 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
2830 return (int)-result;
\r
2834 * Converts this <code>BigDecimal</code> to a <code>long</code>.
\r
2835 * If the <code>BigDecimal</code> has a non-zero decimal part it is
\r
2836 * discarded. If the <code>BigDecimal</code> is out of the possible
\r
2837 * range for a <code>long</code> (64-bit signed integer) result then
\r
2838 * only the low-order 64 bits are used. (That is, the number may be
\r
2839 * <i>decapitated</i>.) To avoid unexpected errors when these
\r
2840 * conditions occur, use the {@link #longValueExact} method.
\r
2842 * @return A <code>long</code> converted from <code>this</code>,
\r
2843 * truncated and decapitated if necessary.
\r
2847 public long longValue(){
\r
2848 return toBigInteger().longValue();
\r
2852 * Converts this <code>BigDecimal</code> to a <code>long</code>.
\r
2853 * If the <code>BigDecimal</code> has a non-zero decimal part or is
\r
2854 * out of the possible range for a <code>long</code> (64-bit signed
\r
2855 * integer) result then an <code>ArithmeticException</code> is thrown.
\r
2857 * @return A <code>long</code> equal in value to <code>this</code>.
\r
2858 * @throws ArithmeticException if <code>this</code> has a non-zero
\r
2859 * decimal part, or will not fit in a
\r
2860 * <code>long</code>.
\r
2864 public long longValueExact(){
\r
2871 // Identical to intValueExact except for result=long, and exp>=20 test
\r
2873 return 0; // easy, and quite common
\r
2874 lodigit=mant.length-1; // last included digit
\r
2877 lodigit=lodigit+exp; // -(-exp)
\r
2878 /* all decimal places must be 0 */
\r
2883 if ((!(allzero(mant,cstart))))
\r
2884 throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
\r
2886 return 0; // -1<this<1
\r
2891 if ((exp+mant.length)>18) // early exit
\r
2892 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
2896 /* convert the mantissa to binary, inline for speed */
\r
2897 // note that we could safely use the 'test for wrap to negative'
\r
2898 // algorithm here, but instead we parallel the intValueExact
\r
2899 // algorithm for ease of checking and maintenance.
\r
2901 {int $17=lodigit+useexp;i=0;for(;i<=$17;i++){
\r
2904 result=result+mant[i];
\r
2908 /* Now, if the risky length, check for overflow */
\r
2909 if ((lodigit+useexp)==18)
\r
2911 topdig=result/1000000000000000000L; // get top digit, preserving sign
\r
2912 if (topdig!=mant[0])
\r
2913 { // digit must match and be positive
\r
2914 // except in the special case ...
\r
2915 if (result==java.lang.Long.MIN_VALUE) // looks like the special
\r
2916 if (ind==isneg) // really was negative
\r
2918 return result; // really had top digit 9
\r
2919 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
2926 return (long)-result;
\r
2930 * Returns a plain <code>BigDecimal</code> whose decimal point has
\r
2931 * been moved to the left by a specified number of positions.
\r
2932 * The parameter, <code>n</code>, specifies the number of positions to
\r
2933 * move the decimal point.
\r
2934 * That is, if <code>n</code> is 0 or positive, the number returned is
\r
2937 * this.multiply(TEN.pow(new BigDecimal(-n)))
\r
2940 * <code>n</code> may be negative, in which case the method returns
\r
2941 * the same result as <code>movePointRight(-n)</code>.
\r
2943 * @param n The <code>int</code> specifying the number of places to
\r
2944 * move the decimal point leftwards.
\r
2945 * @return A <code>BigDecimal</code> derived from
\r
2946 * <code>this</code>, with the decimal point moved
\r
2947 * <code>n</code> places to the left.
\r
2951 public com.ibm.icu.math.BigDecimal movePointLeft(int n){
\r
2952 com.ibm.icu.math.BigDecimal res;
\r
2953 // very little point in optimizing for shift of 0
\r
2955 res.exp=res.exp-n;
\r
2956 return res.finish(plainMC,false); // finish sets form and checks exponent
\r
2960 * Returns a plain <code>BigDecimal</code> whose decimal point has
\r
2961 * been moved to the right by a specified number of positions.
\r
2962 * The parameter, <code>n</code>, specifies the number of positions to
\r
2963 * move the decimal point.
\r
2964 * That is, if <code>n</code> is 0 or positive, the number returned is
\r
2967 * this.multiply(TEN.pow(new BigDecimal(n)))
\r
2970 * <code>n</code> may be negative, in which case the method returns
\r
2971 * the same result as <code>movePointLeft(-n)</code>.
\r
2973 * @param n The <code>int</code> specifying the number of places to
\r
2974 * move the decimal point rightwards.
\r
2975 * @return A <code>BigDecimal</code> derived from
\r
2976 * <code>this</code>, with the decimal point moved
\r
2977 * <code>n</code> places to the right.
\r
2981 public com.ibm.icu.math.BigDecimal movePointRight(int n){
\r
2982 com.ibm.icu.math.BigDecimal res;
\r
2984 res.exp=res.exp+n;
\r
2985 return res.finish(plainMC,false);
\r
2989 * Returns the scale of this <code>BigDecimal</code>.
\r
2990 * Returns a non-negative <code>int</code> which is the scale of the
\r
2991 * number. The scale is the number of digits in the decimal part of
\r
2992 * the number if the number were formatted without exponential
\r
2995 * @return An <code>int</code> whose value is the scale of this
\r
2996 * <code>BigDecimal</code>.
\r
3000 public int scale(){
\r
3002 return 0; // scale can never be negative
\r
3007 * Returns a plain <code>BigDecimal</code> with a given scale.
\r
3009 * If the given scale (which must be zero or positive) is the same as
\r
3010 * or greater than the length of the decimal part (the scale) of this
\r
3011 * <code>BigDecimal</code> then trailing zeros will be added to the
\r
3012 * decimal part as necessary.
\r
3014 * If the given scale is less than the length of the decimal part (the
\r
3015 * scale) of this <code>BigDecimal</code> then trailing digits
\r
3016 * will be removed, and in this case an
\r
3017 * <code>ArithmeticException</code> is thrown if any discarded digits
\r
3020 * The same as {@link #setScale(int, int)}, where the first parameter
\r
3021 * is the scale, and the second is
\r
3022 * <code>MathContext.ROUND_UNNECESSARY</code>.
\r
3024 * @param scale The <code>int</code> specifying the scale of the
\r
3025 * resulting <code>BigDecimal</code>.
\r
3026 * @return A plain <code>BigDecimal</code> with the given scale.
\r
3027 * @throws ArithmeticException if <code>scale</code> is negative.
\r
3028 * @throws ArithmeticException if reducing scale would discard
\r
3029 * non-zero digits.
\r
3033 public com.ibm.icu.math.BigDecimal setScale(int scale){
\r
3034 return setScale(scale,ROUND_UNNECESSARY);
\r
3038 * Returns a plain <code>BigDecimal</code> with a given scale.
\r
3040 * If the given scale (which must be zero or positive) is the same as
\r
3041 * or greater than the length of the decimal part (the scale) of this
\r
3042 * <code>BigDecimal</code> then trailing zeros will be added to the
\r
3043 * decimal part as necessary.
\r
3045 * If the given scale is less than the length of the decimal part (the
\r
3046 * scale) of this <code>BigDecimal</code> then trailing digits
\r
3047 * will be removed, and the rounding mode given by the second
\r
3048 * parameter is used to determine if the remaining digits are
\r
3049 * affected by a carry.
\r
3050 * In this case, an <code>IllegalArgumentException</code> is thrown if
\r
3051 * <code>round</code> is not a valid rounding mode.
\r
3053 * If <code>round</code> is <code>MathContext.ROUND_UNNECESSARY</code>,
\r
3054 * an <code>ArithmeticException</code> is thrown if any discarded
\r
3055 * digits are non-zero.
\r
3057 * @param scale The <code>int</code> specifying the scale of the
\r
3058 * resulting <code>BigDecimal</code>.
\r
3059 * @param round The <code>int</code> rounding mode to be used for
\r
3060 * the division (see the {@link MathContext} class).
\r
3061 * @return A plain <code>BigDecimal</code> with the given scale.
\r
3062 * @throws IllegalArgumentException if <code>round</code> is not a
\r
3063 * valid rounding mode.
\r
3064 * @throws ArithmeticException if <code>scale</code> is negative.
\r
3065 * @throws ArithmeticException if <code>round</code> is
\r
3066 * <code>MathContext.ROUND_UNNECESSARY</code>, and
\r
3067 * reducing scale would discard non-zero digits.
\r
3071 public com.ibm.icu.math.BigDecimal setScale(int scale,int round){
\r
3073 com.ibm.icu.math.BigDecimal res;
\r
3076 // at present this naughtily only checks the round value if it is
\r
3077 // needed (used), for speed
\r
3078 ourscale=this.scale();
\r
3079 if (ourscale==scale) // already correct scale
\r
3080 if (this.form==com.ibm.icu.math.MathContext.PLAIN) // .. and form
\r
3082 res=clone(this); // need copy
\r
3083 if (ourscale<=scale)
\r
3084 { // simply zero-padding/changing form
\r
3085 // if ourscale is 0 we may have lots of 0s to add
\r
3087 padding=res.exp+scale;
\r
3089 padding=scale-ourscale;
\r
3090 res.mant=extend(res.mant,res.mant.length+padding);
\r
3091 res.exp=(int)-scale; // as requested
\r
3094 {/* ourscale>scale: shortening, probably */
\r
3096 throw new java.lang.ArithmeticException("Negative scale:"+" "+scale);
\r
3097 // [round() will raise exception if invalid round]
\r
3098 newlen=res.mant.length-((ourscale-scale)); // [<=0 is OK]
\r
3099 res=res.round(newlen,round); // round to required length
\r
3100 // This could have shifted left if round (say) 0.9->1[.0]
\r
3101 // Repair if so by adding a zero and reducing exponent
\r
3102 if (res.exp!=((int)-scale))
\r
3104 res.mant=extend(res.mant,res.mant.length+1);
\r
3105 res.exp=res.exp-1;
\r
3108 res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // by definition
\r
3113 * Converts this <code>BigDecimal</code> to a <code>short</code>.
\r
3114 * If the <code>BigDecimal</code> has a non-zero decimal part or is
\r
3115 * out of the possible range for a <code>short</code> (16-bit signed
\r
3116 * integer) result then an <code>ArithmeticException</code> is thrown.
\r
3118 * @return A <code>short</code> equal in value to <code>this</code>.
\r
3119 * @throws ArithmeticException if <code>this</code> has a non-zero
\r
3120 * decimal part, or will not fit in a
\r
3121 * <code>short</code>.
\r
3125 public short shortValueExact(){
\r
3127 num=this.intValueExact(); // will check decimal part too
\r
3128 if ((num>32767)|(num<(-32768)))
\r
3129 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+this.toString());
\r
3130 return (short)num;
\r
3134 * Returns the sign of this <code>BigDecimal</code>, as an
\r
3135 * <code>int</code>.
\r
3136 * This returns the <i>signum</i> function value that represents the
\r
3137 * sign of this <code>BigDecimal</code>.
\r
3138 * That is, -1 if the <code>BigDecimal</code> is negative, 0 if it is
\r
3139 * numerically equal to zero, or 1 if it is positive.
\r
3141 * @return An <code>int</code> which is -1 if the
\r
3142 * <code>BigDecimal</code> is negative, 0 if it is
\r
3143 * numerically equal to zero, or 1 if it is positive.
\r
3147 public int signum(){
\r
3148 return (int)this.ind; // [note this assumes values for ind.]
\r
3151 //#if defined(FOUNDATION10)
\r
3154 * Converts this <code>BigDecimal</code> to a
\r
3155 * <code>java.math.BigDecimal</code>.
\r
3157 * This is an exact conversion; the result is the same as if the
\r
3158 * <code>BigDecimal</code> were formatted as a plain number without
\r
3159 * any rounding or exponent and then the
\r
3160 * <code>java.math.BigDecimal(java.lang.String)</code> constructor
\r
3161 * were used to construct the result.
\r
3163 * <i>(Note: this method is provided only in the
\r
3164 * <code>com.ibm.icu.math</code> version of the BigDecimal class.
\r
3165 * It would not be present in a <code>java.math</code> version.)</i>
\r
3167 * @return The <code>java.math.BigDecimal</code> equal in value
\r
3168 * to this <code>BigDecimal</code>.
\r
3172 public java.math.BigDecimal toBigDecimal(){
\r
3173 return new java.math.BigDecimal(this.unscaledValue(),this.scale());
\r
3178 * Converts this <code>BigDecimal</code> to a
\r
3179 * <code>java.math.BigInteger</code>.
\r
3181 * Any decimal part is truncated (discarded).
\r
3182 * If an exception is desired should the decimal part be non-zero,
\r
3183 * use {@link #toBigIntegerExact()}.
\r
3185 * @return The <code>java.math.BigInteger</code> equal in value
\r
3186 * to the integer part of this <code>BigDecimal</code>.
\r
3190 public java.math.BigInteger toBigInteger(){
\r
3191 com.ibm.icu.math.BigDecimal res=null;
\r
3193 byte newmant[]=null;
\r
3195 if ((exp>=0)&(form==com.ibm.icu.math.MathContext.PLAIN))
\r
3196 res=this; // can layout simply
\r
3199 res=clone(this); // safe copy
\r
3200 res.form=(byte)com.ibm.icu.math.MathContext.PLAIN; // .. and request PLAIN
\r
3203 { // exp<0; scale to be truncated
\r
3204 // we could use divideInteger, but we may as well be quicker
\r
3205 if (((int)-this.exp)>=this.mant.length)
\r
3206 res=ZERO; // all blows away
\r
3209 res=clone(this); // safe copy
\r
3210 newlen=res.mant.length+res.exp;
\r
3211 newmant=new byte[newlen]; // [shorter]
\r
3212 java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,newlen);
\r
3214 res.form=(byte)com.ibm.icu.math.MathContext.PLAIN;
\r
3220 return new BigInteger(new java.lang.String(res.layout()));
\r
3224 * Converts this <code>BigDecimal</code> to a
\r
3225 * <code>java.math.BigInteger</code>.
\r
3227 * An exception is thrown if the decimal part (if any) is non-zero.
\r
3229 * @return The <code>java.math.BigInteger</code> equal in value
\r
3230 * to the integer part of this <code>BigDecimal</code>.
\r
3231 * @throws ArithmeticException if <code>this</code> has a non-zero
\r
3236 public java.math.BigInteger toBigIntegerExact(){
\r
3237 /* test any trailing decimal part */
\r
3239 { // possible decimal part
\r
3240 /* all decimal places must be 0; note exp<0 */
\r
3241 if ((!(allzero(mant,mant.length+exp))))
\r
3242 throw new java.lang.ArithmeticException("Decimal part non-zero:"+" "+this.toString());
\r
3244 return toBigInteger();
\r
3248 * Returns the <code>BigDecimal</code> as a character array.
\r
3249 * The result of this method is the same as using the
\r
3250 * sequence <code>toString().toCharArray()</code>, but avoids creating
\r
3251 * the intermediate <code>String</code> and <code>char[]</code>
\r
3254 * @return The <code>char[]</code> array corresponding to this
\r
3255 * <code>BigDecimal</code>.
\r
3259 public char[] toCharArray(){
\r
3264 * Returns the <code>BigDecimal</code> as a <code>String</code>.
\r
3265 * This returns a <code>String</code> that exactly represents this
\r
3266 * <code>BigDecimal</code>, as defined in the decimal documentation
\r
3267 * (see {@link BigDecimal class header}).
\r
3269 * By definition, using the {@link #BigDecimal(String)} constructor
\r
3270 * on the result <code>String</code> will create a
\r
3271 * <code>BigDecimal</code> that is exactly equal to the original
\r
3272 * <code>BigDecimal</code>.
\r
3274 * @return The <code>String</code> exactly corresponding to this
\r
3275 * <code>BigDecimal</code>.
\r
3276 * @see #format(int, int)
\r
3277 * @see #format(int, int, int, int, int, int)
\r
3278 * @see #toCharArray()
\r
3282 public java.lang.String toString(){
\r
3283 return new java.lang.String(layout());
\r
3287 * Returns the number as a <code>BigInteger</code> after removing the
\r
3289 * That is, the number is expressed as a plain number, any decimal
\r
3290 * point is then removed (retaining the digits of any decimal part),
\r
3291 * and the result is then converted to a <code>BigInteger</code>.
\r
3293 * @return The <code>java.math.BigInteger</code> equal in value to
\r
3294 * this <code>BigDecimal</code> multiplied by ten to the
\r
3295 * power of <code>this.scale()</code>.
\r
3299 public java.math.BigInteger unscaledValue(){
\r
3300 com.ibm.icu.math.BigDecimal res=null;
\r
3305 res=clone(this); // safe copy
\r
3306 res.exp=0; // drop scale
\r
3308 return res.toBigInteger();
\r
3312 * Translates a <code>double</code> to a <code>BigDecimal</code>.
\r
3314 * Returns a <code>BigDecimal</code> which is the decimal
\r
3315 * representation of the 64-bit signed binary floating point
\r
3316 * parameter. If the parameter is infinite, or is not a number (NaN),
\r
3317 * a <code>NumberFormatException</code> is thrown.
\r
3319 * The number is constructed as though <code>num</code> had been
\r
3320 * converted to a <code>String</code> using the
\r
3321 * <code>Double.toString()</code> method and the
\r
3322 * {@link #BigDecimal(java.lang.String)} constructor had then been used.
\r
3323 * This is typically not an exact conversion.
\r
3325 * @param dub The <code>double</code> to be translated.
\r
3326 * @return The <code>BigDecimal</code> equal in value to
\r
3327 * <code>dub</code>.
\r
3328 * @throws NumberFormatException if the parameter is infinite or
\r
3333 public static com.ibm.icu.math.BigDecimal valueOf(double dub){
\r
3334 // Reminder: a zero double returns '0.0', so we cannot fastpath to
\r
3335 // use the constant ZERO. This might be important enough to justify
\r
3336 // a factory approach, a cache, or a few private constants, later.
\r
3337 return new com.ibm.icu.math.BigDecimal((new java.lang.Double(dub)).toString());
\r
3341 * Translates a <code>long</code> to a <code>BigDecimal</code>.
\r
3342 * That is, returns a plain <code>BigDecimal</code> whose value is
\r
3343 * equal to the given <code>long</code>.
\r
3345 * @param lint The <code>long</code> to be translated.
\r
3346 * @return The <code>BigDecimal</code> equal in value to
\r
3347 * <code>lint</code>.
\r
3351 public static com.ibm.icu.math.BigDecimal valueOf(long lint){
\r
3352 return valueOf(lint,0);
\r
3356 * Translates a <code>long</code> to a <code>BigDecimal</code> with a
\r
3358 * That is, returns a plain <code>BigDecimal</code> whose unscaled
\r
3359 * value is equal to the given <code>long</code>, adjusted by the
\r
3360 * second parameter, <code>scale</code>.
\r
3362 * The result is given by:
\r
3364 * (new BigDecimal(lint)).divide(TEN.pow(new BigDecimal(scale)))
\r
3367 * A <code>NumberFormatException</code> is thrown if <code>scale</code>
\r
3370 * @param lint The <code>long</code> to be translated.
\r
3371 * @param scale The <code>int</code> scale to be applied.
\r
3372 * @return The <code>BigDecimal</code> equal in value to
\r
3373 * <code>lint</code>.
\r
3374 * @throws NumberFormatException if the scale is negative.
\r
3378 public static com.ibm.icu.math.BigDecimal valueOf(long lint,int scale){
\r
3379 com.ibm.icu.math.BigDecimal res=null;
\r
3385 else if (lint==10)
\r
3388 res=new com.ibm.icu.math.BigDecimal(lint);
\r
3394 throw new java.lang.NumberFormatException("Negative scale:"+" "+scale);
\r
3395 res=clone(res); // safe copy [do not mutate]
\r
3396 res.exp=(int)-scale; // exponent is -scale
\r
3400 /* ---------------------------------------------------------------- */
\r
3401 /* Private methods */
\r
3402 /* ---------------------------------------------------------------- */
\r
3404 /* <sgml> Return char array value of a BigDecimal (conversion from
\r
3405 BigDecimal to laid-out canonical char array).
\r
3406 <p>The mantissa will either already have been rounded (following an
\r
3407 operation) or will be of length appropriate (in the case of
\r
3408 construction from an int, for example).
\r
3409 <p>We must not alter the mantissa, here.
\r
3410 <p>'form' describes whether we are to use exponential notation (and
\r
3411 if so, which), or if we are to lay out as a plain/pure numeric.
\r
3414 private char[] layout(){
\r
3417 java.lang.StringBuffer sb=null;
\r
3425 cmant=new char[mant.length]; // copy byte[] to a char[]
\r
3426 {int $18=mant.length;i=0;for(;$18>0;$18--,i++){
\r
3427 cmant[i]=(char)(mant[i]+((int)('0')));
\r
3431 if (form!=com.ibm.icu.math.MathContext.PLAIN)
\r
3432 {/* exponential notation needed */
\r
3433 sb=new java.lang.StringBuffer(cmant.length+15); // -x.xxxE+999999999
\r
3436 euse=(exp+cmant.length)-1; // exponent to use
\r
3437 /* setup sig=significant digits and copy to result */
\r
3438 if (form==com.ibm.icu.math.MathContext.SCIENTIFIC)
\r
3440 sb.append(cmant[0]); // significant character
\r
3441 if (cmant.length>1) // have decimal part
\r
3442 sb.append('.').append(cmant,1,cmant.length-1);
\r
3446 sig=euse%3; // common
\r
3448 sig=3+sig; // negative exponent
\r
3451 if (sig>=cmant.length)
\r
3452 { // zero padding may be needed
\r
3453 sb.append(cmant,0,cmant.length);
\r
3454 {int $19=sig-cmant.length;for(;$19>0;$19--){
\r
3460 { // decimal point needed
\r
3461 sb.append(cmant,0,sig).append('.').append(cmant,sig,cmant.length-sig);
\r
3463 }while(false);}/*engineering*/
\r
3473 sb.append('E').append(csign).append(euse);
\r
3475 rec=new char[sb.length()];
\r
3476 Utility.getChars(sb, 0,sb.length(),rec,0);
\r
3480 /* Here for non-exponential (plain) notation */
\r
3484 return cmant; // non-negative integer
\r
3485 rec=new char[cmant.length+1];
\r
3487 java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,1,cmant.length);
\r
3491 /* Need a '.' and/or some zeros */
\r
3492 needsign=(int)((ind==isneg)?1:0); // space for sign? 0 or 1
\r
3494 /* MAG is the position of the point in the mantissa (index of the
\r
3495 character it follows) */
\r
3496 mag=exp+cmant.length;
\r
3499 {/* 0.00xxxx form */
\r
3500 len=(needsign+2)-exp; // needsign+2+(-mag)+cmant.length
\r
3501 rec=new char[len];
\r
3504 rec[needsign]='0';
\r
3505 rec[needsign+1]='.';
\r
3506 {int $20=(int)-mag;i=needsign+2;for(;$20>0;$20--,i++){ // maybe none
\r
3510 java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,(needsign+2)-mag,cmant.length);
\r
3514 if (mag>cmant.length)
\r
3515 {/* xxxx0000 form */
\r
3517 rec=new char[len];
\r
3520 java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,cmant.length);
\r
3521 {int $21=mag-cmant.length;i=needsign+cmant.length;for(;$21>0;$21--,i++){ // never 0
\r
3528 /* decimal point is in the middle of the mantissa */
\r
3529 len=(needsign+1)+cmant.length;
\r
3530 rec=new char[len];
\r
3533 java.lang.System.arraycopy((java.lang.Object)cmant,0,(java.lang.Object)rec,needsign,mag);
\r
3534 rec[needsign+mag]='.';
\r
3535 java.lang.System.arraycopy((java.lang.Object)cmant,mag,(java.lang.Object)rec,(needsign+mag)+1,cmant.length-mag);
\r
3539 /* <sgml> Checks a BigDecimal argument to ensure it's a true integer
\r
3541 <p>If OK, returns it as an int. </sgml> */
\r
3542 // [currently only used by pow]
\r
3544 private int intcheck(int min,int max){
\r
3546 i=this.intValueExact(); // [checks for non-0 decimal part]
\r
3547 // Use same message as though intValueExact failed due to size
\r
3548 if ((i<min)|(i>max))
\r
3549 throw new java.lang.ArithmeticException("Conversion overflow:"+" "+i);
\r
3553 /* <sgml> Carry out division operations. </sgml> */
\r
3555 Arg1 is operation code: D=divide, I=integer divide, R=remainder
\r
3557 Arg3 is the context.
\r
3558 Arg4 is explicit scale iff code='D' or 'I' (-1 if none).
\r
3560 Underlying algorithm (complications for Remainder function and
\r
3561 scaled division are omitted for clarity):
\r
3563 Test for x/0 and then 0/x
\r
3565 Exp =Exp +len(var1) -len(var2)
\r
3566 Sign=Sign1 * Sign2
\r
3567 Pad accumulator (Var1) to double-length with 0's (pad1)
\r
3568 Pad Var2 to same length as Var1
\r
3569 B2B=1st two digits of var2, +1 to allow for roundup
\r
3571 Do until (have=digits+1 OR residue=0)
\r
3572 if exp<0 then if integer divide/residue then leave
\r
3576 if <0 then leave inner_loop
\r
3577 if =0 then (- quick exit without subtract -) do
\r
3578 this_digit=this_digit+1; output this_digit
\r
3579 leave outer_loop; end
\r
3580 Compare lengths of numbers (mantissae):
\r
3581 If same then CA=first_digit_of_Var1
\r
3582 else CA=first_two_digits_of_Var1
\r
3583 mult=ca*10/b2b -- Good and safe guess at divisor
\r
3584 if mult=0 then mult=1
\r
3585 this_digit=this_digit+mult
\r
3588 if have\=0 | this_digit\=0 then do
\r
3594 exp=exp+1 -- set the proper exponent
\r
3595 if have=0 then generate answer=0
\r
3596 Return to FINISHED
\r
3597 Result defined by MATHV1
\r
3599 For extended commentary, see DMSRCN.
\r
3602 private com.ibm.icu.math.BigDecimal dodivide(char code,com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set,int scale){
\r
3603 com.ibm.icu.math.BigDecimal lhs;
\r
3606 com.ibm.icu.math.BigDecimal res;
\r
3622 byte newvar1[]=null;
\r
3625 byte newmant[]=null;
\r
3627 if (set.lostDigits)
\r
3628 checkdigits(rhs,set.digits);
\r
3629 lhs=this; // name for clarity
\r
3631 // [note we must have checked lostDigits before the following checks]
\r
3633 throw new java.lang.ArithmeticException("Divide by 0"); // includes 0/0
\r
3635 { // 0/x => 0 [possibly with .0s]
\r
3636 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
3640 return lhs.setScale(scale);
\r
3643 /* Prepare numbers according to BigDecimal rules */
\r
3644 reqdig=set.digits; // local copy (heavily used)
\r
3647 if (lhs.mant.length>reqdig)
\r
3648 lhs=clone(lhs).round(set);
\r
3649 if (rhs.mant.length>reqdig)
\r
3650 rhs=clone(rhs).round(set);
\r
3653 {/* scaled divide */
\r
3655 scale=lhs.scale();
\r
3656 // set reqdig to be at least large enough for the computation
\r
3657 reqdig=lhs.mant.length; // base length
\r
3658 // next line handles both positive lhs.exp and also scale mismatch
\r
3659 if (scale!=((int)-lhs.exp))
\r
3660 reqdig=(reqdig+scale)+lhs.exp;
\r
3661 reqdig=(reqdig-((rhs.mant.length-1)))-rhs.exp; // reduce by RHS effect
\r
3662 if (reqdig<lhs.mant.length)
\r
3663 reqdig=lhs.mant.length; // clamp
\r
3664 if (reqdig<rhs.mant.length)
\r
3665 reqdig=rhs.mant.length; // ..
\r
3668 /* precalculate exponent */
\r
3669 newexp=((lhs.exp-rhs.exp)+lhs.mant.length)-rhs.mant.length;
\r
3670 /* If new exponent -ve, then some quick exits are possible */
\r
3675 return ZERO; // easy - no integer part
\r
3676 /* Must be 'R'; remainder is [finished clone of] input value */
\r
3677 return clone(lhs).finish(set,false);
\r
3680 /* We need slow division */
\r
3681 res=new com.ibm.icu.math.BigDecimal(); // where we'll build result
\r
3682 res.ind=(byte)(lhs.ind*rhs.ind); // final sign (for D/I)
\r
3683 res.exp=newexp; // initial exponent (for D/I)
\r
3684 res.mant=new byte[reqdig+1]; // where build the result
\r
3686 /* Now [virtually pad the mantissae with trailing zeros */
\r
3687 // Also copy the LHS, which will be our working array
\r
3688 newlen=(reqdig+reqdig)+1;
\r
3689 var1=extend(lhs.mant,newlen); // always makes longer, so new safe array
\r
3690 var1len=newlen; // [remaining digits are 0]
\r
3695 /* Calculate first two digits of rhs (var2), +1 for later estimations */
\r
3696 b2b=(var2[0]*10)+1;
\r
3697 if (var2.length>1)
\r
3700 /* start the long-division loops */
\r
3704 /* find the next digit */
\r
3706 if (var1len<var2len)
\r
3707 break inner; // V1 too low
\r
3708 if (var1len==var2len)
\r
3709 { // compare needed
\r
3710 {compare:do{ // comparison
\r
3711 {int $22=var1len;i=0;for(;$22>0;$22--,i++){
\r
3712 // var1len is always <= var1.length
\r
3713 if (i<var2.length)
\r
3718 break inner; // V1 too low
\r
3720 break compare; // OK to subtract
\r
3723 /* reach here if lhs and rhs are identical; subtraction will
\r
3724 increase digit by one, and the residue will be 0 so we
\r
3725 are done; leave the loop with residue set to 0 (in case
\r
3726 code is 'R' or ROUND_UNNECESSARY or a ROUND_HALF_xxxx is
\r
3729 res.mant[have]=(byte)thisdigit;
\r
3731 var1[0]=(byte)0; // residue to 0 [this is all we'll test]
\r
3732 // var1len=1 -- [optimized out]
\r
3734 }while(false);}/*compare*/
\r
3735 /* prepare for subtraction. Estimate BA (lengths the same) */
\r
3736 ba=(int)var1[0]; // use only first digit
\r
3737 } // lengths the same
\r
3739 {/* lhs longer than rhs */
\r
3740 /* use first two digits for estimate */
\r
3745 /* subtraction needed; V1>=V2 */
\r
3749 thisdigit=thisdigit+mult;
\r
3750 // subtract; var1 reusable
\r
3751 var1=byteaddsub(var1,var1len,var2,var2len,(int)-mult,true);
\r
3753 continue inner; // maybe another subtract needed
\r
3754 /* V1 now probably has leading zeros, remove leading 0's and try
\r
3755 again. (It could be longer than V2) */
\r
3756 {int $23=var1len-2;start=0;start:for(;start<=$23;start++){
\r
3757 if (var1[start]!=0)
\r
3765 java.lang.System.arraycopy((java.lang.Object)var1,start,(java.lang.Object)var1,0,var1len);
\r
3769 /* We have the next digit */
\r
3770 if ((have!=0)|(thisdigit!=0))
\r
3771 { // put the digit we got
\r
3772 res.mant[have]=(byte)thisdigit;
\r
3774 if (have==(reqdig+1))
\r
3775 break outer; // we have all we need
\r
3777 break outer; // residue now 0
\r
3779 /* can leave now if a scaled divide and exponent is small enough */
\r
3781 if (((int)-res.exp)>scale)
\r
3783 /* can leave now if not Divide and no integer part left */
\r
3787 res.exp=res.exp-1; // reduce the exponent
\r
3788 /* to get here, V1 is less than V2, so divide V2 by 10 and go for
\r
3794 /* here when we have finished dividing, for some reason */
\r
3795 // have is the number of digits we collected in res.mant
\r
3797 have=1; // res.mant[0] is 0; we always want a digit
\r
3799 if ((code=='I')|(code=='R'))
\r
3800 {/* check for integer overflow needed */
\r
3801 if ((have+res.exp)>reqdig)
\r
3802 throw new java.lang.ArithmeticException("Integer overflow");
\r
3806 /* We were doing Remainder -- return the residue */
\r
3807 if (res.mant[0]==0) // no integer part was found
\r
3808 return clone(lhs).finish(set,false); // .. so return lhs, canonical
\r
3810 return ZERO; // simple 0 residue
\r
3811 res.ind=lhs.ind; // sign is always as LHS
\r
3812 /* Calculate the exponent by subtracting the number of padding zeros
\r
3813 we added and adding the original exponent */
\r
3814 padding=((reqdig+reqdig)+1)-lhs.mant.length;
\r
3815 res.exp=(res.exp-padding)+lhs.exp;
\r
3817 /* strip insignificant padding zeros from residue, and create/copy
\r
3818 the resulting mantissa if need be */
\r
3820 {i=d-1;i:for(;i>=1;i--){if(!((res.exp<lhs.exp)&(res.exp<rhs.exp)))break;
\r
3824 res.exp=res.exp+1;
\r
3827 if (d<var1.length)
\r
3828 {/* need to reduce */
\r
3829 newvar1=new byte[d];
\r
3830 java.lang.System.arraycopy((java.lang.Object)var1,0,(java.lang.Object)newvar1,0,d); // shorten
\r
3834 return res.finish(set,false);
\r
3835 }while(false);}/*remainder*/
\r
3839 {/* 'D' -- no overflow check needed */
\r
3840 // If there was a residue then bump the final digit (iff 0 or 5)
\r
3841 // so that the residue is visible for ROUND_UP, ROUND_HALF_xxx and
\r
3842 // ROUND_UNNECESSARY checks (etc.) later.
\r
3843 // [if we finished early, the residue will be 0]
\r
3845 { // residue not 0
\r
3846 lasthave=res.mant[have-1];
\r
3847 if (((lasthave%5))==0)
\r
3848 res.mant[have-1]=(byte)(lasthave+1);
\r
3852 /* Here for Divide or Integer Divide */
\r
3853 // handle scaled results first ['I' always scale 0, optional for 'D']
\r
3856 // say 'scale have res.exp len' scale have res.exp res.mant.length
\r
3857 if (have!=res.mant.length)
\r
3858 // already padded with 0's, so just adjust exponent
\r
3859 res.exp=res.exp-((res.mant.length-have));
\r
3860 // calculate number of digits we really want [may be 0]
\r
3861 actdig=res.mant.length-((((int)-res.exp)-scale));
\r
3862 res.round(actdig,set.roundingMode); // round to desired length
\r
3863 // This could have shifted left if round (say) 0.9->1[.0]
\r
3864 // Repair if so by adding a zero and reducing exponent
\r
3865 if (res.exp!=((int)-scale))
\r
3867 res.mant=extend(res.mant,res.mant.length+1);
\r
3868 res.exp=res.exp-1;
\r
3870 return res.finish(set,true); // [strip if not PLAIN]
\r
3871 }while(false);}/*scaled*/
\r
3873 // reach here only if a non-scaled
\r
3874 if (have==res.mant.length)
\r
3875 { // got digits+1 digits
\r
3880 {/* have<=reqdig */
\r
3881 if (res.mant[0]==0)
\r
3882 return ZERO; // fastpath
\r
3883 // make the mantissa truly just 'have' long
\r
3884 // [we could let finish do this, during strip, if we adjusted
\r
3885 // the exponent; however, truncation avoids the strip loop]
\r
3886 newmant=new byte[have]; // shorten
\r
3887 java.lang.System.arraycopy((java.lang.Object)res.mant,0,(java.lang.Object)newmant,0,have);
\r
3890 return res.finish(set,true);
\r
3894 /* <sgml> Report a conversion exception. </sgml> */
\r
3896 private void bad(char s[]){
\r
3897 throw new java.lang.NumberFormatException("Not a number:"+" "+java.lang.String.valueOf(s));
\r
3900 /* <sgml> Report a bad argument to a method. </sgml>
\r
3901 Arg1 is method name
\r
3902 Arg2 is argument position
\r
3903 Arg3 is what was found */
\r
3905 private void badarg(java.lang.String name,int pos,java.lang.String value){
\r
3906 throw new java.lang.IllegalArgumentException("Bad argument"+" "+pos+" "+"to"+" "+name+":"+" "+value);
\r
3909 /* <sgml> Extend byte array to given length, padding with 0s. If no
\r
3910 extension is required then return the same array. </sgml>
\r
3912 Arg1 is the source byte array
\r
3913 Arg2 is the new length (longer)
\r
3916 private static final byte[] extend(byte inarr[],int newlen){
\r
3918 if (inarr.length==newlen)
\r
3920 newarr=new byte[newlen];
\r
3921 java.lang.System.arraycopy((java.lang.Object)inarr,0,(java.lang.Object)newarr,0,inarr.length);
\r
3922 // 0 padding is carried out by the JVM on allocation initialization
\r
3926 /* <sgml> Add or subtract two >=0 integers in byte arrays
\r
3927 <p>This routine performs the calculation:
\r
3931 Where M is in the range -9 through +9
\r
3933 If M<0 then A>=B must be true, so the result is always
\r
3936 Leading zeros are not removed after a subtraction. The result is
\r
3937 either the same length as the longer of A and B, or 1 longer than
\r
3938 that (if a carry occurred).
\r
3940 A is not altered unless Arg6 is 1.
\r
3941 B is never altered.
\r
3944 Arg2 is A length to use (if longer than A, pad with 0's)
\r
3946 Arg4 is B length to use (if longer than B, pad with 0's)
\r
3947 Arg5 is M, the multiplier
\r
3948 Arg6 is 1 if A can be used to build the result (if it fits)
\r
3950 This routine is severely performance-critical; *any* change here
\r
3951 must be measured (timed) to assure no performance degradation.
\r
3953 // 1996.02.20 -- enhanced version of DMSRCN algorithm (1981)
\r
3954 // 1997.10.05 -- changed to byte arrays (from char arrays)
\r
3955 // 1998.07.01 -- changed to allow destructive reuse of LHS
\r
3956 // 1998.07.01 -- changed to allow virtual lengths for the arrays
\r
3957 // 1998.12.29 -- use lookaside for digit/carry calculation
\r
3958 // 1999.08.07 -- avoid multiply when mult=1, and make db an int
\r
3959 // 1999.12.22 -- special case m=-1, also drop 0 special case
\r
3961 private static final byte[] byteaddsub(byte a[],int avlen,byte b[],int bvlen,int m,boolean reuse){
\r
3978 // We'll usually be right if we assume no carry
\r
3979 alength=a.length; // physical lengths
\r
3980 blength=b.length; // ..
\r
3981 ap=avlen-1; // -> final (rightmost) digit
\r
3986 reb=(byte[])null; // result byte array
\r
3988 if ((maxarr+1)==alength)
\r
3989 reb=a; // OK to reuse A
\r
3991 reb=new byte[maxarr+1]; // need new array
\r
3993 quickm=false; // 1 if no multiply needed
\r
3995 quickm=true; // most common
\r
3998 quickm=true; // also common
\r
4000 digit=0; // digit, with carry or borrow
\r
4001 {op=maxarr;op:for(;op>=0;op--){
\r
4005 digit=digit+a[ap]; // within A
\r
4015 digit=digit+b[bp]; // most common
\r
4017 digit=digit-b[bp]; // also common
\r
4020 digit=digit+(b[bp]*m);
\r
4024 /* result so far (digit) could be -90 through 99 */
\r
4028 reb[op]=(byte)digit;
\r
4029 digit=0; // no carry
\r
4031 }while(false);}/*quick*/
\r
4033 reb[op]=bytedig[dp90]; // this digit
\r
4034 digit=bytecar[dp90]; // carry or borrow
\r
4039 return reb; // no carry
\r
4040 // following line will become an Assert, later
\r
4041 // if digit<0 then signal ArithmeticException("internal.error ["digit"]")
\r
4043 /* We have carry -- need to make space for the extra digit */
\r
4044 newarr=(byte[])null;
\r
4046 if ((maxarr+2)==a.length)
\r
4047 newarr=a; // OK to reuse A
\r
4048 if (newarr==null)
\r
4049 newarr=new byte[maxarr+2];
\r
4050 newarr[0]=(byte)digit; // the carried digit ..
\r
4051 // .. and all the rest [use local loop for short numbers]
\r
4053 {int $24=maxarr+1;i=0;for(;$24>0;$24--,i++){
\r
4054 newarr[i+1]=reb[i];
\r
4058 java.lang.System.arraycopy((java.lang.Object)reb,0,(java.lang.Object)newarr,1,maxarr+1);
\r
4062 /* <sgml> Initializer for digit array properties (lookaside). </sgml>
\r
4063 Returns the digit array, and initializes the carry array. */
\r
4065 private static final byte[] diginit(){
\r
4069 work=new byte[(90+99)+1];
\r
4070 {op=0;op:for(;op<=(90+99);op++){
\r
4074 work[op]=(byte)(digit%10);
\r
4075 bytecar[op]=(byte)(digit/10); // calculate carry
\r
4079 digit=digit+100; // yes, this is right [consider -50]
\r
4080 work[op]=(byte)(digit%10);
\r
4081 bytecar[op]=(byte)((digit/10)-10); // calculate borrow [NB: - after %]
\r
4087 /* <sgml> Create a copy of BigDecimal object for local use.
\r
4088 <p>This does NOT make a copy of the mantissa array.
\r
4090 Arg1 is the BigDecimal to clone (non-null)
\r
4093 private static final com.ibm.icu.math.BigDecimal clone(com.ibm.icu.math.BigDecimal dec){
\r
4094 com.ibm.icu.math.BigDecimal copy;
\r
4095 copy=new com.ibm.icu.math.BigDecimal();
\r
4098 copy.form=dec.form;
\r
4099 copy.mant=dec.mant;
\r
4103 /* <sgml> Check one or two numbers for lost digits. </sgml>
\r
4104 Arg1 is RHS (or null, if none)
\r
4105 Arg2 is current DIGITS setting
\r
4106 returns quietly or throws an exception */
\r
4108 private void checkdigits(com.ibm.icu.math.BigDecimal rhs,int dig){
\r
4110 return; // don't check if digits=0
\r
4111 // first check lhs...
\r
4112 if (this.mant.length>dig)
\r
4113 if ((!(allzero(this.mant,dig))))
\r
4114 throw new java.lang.ArithmeticException("Too many digits:"+" "+this.toString());
\r
4116 return; // monadic
\r
4117 if (rhs.mant.length>dig)
\r
4118 if ((!(allzero(rhs.mant,dig))))
\r
4119 throw new java.lang.ArithmeticException("Too many digits:"+" "+rhs.toString());
\r
4122 /* <sgml> Round to specified digits, if necessary. </sgml>
\r
4123 Arg1 is requested MathContext [with length and rounding mode]
\r
4124 returns this, for convenience */
\r
4126 private com.ibm.icu.math.BigDecimal round(com.ibm.icu.math.MathContext set){
\r
4127 return round(set.digits,set.roundingMode);
\r
4130 /* <sgml> Round to specified digits, if necessary.
\r
4131 Arg1 is requested length (digits to round to)
\r
4132 [may be <=0 when called from format, dodivide, etc.]
\r
4133 Arg2 is rounding mode
\r
4134 returns this, for convenience
\r
4136 ind and exp are adjusted, but not cleared for a mantissa of zero
\r
4138 The length of the mantissa returned will be Arg1, except when Arg1
\r
4139 is 0, in which case the returned mantissa length will be 1.
\r
4143 private com.ibm.icu.math.BigDecimal round(int len,int mode){
\r
4147 boolean reuse=false;
\r
4150 byte newmant[]=null;
\r
4151 adjust=mant.length-len;
\r
4153 return this; // nowt to do
\r
4155 exp=exp+adjust; // exponent of result
\r
4156 sign=(int)ind; // save [assumes -1, 0, 1]
\r
4157 oldmant=mant; // save
\r
4160 // remove the unwanted digits
\r
4161 mant=new byte[len];
\r
4162 java.lang.System.arraycopy((java.lang.Object)oldmant,0,(java.lang.Object)mant,0,len);
\r
4163 reuse=true; // can reuse mantissa
\r
4164 first=oldmant[len]; // first of discarded digits
\r
4170 reuse=false; // cannot reuse mantissa
\r
4174 first=(byte)0; // [virtual digit]
\r
4177 // decide rounding adjustment depending on mode, sign, and discarded digits
\r
4178 increment=0; // bumper
\r
4180 if (mode==ROUND_HALF_UP)
\r
4181 { // default first [most common]
\r
4185 else if (mode==ROUND_UNNECESSARY)
\r
4186 { // default for setScale()
\r
4187 // discarding any non-zero digits is an error
\r
4188 if ((!(allzero(oldmant,len))))
\r
4189 throw new java.lang.ArithmeticException("Rounding necessary");
\r
4191 else if (mode==ROUND_HALF_DOWN)
\r
4192 { // 0.5000 goes down
\r
4197 if ((!(allzero(oldmant,len+1))))
\r
4200 else if (mode==ROUND_HALF_EVEN)
\r
4201 { // 0.5000 goes down if left digit even
\r
4207 if ((!(allzero(oldmant,len+1))))
\r
4210 if ((((mant[mant.length-1])%2))==1)
\r
4214 else if (mode==ROUND_DOWN){
\r
4215 // never increment
\r
4216 }else if (mode==ROUND_UP)
\r
4217 { // increment if discarded non-zero
\r
4218 if ((!(allzero(oldmant,len))))
\r
4221 else if (mode==ROUND_CEILING)
\r
4222 { // more positive
\r
4224 if ((!(allzero(oldmant,len))))
\r
4227 else if (mode==ROUND_FLOOR)
\r
4228 { // more negative
\r
4230 if ((!(allzero(oldmant,len))))
\r
4234 throw new java.lang.IllegalArgumentException("Bad round value:"+" "+mode);
\r
4236 }while(false);}/*modes*/
\r
4238 if (increment!=0)
\r
4242 // we must not subtract from 0, but result is trivial anyway
\r
4244 ind=(byte)increment;
\r
4248 // mantissa is non-0; we can safely add or subtract 1
\r
4250 increment=(int)-increment;
\r
4251 newmant=byteaddsub(mant,mant.length,ONE.mant,1,increment,reuse);
\r
4252 if (newmant.length>mant.length)
\r
4254 // drop rightmost digit and raise exponent
\r
4256 // mant is already the correct length
\r
4257 java.lang.System.arraycopy((java.lang.Object)newmant,0,(java.lang.Object)mant,0,mant.length);
\r
4262 }while(false);}/*bump*/
\r
4263 // rounding can increase exponent significantly
\r
4265 throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+exp);
\r
4269 /* <sgml> Test if rightmost digits are all 0.
\r
4270 Arg1 is a mantissa array to test
\r
4271 Arg2 is the offset of first digit to check
\r
4272 [may be negative; if so, digits to left are 0's]
\r
4273 returns 1 if all the digits starting at Arg2 are 0
\r
4275 Arg2 may be beyond array bounds, in which case 1 is returned
\r
4278 private static final boolean allzero(byte array[],int start){
\r
4282 {int $25=array.length-1;i=start;for(;i<=$25;i++){
\r
4290 /* <sgml> Carry out final checks and canonicalization
\r
4292 This finishes off the current number by:
\r
4293 1. Rounding if necessary (NB: length includes leading zeros)
\r
4294 2. Stripping trailing zeros (if requested and \PLAIN)
\r
4295 3. Stripping leading zeros (always)
\r
4296 4. Selecting exponential notation (if required)
\r
4297 5. Converting a zero result to just '0' (if \PLAIN)
\r
4298 In practice, these operations overlap and share code.
\r
4299 It always sets form.
\r
4301 Arg1 is requested MathContext (length to round to, trigger, and FORM)
\r
4302 Arg2 is 1 if trailing insignificant zeros should be removed after
\r
4303 round (for division, etc.), provided that set.form isn't PLAIN.
\r
4304 returns this, for convenience
\r
4307 private com.ibm.icu.math.BigDecimal finish(com.ibm.icu.math.MathContext set,boolean strip){
\r
4310 byte newmant[]=null;
\r
4313 /* Round if mantissa too long and digits requested */
\r
4314 if (set.digits!=0)
\r
4315 if (this.mant.length>set.digits)
\r
4318 /* If strip requested (and standard formatting), remove
\r
4319 insignificant trailing zeros. */
\r
4321 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
4323 d=this.mant.length;
\r
4324 /* see if we need to drop any trailing zeros */
\r
4325 {i=d-1;i:for(;i>=1;i--){
\r
4326 if (this.mant[i]!=0)
\r
4332 if (d<this.mant.length)
\r
4333 {/* need to reduce */
\r
4334 newmant=new byte[d];
\r
4335 java.lang.System.arraycopy((java.lang.Object)this.mant,0,(java.lang.Object)newmant,0,d);
\r
4336 this.mant=newmant;
\r
4340 form=(byte)com.ibm.icu.math.MathContext.PLAIN; // preset
\r
4342 /* Now check for leading- and all- zeros in mantissa */
\r
4343 {int $26=this.mant.length;i=0;for(;$26>0;$26--,i++){
\r
4344 if (this.mant[i]!=0)
\r
4346 // non-0 result; ind will be correct
\r
4347 // remove leading zeros [e.g., after subtract]
\r
4350 newmant=new byte[this.mant.length-i];
\r
4351 java.lang.System.arraycopy((java.lang.Object)this.mant,i,(java.lang.Object)newmant,0,this.mant.length-i);
\r
4352 this.mant=newmant;
\r
4353 }while(false);}/*delead*/
\r
4354 // now determine form if not PLAIN
\r
4355 mag=exp+mant.length;
\r
4357 { // most common path
\r
4358 if (mag>set.digits)
\r
4359 if (set.digits!=0)
\r
4360 form=(byte)set.form;
\r
4361 if ((mag-1)<=MaxExp)
\r
4362 return this; // no overflow; quick return
\r
4366 form=(byte)set.form;
\r
4367 /* check for overflow */
\r
4369 if ((mag<MinExp)|(mag>MaxExp))
\r
4371 // possible reprieve if form is engineering
\r
4372 if (form==com.ibm.icu.math.MathContext.ENGINEERING)
\r
4374 sig=mag%3; // leftover
\r
4376 sig=3+sig; // negative exponent
\r
4377 mag=mag-sig; // exponent to use
\r
4378 // 1999.06.29: second test here must be MaxExp
\r
4383 throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+mag);
\r
4384 }while(false);}/*overflow*/
\r
4390 // Drop through to here only if mantissa is all zeros
\r
4393 if (set.form!=com.ibm.icu.math.MathContext.PLAIN)
\r
4394 exp=0; // standard result; go to '0'
\r
4396 exp=0; // +ve exponent also goes to '0'
\r
4398 // a plain number with -ve exponent; preserve and check exponent
\r
4400 throw new java.lang.ArithmeticException("Exponent Overflow:"+" "+exp);
\r
4403 mant=ZERO.mant; // canonical mantissa
\r