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