UNPKG

big-decimal

Version:

Javascript version of the com.ibm.icu.math.BigDecimal and com.ibm.icu.math.MathContext Java classes from the ICU4J project.

1,369 lines (1,287 loc) 171 kB
/* Generated from 'BigDecimal.nrx' 8 Sep 2000 11:10:50 [v2.00] */ /* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */ //--package com.ibm.icu.math; //--import java.math.BigInteger; //--import com.ibm.icu.impl.Utility; /* ------------------------------------------------------------------ */ /* BigDecimal -- Decimal arithmetic for Java */ /* ------------------------------------------------------------------ */ /* Copyright IBM Corporation, 1996, 2000. All Rights Reserved. */ /* */ /* The BigDecimal class provides immutable arbitrary-precision */ /* floating point (including integer) decimal numbers. */ /* */ /* As the numbers are decimal, there is an exact correspondence */ /* between an instance of a BigDecimal object and its String */ /* representation; the BigDecimal class provides direct conversions */ /* to and from String and character array objects, and well as */ /* conversions to and from the Java primitive types (which may not */ /* be exact). */ /* ------------------------------------------------------------------ */ /* Notes: */ /* */ /* 1. A BigDecimal object is never changed in value once constructed; */ /* this avoids the need for locking. Note in particular that the */ /* mantissa array may be shared between many BigDecimal objects, */ /* so that once exposed it must not be altered. */ /* */ /* 2. This class looks at MathContext class fields directly (for */ /* performance). It must not and does not change them. */ /* */ /* 3. Exponent checking is delayed until finish(), as we know */ /* intermediate calculations cannot cause 31-bit overflow. */ /* [This assertion depends on MAX_DIGITS in MathContext.] */ /* */ /* 4. Comments for the public API now follow the javadoc conventions. */ /* The NetRexx -comments option is used to pass these comments */ /* through to the generated Java code (with -format, if desired). */ /* */ /* 5. System.arraycopy is faster than explicit loop as follows */ /* Mean length 4: equal */ /* Mean length 8: x2 */ /* Mean length 16: x3 */ /* Mean length 24: x4 */ /* From prior experience, we expect mean length a little below 8, */ /* but arraycopy is still the one to use, in general, until later */ /* measurements suggest otherwise. */ /* */ /* 6. 'DMSRCN' referred to below is the original (1981) IBM S/370 */ /* assembler code implementation of the algorithms below; it is */ /* now called IXXRCN and is available with the OS/390 and VM/ESA */ /* operating systems. */ /* ------------------------------------------------------------------ */ /* Change History: */ /* 1997.09.02 Initial version (derived from netrexx.lang classes) */ /* 1997.09.12 Add lostDigits checking */ /* 1997.10.06 Change mantissa to a byte array */ /* 1997.11.22 Rework power [did not prepare arguments, etc.] */ /* 1997.12.13 multiply did not prepare arguments */ /* 1997.12.14 add did not prepare and align arguments correctly */ /* 1998.05.02 0.07 packaging changes suggested by Sun and Oracle */ /* 1998.05.21 adjust remainder operator finalization */ /* 1998.06.04 rework to pass MathContext to finish() and round() */ /* 1998.06.06 change format to use round(); support rounding modes */ /* 1998.06.25 rename to BigDecimal and begin merge */ /* zero can now have trailing zeros (i.e., exp\=0) */ /* 1998.06.28 new methods: movePointXxxx, scale, toBigInteger */ /* unscaledValue, valueof */ /* 1998.07.01 improve byteaddsub to allow array reuse, etc. */ /* 1998.07.01 make null testing explicit to avoid JIT bug [Win32] */ /* 1998.07.07 scaled division [divide(BigDecimal, int, int)] */ /* 1998.07.08 setScale, faster equals */ /* 1998.07.11 allow 1E6 (no sign) <sigh>; new double/float conversion */ /* 1998.10.12 change package to com.ibm.icu.math */ /* 1998.12.14 power operator no longer rounds RHS [to match ANSI] */ /* add toBigDecimal() and BigDecimal(java.math.BigDecimal) */ /* 1998.12.29 improve byteaddsub by using table lookup */ /* 1999.02.04 lostdigits=0 behaviour rounds instead of digits+1 guard */ /* 1999.02.05 cleaner code for BigDecimal(char[]) */ /* 1999.02.06 add javadoc comments */ /* 1999.02.11 format() changed from 7 to 2 method form */ /* 1999.03.05 null pointer checking is no longer explicit */ /* 1999.03.05 simplify; changes from discussion with J. Bloch: */ /* null no longer permitted for MathContext; drop boolean, */ /* byte, char, float, short constructor, deprecate double */ /* constructor, no blanks in string constructor, add */ /* offset and length version of char[] constructor; */ /* add valueOf(double); drop booleanValue, charValue; */ /* add ...Exact versions of remaining convertors */ /* 1999.03.13 add toBigIntegerExact */ /* 1999.03.13 1.00 release to IBM Centre for Java Technology */ /* 1999.05.27 1.01 correct 0-0.2 bug under scaled arithmetic */ /* 1999.06.29 1.02 constructors should not allow exponent > 9 digits */ /* 1999.07.03 1.03 lost digits should not be checked if digits=0 */ /* 1999.07.06 lost digits Exception message changed */ /* 1999.07.10 1.04 more work on 0-0.2 (scaled arithmetic) */ /* 1999.07.17 improve messages from pow method */ /* 1999.08.08 performance tweaks */ /* 1999.08.15 fastpath in multiply */ /* 1999.11.05 1.05 fix problem in intValueExact [e.g., 5555555555] */ /* 1999.12.22 1.06 remove multiply fastpath, and improve performance */ /* 2000.01.01 copyright update [Y2K has arrived] */ /* 2000.06.18 1.08 no longer deprecate BigDecimal(double) */ /* ------------------------------------------------------------------ */ /* JavaScript conversion (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany */ function div(a, b) { return (a-(a%b))/b; } BigDecimal.prototype.div = div; function arraycopy(src, srcindex, dest, destindex, length) { var i; if (destindex > srcindex) { // in case src and dest are equals, but also doesn't hurt // if they are different for (i = length-1; i >= 0; --i) { dest[i+destindex] = src[i+srcindex]; } } else { for (i = 0; i < length; ++i) { dest[i+destindex] = src[i+srcindex]; } } } BigDecimal.prototype.arraycopy = arraycopy; function createArrayWithZeros(length) { var retVal = new Array(length); var i; for (i = 0; i < length; ++i) { retVal[i] = 0; } return retVal; } BigDecimal.prototype.createArrayWithZeros = createArrayWithZeros; /** * The <code>BigDecimal</code> class implements immutable * arbitrary-precision decimal numbers. The methods of the * <code>BigDecimal</code> class provide operations for fixed and * floating point arithmetic, comparison, format conversions, and * hashing. * <p> * As the numbers are decimal, there is an exact correspondence between * an instance of a <code>BigDecimal</code> object and its * <code>String</code> representation; the <code>BigDecimal</code> class * provides direct conversions to and from <code>String</code> and * character array (<code>char[]</code>) objects, as well as conversions * to and from the Java primitive types (which may not be exact) and * <code>BigInteger</code>. * <p> * In the descriptions of constructors and methods in this documentation, * the value of a <code>BigDecimal</code> number object is shown as the * result of invoking the <code>toString()</code> method on the object. * The internal representation of a decimal number is neither defined * nor exposed, and is not permitted to affect the result of any * operation. * <p> * The floating point arithmetic provided by this class is defined by * the ANSI X3.274-1996 standard, and is also documented at * <code>http://www2.hursley.ibm.com/decimal</code> * <br><i>[This URL will change.]</i> * * <h3>Operator methods</h3> * <p> * Operations on <code>BigDecimal</code> numbers are controlled by a * {@link MathContext} object, which provides the context (precision and * other information) for the operation. Methods that can take a * <code>MathContext</code> parameter implement the standard arithmetic * operators for <code>BigDecimal</code> objects and are known as * <i>operator methods</i>. The default settings provided by the * constant {@link MathContext#DEFAULT} (<code>digits=9, * form=SCIENTIFIC, lostDigits=false, roundingMode=ROUND_HALF_UP</code>) * perform general-purpose floating point arithmetic to nine digits of * precision. The <code>MathContext</code> parameter must not be * <code>null</code>. * <p> * Each operator method also has a version provided which does * not take a <code>MathContext</code> parameter. For this version of * each method, the context settings used are <code>digits=0, * form=PLAIN, lostDigits=false, roundingMode=ROUND_HALF_UP</code>; * these settings perform fixed point arithmetic with unlimited * precision, as defined for the original BigDecimal class in Java 1.1 * and Java 1.2. * <p> * For monadic operators, only the optional <code>MathContext</code> * parameter is present; the operation acts upon the current object. * <p> * For dyadic operators, a <code>BigDecimal</code> parameter is always * present; it must not be <code>null</code>. * The operation acts with the current object being the left-hand operand * and the <code>BigDecimal</code> parameter being the right-hand operand. * <p> * For example, adding two <code>BigDecimal</code> objects referred to * by the names <code>award</code> and <code>extra</code> could be * written as any of: * <p><code> * award.add(extra) * <br>award.add(extra, MathContext.DEFAULT) * <br>award.add(extra, acontext) * </code> * <p> * (where <code>acontext</code> is a <code>MathContext</code> object), * which would return a <code>BigDecimal</code> object whose value is * the result of adding <code>award</code> and <code>extra</code> under * the appropriate context settings. * <p> * When a <code>BigDecimal</code> operator method is used, a set of * rules define what the result will be (and, by implication, how the * result would be represented as a character string). * These rules are defined in the BigDecimal arithmetic documentation * (see the URL above), but in summary: * <ul> * <li>Results are normally calculated with up to some maximum number of * significant digits. * For example, if the <code>MathContext</code> parameter for an operation * were <code>MathContext.DEFAULT</code> then the result would be * rounded to 9 digits; the division of 2 by 3 would then result in * 0.666666667. * <br> * You can change the default of 9 significant digits by providing the * method with a suitable <code>MathContext</code> object. This lets you * calculate using as many digits as you need -- thousands, if necessary. * Fixed point (scaled) arithmetic is indicated by using a * <code>digits</code> setting of 0 (or omitting the * <code>MathContext</code> parameter). * <br> * Similarly, you can change the algorithm used for rounding from the * default "classic" algorithm. * <li> * In standard arithmetic (that is, when the <code>form</code> setting * is not <code>PLAIN</code>), a zero result is always expressed as the * single digit <code>'0'</code> (that is, with no sign, decimal point, * or exponent part). * <li> * Except for the division and power operators in standard arithmetic, * trailing zeros are preserved (this is in contrast to binary floating * point operations and most electronic calculators, which lose the * information about trailing zeros in the fractional part of results). * <br> * So, for example: * <p><code> * new BigDecimal("2.40").add( new BigDecimal("2")) =&gt; "4.40" * <br>new BigDecimal("2.40").subtract(new BigDecimal("2")) =&gt; "0.40" * <br>new BigDecimal("2.40").multiply(new BigDecimal("2")) =&gt; "4.80" * <br>new BigDecimal("2.40").divide( new BigDecimal("2"), def) =&gt; "1.2" * </code> * <p>where the value on the right of the <code>=&gt;</code> would be the * result of the operation, expressed as a <code>String</code>, and * <code>def</code> (in this and following examples) refers to * <code>MathContext.DEFAULT</code>). * This preservation of trailing zeros is desirable for most * calculations (including financial calculations). * If necessary, trailing zeros may be easily removed using division by 1. * <li> * In standard arithmetic, exponential form is used for a result * depending on its value and the current setting of <code>digits</code> * (the default is 9 digits). * If the number of places needed before the decimal point exceeds the * <code>digits</code> setting, or the absolute value of the number is * less than <code>0.000001</code>, then the number will be expressed in * exponential notation; thus * <p><code> * new BigDecimal("1e+6").multiply(new BigDecimal("1e+6"), def) * </code> * <p>results in <code>1E+12</code> instead of * <code>1000000000000</code>, and * <p><code> * new BigDecimal("1").divide(new BigDecimal("3E+10"), def) * </code> * <p>results in <code>3.33333333E-11</code> instead of * <code>0.0000000000333333333</code>. * <p> * The form of the exponential notation (scientific or engineering) is * determined by the <code>form</code> setting. * <eul> * <p> * The names of methods in this class follow the conventions established * by <code>java.lang.Number</code>, <code>java.math.BigInteger</code>, * and <code>java.math.BigDecimal</code> in Java 1.1 and Java 1.2. * * @see MathContext * @author Mike Cowlishaw * @stable ICU 2.0 */ //--public class BigDecimal extends java.lang.Number implements java.io.Serializable,java.lang.Comparable{ //-- private static final java.lang.String $0="BigDecimal.nrx"; //-- methods BigDecimal.prototype.abs = abs; BigDecimal.prototype.add = add; BigDecimal.prototype.compareTo = compareTo; BigDecimal.prototype.divide = divide; BigDecimal.prototype.divideInteger = divideInteger; BigDecimal.prototype.max = max; BigDecimal.prototype.min = min; BigDecimal.prototype.multiply = multiply; BigDecimal.prototype.negate = negate; BigDecimal.prototype.plus = plus; BigDecimal.prototype.pow = pow; BigDecimal.prototype.remainder = remainder; BigDecimal.prototype.subtract = subtract; BigDecimal.prototype.equals = equals; BigDecimal.prototype.format = format; BigDecimal.prototype.intValueExact = intValueExact; BigDecimal.prototype.movePointLeft = movePointLeft; BigDecimal.prototype.movePointRight = movePointRight; BigDecimal.prototype.scale = scale; BigDecimal.prototype.setScale = setScale; BigDecimal.prototype.signum = signum; BigDecimal.prototype.toString = toString; BigDecimal.prototype.layout = layout; BigDecimal.prototype.intcheck = intcheck; BigDecimal.prototype.dodivide = dodivide; BigDecimal.prototype.bad = bad; BigDecimal.prototype.badarg = badarg; BigDecimal.prototype.extend = extend; BigDecimal.prototype.byteaddsub = byteaddsub; BigDecimal.prototype.diginit = diginit; BigDecimal.prototype.clone = clone; BigDecimal.prototype.checkdigits = checkdigits; BigDecimal.prototype.round = round; BigDecimal.prototype.allzero = allzero; BigDecimal.prototype.finish = finish; // Convenience methods BigDecimal.prototype.isGreaterThan = isGreaterThan; BigDecimal.prototype.isLessThan = isLessThan; BigDecimal.prototype.isGreaterThanOrEqualTo = isGreaterThanOrEqualTo; BigDecimal.prototype.isLessThanOrEqualTo = isLessThanOrEqualTo; BigDecimal.prototype.isPositive = isPositive; BigDecimal.prototype.isNegative = isNegative; BigDecimal.prototype.isZero = isZero; /* ----- Constants ----- */ /* properties constant public */ // useful to others // the rounding modes (copied here for upwards compatibility) /** * Rounding mode to round to a more positive number. * @see MathContext#ROUND_CEILING * @stable ICU 2.0 */ //--public static final int ROUND_CEILING=com.ibm.icu.math.MathContext.ROUND_CEILING; BigDecimal.ROUND_CEILING = BigDecimal.prototype.ROUND_CEILING = MathContext.prototype.ROUND_CEILING; /** * Rounding mode to round towards zero. * @see MathContext#ROUND_DOWN * @stable ICU 2.0 */ //--public static final int ROUND_DOWN=com.ibm.icu.math.MathContext.ROUND_DOWN; BigDecimal.ROUND_DOWN = BigDecimal.prototype.ROUND_DOWN = MathContext.prototype.ROUND_DOWN; /** * Rounding mode to round to a more negative number. * @see MathContext#ROUND_FLOOR * @stable ICU 2.0 */ //--public static final int ROUND_FLOOR=com.ibm.icu.math.MathContext.ROUND_FLOOR; BigDecimal.ROUND_FLOOR = BigDecimal.prototype.ROUND_FLOOR = MathContext.prototype.ROUND_FLOOR; /** * Rounding mode to round to nearest neighbor, where an equidistant * value is rounded down. * @see MathContext#ROUND_HALF_DOWN * @stable ICU 2.0 */ //--public static final int ROUND_HALF_DOWN=com.ibm.icu.math.MathContext.ROUND_HALF_DOWN; BigDecimal.ROUND_HALF_DOWN = BigDecimal.prototype.ROUND_HALF_DOWN = MathContext.prototype.ROUND_HALF_DOWN; /** * Rounding mode to round to nearest neighbor, where an equidistant * value is rounded to the nearest even neighbor. * @see MathContext#ROUND_HALF_EVEN * @stable ICU 2.0 */ //--public static final int ROUND_HALF_EVEN=com.ibm.icu.math.MathContext.ROUND_HALF_EVEN; BigDecimal.ROUND_HALF_EVEN = BigDecimal.prototype.ROUND_HALF_EVEN = MathContext.prototype.ROUND_HALF_EVEN; /** * Rounding mode to round to nearest neighbor, where an equidistant * value is rounded up. * @see MathContext#ROUND_HALF_UP * @stable ICU 2.0 */ //--public static final int ROUND_HALF_UP=com.ibm.icu.math.MathContext.ROUND_HALF_UP; BigDecimal.ROUND_HALF_UP = BigDecimal.prototype.ROUND_HALF_UP = MathContext.prototype.ROUND_HALF_UP; /** * Rounding mode to assert that no rounding is necessary. * @see MathContext#ROUND_UNNECESSARY * @stable ICU 2.0 */ //--public static final int ROUND_UNNECESSARY=com.ibm.icu.math.MathContext.ROUND_UNNECESSARY; BigDecimal.ROUND_UNNECESSARY = BigDecimal.prototype.ROUND_UNNECESSARY = MathContext.prototype.ROUND_UNNECESSARY; /** * Rounding mode to round away from zero. * @see MathContext#ROUND_UP * @stable ICU 2.0 */ //--public static final int ROUND_UP=com.ibm.icu.math.MathContext.ROUND_UP; BigDecimal.ROUND_UP = BigDecimal.prototype.ROUND_UP = MathContext.prototype.ROUND_UP; /* properties constant private */ // locals //--private static final byte ispos=1; // ind: indicates positive (must be 1) //--private static final byte iszero=0; // ind: indicates zero (must be 0) //--private static final byte isneg=-1; // ind: indicates negative (must be -1) BigDecimal.prototype.ispos = 1; BigDecimal.prototype.iszero = 0; BigDecimal.prototype.isneg = -1; // [later could add NaN, +/- infinity, here] //--private static final int MinExp=-999999999; // minimum exponent allowed //--private static final int MaxExp=999999999; // maximum exponent allowed //--private static final int MinArg=-999999999; // minimum argument integer //--private static final int MaxArg=999999999; // maximum argument integer BigDecimal.prototype.MinExp=-999999999; // minimum exponent allowed BigDecimal.prototype.MaxExp=999999999; // maximum exponent allowed BigDecimal.prototype.MinArg=-999999999; // minimum argument integer BigDecimal.prototype.MaxArg=999999999; // maximum argument integer //--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 BigDecimal.prototype.plainMC=new MathContext(0, MathContext.prototype.PLAIN); /* properties constant private unused */ // present but not referenced // Serialization version //--private static final long serialVersionUID=8245355804974198832L; //--private static final java.lang.String copyright=" Copyright (c) IBM Corporation 1996, 2000. All rights reserved. "; /* properties static private */ // Precalculated constant arrays (used by byteaddsub) //--private static byte bytecar[]=new byte[(90+99)+1]; // carry/borrow array //--private static byte bytedig[]=diginit(); // next digit array BigDecimal.prototype.bytecar = new Array((90+99)+1); BigDecimal.prototype.bytedig = diginit(); /** * The <code>BigDecimal</code> constant "0". * * @see #ONE * @see #TEN * @stable ICU 2.0 */ //--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 // .. to be able to use this, for speed BigDecimal.ZERO = BigDecimal.prototype.ZERO = new BigDecimal("0"); /** * The <code>BigDecimal</code> constant "1". * * @see #TEN * @see #ZERO * @stable ICU 2.0 */ //--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 // .. to be able to use this, for speed BigDecimal.ONE = BigDecimal.prototype.ONE = new BigDecimal("1"); /** * The <code>BigDecimal</code> constant "10". * * @see #ONE * @see #ZERO * @stable ICU 2.0 */ //--public static final com.ibm.icu.math.BigDecimal TEN=new com.ibm.icu.math.BigDecimal(10); BigDecimal.TEN = BigDecimal.prototype.TEN = new BigDecimal("10"); /* ----- Instance properties [all private and immutable] ----- */ /* properties private */ /** * The indicator. This may take the values: * <ul> * <li>ispos -- the number is positive * <li>iszero -- the number is zero * <li>isneg -- the number is negative * </ul> * * @serial */ //--private byte ind; // assumed undefined // Note: some code below assumes IND = Sign [-1, 0, 1], at present. // We only need two bits for this, but use a byte [also permits // smooth future extension]. /** * The formatting style. This may take the values: * <ul> * <li>MathContext.PLAIN -- no exponent needed * <li>MathContext.SCIENTIFIC -- scientific notation required * <li>MathContext.ENGINEERING -- engineering notation required * </ul> * <p> * This property is an optimization; it allows us to defer number * layout until it is actually needed as a string, hence avoiding * unnecessary formatting. * * @serial */ //--private byte form=(byte)com.ibm.icu.math.MathContext.PLAIN; // assumed PLAIN // We only need two bits for this, at present, but use a byte // [again, to allow for smooth future extension] /** * The value of the mantissa. * <p> * Once constructed, this may become shared between several BigDecimal * objects, so must not be altered. * <p> * For efficiency (speed), this is a byte array, with each byte * taking a value of 0 -> 9. * <p> * If the first byte is 0 then the value of the number is zero (and * mant.length=1, except when constructed from a plain number, for * example, 0.000). * * @serial */ //--private byte mant[]; // assumed null /** * The exponent. * <p> * For fixed point arithmetic, scale is <code>-exp</code>, and can * apply to zero. * * Note that this property can have a value less than MinExp when * the mantissa has more than one digit. * * @serial */ //--private int exp; // assumed 0 /* ---------------------------------------------------------------- */ /* Constructors */ /* ---------------------------------------------------------------- */ /** * Constructs a <code>BigDecimal</code> object from a * <code>java.math.BigDecimal</code>. * <p> * Constructs a <code>BigDecimal</code> as though the parameter had * been represented as a <code>String</code> (using its * <code>toString</code> method) and the * {@link #BigDecimal(java.lang.String)} constructor had then been * used. * The parameter must not be <code>null</code>. * <p> * <i>(Note: this constructor is provided only in the * <code>com.ibm.icu.math</code> version of the BigDecimal class. * It would not be present in a <code>java.math</code> version.)</i> * * @param bd The <code>BigDecimal</code> to be translated. * @stable ICU 2.0 */ //--public BigDecimal(java.math.BigDecimal bd){ //-- this(bd.toString()); //-- return;} /** * Constructs a <code>BigDecimal</code> object from a * <code>BigInteger</code>, with scale 0. * <p> * Constructs a <code>BigDecimal</code> which is the exact decimal * representation of the <code>BigInteger</code>, with a scale of * zero. * The value of the <code>BigDecimal</code> is identical to the value * of the <code>BigInteger</code>. * The parameter must not be <code>null</code>. * <p> * The <code>BigDecimal</code> will contain only decimal digits, * prefixed with a leading minus sign (hyphen) if the * <code>BigInteger</code> is negative. A leading zero will be * present only if the <code>BigInteger</code> is zero. * * @param bi The <code>BigInteger</code> to be converted. * @stable ICU 2.0 */ //--public BigDecimal(java.math.BigInteger bi){ //-- this(bi.toString(10)); //-- return;} // exp remains 0 /** * Constructs a <code>BigDecimal</code> object from a * <code>BigInteger</code> and a scale. * <p> * Constructs a <code>BigDecimal</code> which is the exact decimal * representation of the <code>BigInteger</code>, scaled by the * second parameter, which may not be negative. * The value of the <code>BigDecimal</code> is the * <code>BigInteger</code> divided by ten to the power of the scale. * The <code>BigInteger</code> parameter must not be * <code>null</code>. * <p> * The <code>BigDecimal</code> will contain only decimal digits, (with * an embedded decimal point followed by <code>scale</code> decimal * digits if the scale is positive), prefixed with a leading minus * sign (hyphen) if the <code>BigInteger</code> is negative. A * leading zero will be present only if the <code>BigInteger</code> is * zero. * * @param bi The <code>BigInteger</code> to be converted. * @param scale The <code>int</code> specifying the scale. * @throws NumberFormatException if the scale is negative. * @stable ICU 2.0 */ //--public BigDecimal(java.math.BigInteger bi,int scale){ //-- this(bi.toString(10)); //-- if (scale<0) //-- throw new java.lang.NumberFormatException("Negative scale:"+" "+scale); //-- exp=(int)-scale; // exponent is -scale //-- return;} /** * Constructs a <code>BigDecimal</code> object from an array of characters. * <p> * Constructs a <code>BigDecimal</code> as though a * <code>String</code> had been constructed from the character array * and the {@link #BigDecimal(java.lang.String)} constructor had then * been used. The parameter must not be <code>null</code>. * <p> * Using this constructor is faster than using the * <code>BigDecimal(String)</code> constructor if the string is * already available in character array form. * * @param inchars The <code>char[]</code> array containing the number * to be converted. * @throws NumberFormatException if the parameter is not a valid * number. * @stable ICU 2.0 */ //--public BigDecimal(char inchars[]){ //-- this(inchars,0,inchars.length); //-- return;} /** * Constructs a <code>BigDecimal</code> object from an array of characters. * <p> * Constructs a <code>BigDecimal</code> as though a * <code>String</code> had been constructed from the character array * (or a subarray of that array) and the * {@link #BigDecimal(java.lang.String)} constructor had then been * used. The first parameter must not be <code>null</code>, and the * subarray must be wholly contained within it. * <p> * Using this constructor is faster than using the * <code>BigDecimal(String)</code> constructor if the string is * already available within a character array. * * @param inchars The <code>char[]</code> array containing the number * to be converted. * @param offset The <code>int</code> offset into the array of the * start of the number to be converted. * @param length The <code>int</code> length of the number. * @throws NumberFormatException if the parameter is not a valid * number for any reason. * @stable ICU 2.0 */ //--public BigDecimal(char inchars[],int offset,int length){super(); function BigDecimal() { //-- members this.ind = 0; this.form = MathContext.prototype.PLAIN; this.mant = null; this.exp = 0; //-- overloaded ctor if (BigDecimal.arguments.length == 0) return; var inchars; var offset; var length; if (BigDecimal.arguments.length == 1) { inchars = BigDecimal.arguments[0]; offset = 0; length = inchars.length; } else { inchars = BigDecimal.arguments[0]; offset = BigDecimal.arguments[1]; length = BigDecimal.arguments[2]; } if (typeof inchars == "string") { inchars = inchars.split(""); } //--boolean exotic; var exotic; //--boolean hadexp; var hadexp; //--int d; var d; //--int dotoff; var dotoff; //--int last; var last; //--int i=0; var i=0; //--char si=0; var si=0; //--boolean eneg=false; var eneg=false; //--int k=0; var k=0; //--int elen=0; var elen=0; //--int j=0; var j=0; //--char sj=0; var sj=0; //--int dvalue=0; var dvalue=0; //--int mag=0; var mag=0; // This is the primary constructor; all incoming strings end up // here; it uses explicit (inline) parsing for speed and to avoid // generating intermediate (temporary) objects of any kind. // 1998.06.25: exponent form built only if E/e in string // 1998.06.25: trailing zeros not removed for zero // 1999.03.06: no embedded blanks; allow offset and length if (length<=0) this.bad("BigDecimal(): ", inchars); // bad conversion (empty string) // [bad offset will raise array bounds exception] /* Handle and step past sign */ this.ind=this.ispos; // assume positive if (inchars[0]==('-')) { length--; if (length==0) this.bad("BigDecimal(): ", inchars); // nothing after sign this.ind=this.isneg; offset++; } else if (inchars[0]==('+')) { length--; if (length==0) this.bad("BigDecimal(): ", inchars); // nothing after sign offset++; } /* We're at the start of the number */ exotic=false; // have extra digits hadexp=false; // had explicit exponent d=0; // count of digits found dotoff=-1; // offset where dot was found last=-1; // last character of mantissa {var $1=length;i=offset;i:for(;$1>0;$1--,i++){ si=inchars[i]; if (si>='0') // test for Arabic digit if (si<='9') { last=i; d++; // still in mantissa continue i; } if (si=='.') { // record and ignore if (dotoff>=0) this.bad("BigDecimal(): ", inchars); // two dots dotoff=i-offset; // offset into mantissa continue i; } if (si!='e') if (si!='E') { // expect an extra digit if (si<'0' || si>'9') this.bad("BigDecimal(): ", inchars); // not a number // defer the base 10 check until later to avoid extra method call exotic=true; // will need conversion later last=i; d++; // still in mantissa continue i; } /* Found 'e' or 'E' -- now process explicit exponent */ // 1998.07.11: sign no longer required if ((i-offset)>(length-2)) this.bad("BigDecimal(): ", inchars); // no room for even one digit eneg=false; if ((inchars[i+1])==('-')) { eneg=true; k=i+2; } else if ((inchars[i+1])==('+')) k=i+2; else k=i+1; // k is offset of first expected digit elen=length-((k-offset)); // possible number of digits if ((elen==0)||(elen>9)) this.bad("BigDecimal(): ", inchars); // 0 or more than 9 digits {var $2=elen;j=k;j:for(;$2>0;$2--,j++){ sj=inchars[j]; if (sj<'0') this.bad("BigDecimal(): ", inchars); // always bad if (sj>'9') { // maybe an exotic digit /*if (si<'0' || si>'9') this.bad(inchars); // not a number dvalue=java.lang.Character.digit(sj,10); // check base if (dvalue<0) bad(inchars); // not base 10*/ this.bad("BigDecimal(): ", inchars); } else dvalue=sj-'0'; this.exp=(this.exp*10)+dvalue; } }/*j*/ if (eneg) this.exp=-this.exp; // was negative hadexp=true; // remember we had one break i; // we are done } }/*i*/ /* Here when all inspected */ if (d==0) this.bad("BigDecimal(): ", inchars); // no mantissa digits if (dotoff>=0) this.exp=(this.exp+dotoff)-d; // adjust exponent if had dot /* strip leading zeros/dot (leave final if all 0's) */ {var $3=last-1;i=offset;i:for(;i<=$3;i++){ si=inchars[i]; if (si=='0') { offset++; dotoff--; d--; } else if (si=='.') { offset++; // step past dot dotoff--; } else if (si<='9') break i;/* non-0 */ else {/* exotic */ //if ((java.lang.Character.digit(si,10))!=0) break i; // non-0 or bad // is 0 .. strip like '0' //offset++; //dotoff--; //d--; } } }/*i*/ /* Create the mantissa array */ this.mant=new Array(d); // we know the length j=offset; // input offset if (exotic) {exotica:do{ // slow: check for exotica {var $4=d;i=0;i:for(;$4>0;$4--,i++){ if (i==dotoff) j++; // at dot sj=inchars[j]; if (sj<='9') this.mant[i]=sj-'0';/* easy */ else { //dvalue=java.lang.Character.digit(sj,10); //if (dvalue<0) this.bad("BigDecimal(): ", inchars); // not a number after all //mant[i]=(byte)dvalue; } j++; } }/*i*/ }while(false);}/*exotica*/ else {simple:do{ {var $5=d;i=0;i:for(;$5>0;$5--,i++){ if (i==dotoff) j++; this.mant[i]=inchars[j]-'0'; j++; } }/*i*/ }while(false);}/*simple*/ /* Looks good. Set the sign indicator and form, as needed. */ // Trailing zeros are preserved // The rule here for form is: // If no E-notation, then request plain notation // Otherwise act as though add(0,DEFAULT) and request scientific notation // [form is already PLAIN] if (this.mant[0]==0) { this.ind=this.iszero; // force to show zero // negative exponent is significant (e.g., -3 for 0.000) if plain if (this.exp>0) this.exp=0; // positive exponent can be ignored if (hadexp) { // zero becomes single digit from add this.mant=this.ZERO.mant; this.exp=0; } } else { // non-zero // [ind was set earlier] // now determine form if (hadexp) { this.form=MathContext.prototype.SCIENTIFIC; // 1999.06.29 check for overflow mag=(this.exp+this.mant.length)-1; // true exponent in scientific notation if ((mag<this.MinExp)||(mag>this.MaxExp)) this.bad("BigDecimal(): ", inchars); } } // say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] mant.length exp ind form return; } /** * Constructs a <code>BigDecimal</code> object directly from a * <code>double</code>. * <p> * Constructs a <code>BigDecimal</code> which is the exact decimal * representation of the 64-bit signed binary floating point * parameter. * <p> * Note that this constructor it an exact conversion; it does not give * the same result as converting <code>num</code> to a * <code>String</code> using the <code>Double.toString()</code> method * and then using the {@link #BigDecimal(java.lang.String)} * constructor. * To get that result, use the static {@link #valueOf(double)} * method to construct a <code>BigDecimal</code> from a * <code>double</code>. * * @param num The <code>double</code> to be converted. * @throws NumberFormatException if the parameter is infinite or * not a number. * @stable ICU 2.0 */ //--public BigDecimal(double num){ //-- // 1999.03.06: use exactly the old algorithm //-- // 2000.01.01: note that this constructor does give an exact result, //-- // so perhaps it should not be deprecated //-- // 2000.06.18: no longer deprecated //-- this((new java.math.BigDecimal(num)).toString()); //-- return;} /** * Constructs a <code>BigDecimal</code> object directly from a * <code>int</code>. * <p> * Constructs a <code>BigDecimal</code> which is the exact decimal * representation of the 32-bit signed binary integer parameter. * The <code>BigDecimal</code> will contain only decimal digits, * prefixed with a leading minus sign (hyphen) if the parameter is * negative. * A leading zero will be present only if the parameter is zero. * * @param num The <code>int</code> to be converted. * @stable ICU 2.0 */ //--public BigDecimal(int num){super(); //-- int mun; //-- int i=0; //-- // We fastpath commoners //-- if (num<=9) //-- if (num>=(-9)) //-- {singledigit:do{ //-- // very common single digit case //-- {/*select*/ //-- if (num==0) //-- { //-- mant=ZERO.mant; //-- ind=iszero; //-- } //-- else if (num==1) //-- { //-- mant=ONE.mant; //-- ind=ispos; //-- } //-- else if (num==(-1)) //-- { //-- mant=ONE.mant; //-- ind=isneg; //-- } //-- else{ //-- { //-- mant=new byte[1]; //-- if (num>0) //-- { //-- mant[0]=(byte)num; //-- ind=ispos; //-- } //-- else //-- { // num<-1 //-- mant[0]=(byte)((int)-num); //-- ind=isneg; //-- } //-- } //-- } //-- } //-- return; //-- }while(false);}/*singledigit*/ //-- //-- /* We work on negative numbers so we handle the most negative number */ //-- if (num>0) //-- { //-- ind=ispos; //-- num=(int)-num; //-- } //-- else //-- ind=isneg;/* negative */ // [0 case already handled] //-- // [it is quicker, here, to pre-calculate the length with //-- // one loop, then allocate exactly the right length of byte array, //-- // then re-fill it with another loop] //-- mun=num; // working copy //-- {i=9;i:for(;;i--){ //-- mun=mun/10; //-- if (mun==0) //-- break i; //-- } //-- }/*i*/ //-- // i is the position of the leftmost digit placed //-- mant=new byte[10-i]; //-- {i=(10-i)-1;i:for(;;i--){ //-- mant[i]=(byte)-(((byte)(num%10))); //-- num=num/10; //-- if (num==0) //-- break i; //-- } //-- }/*i*/ //-- return; //-- } /** * Constructs a <code>BigDecimal</code> object directly from a * <code>long</code>. * <p> * Constructs a <code>BigDecimal</code> which is the exact decimal * representation of the 64-bit signed binary integer parameter. * The <code>BigDecimal</code> will contain only decimal digits, * prefixed with a leading minus sign (hyphen) if the parameter is * negative. * A leading zero will be present only if the parameter is zero. * * @param num The <code>long</code> to be converted. * @stable ICU 2.0 */ //--public BigDecimal(long num){super(); //-- long mun; //-- int i=0; //-- // Not really worth fastpathing commoners in this constructor [also, //-- // we use this to construct the static constants]. //-- // This is much faster than: this(String.valueOf(num).toCharArray()) //-- /* We work on negative num so we handle the most negative number */ //-- if (num>0) //-- { //-- ind=ispos; //-- num=(long)-num; //-- } //-- else //-- if (num==0) //-- ind=iszero; //-- else //-- ind=isneg;/* negative */ //-- mun=num; //-- {i=18;i:for(;;i--){ //-- mun=mun/10; //-- if (mun==0) //-- break i; //-- } //-- }/*i*/ //-- // i is the position of the leftmost digit placed //-- mant=new byte[19-i]; //-- {i=(19-i)-1;i:for(;;i--){ //-- mant[i]=(byte)-(((byte)(num%10))); //-- num=num/10; //-- if (num==0) //-- break i; //-- } //-- }/*i*/ //-- return; //-- } /** * Constructs a <code>BigDecimal</code> object from a <code>String</code>. * <p> * Constructs a <code>BigDecimal</code> from the parameter, which must * not be <code>null</code> and must represent a valid <i>number</i>, * as described formally in the documentation referred to * {@link BigDecimal above}. * <p> * In summary, numbers in <code>String</code> form must have at least * one digit, may have a leading sign, may have a decimal point, and * exponential notation may be used. They follow conventional syntax, * and may not contain blanks. * <p> * Some valid strings from which a <code>BigDecimal</code> might * be constructed are: * <pre> * "0" -- Zero * "12" -- A whole number * "-76" -- A signed whole number * "12.70" -- Some decimal places * "+0.003" -- Plus sign is allowed * "17." -- The same as 17 * ".5" -- The same as 0.5 * "4E+9" -- Exponential notation * "0.73e-7" -- Exponential notation * </pre> * <p> * (Exponential notation means that the number includes an optional * sign and a power of ten following an '</code>E</code>' that * indicates how the decimal point will be shifted. Thus the * <code>"4E+9"</code> above is just a short way of writing * <code>4000000000</code>, and the <code>"0.73e-7"</code> is short * for <code>0.000000073</code>.) * <p> * The <code>BigDecimal</code> constructed from the String is in a * standard form, with no blanks, as though the * {@link #add(BigDecimal)} method had been used to add zero to the * number with unlimited precision. * If the string uses exponential notation (that is, includes an * <code>e</code> or an <code>E</code>), then the * <code>BigDecimal</code> number will be expressed in scientific * notation (where the power of ten is adjusted so there is a single * non-zero digit to the left of the decimal point); in this case if * the number is zero then it will be expressed as the single digit 0, * and if non-zero it will have an exponent unless that exponent would * be 0. The exponent must fit in nine digits both before and after it * is expressed in scientific notation. * <p> * Any digits in the parameter must be decimal; that is, * <code>Character.digit(c, 10)</code> (where </code>c</code> is the * character in question) would not return -1. * * @param string The <code>String</code> to be converted. * @throws NumberFormatException if the parameter is not a valid * number. * @stable ICU 2.0 */ //--public BigDecimal(java.lang.String string){ //-- this(string.toCharArray(),0,string.length()); //-- return;} /* <sgml> Make a default BigDecimal object for local use. </sgml> */ //--private BigDecimal(){super(); //-- return; //-- } /* ---------------------------------------------------------------- */ /* Operator methods [methods which take a context parameter] */ /* ---------------------------------------------------------------- */ /** * Returns a plain <code>BigDecimal</code> whose value is the absolute * value of this <code>BigDecimal</code>. * <p> * The same as {@link #abs(MathContext)}, where the context is * <code>new MathContext(0, MathContext.PLAIN)</code>. * <p> * The length of the decimal part (the scale) of the result will * be <code>this.scale()</code> * * @return A <code>BigDecimal</code> whose value is the absolute * value of this <code>BigDecimal</code>. * @stable ICU 2.0 */ //--public com.ibm.icu.math.BigDecimal abs(){ //- return this.abs(plainMC); //- } /** * Returns a <code>BigDecimal</code> whose value is the absolute value * of this <code>BigDecimal</code>. * <p> * If the current object is zero or positive, then the same result as * invoking the {@link #plus(MathContext)} method with the same * parameter is returned. * Otherwise, the same result as invoking the * {@link #negate(MathContext)} method with the same parameter is * returned. * * @param set The <code>MathContext</code> arithmetic settings. * @return A <code>BigDecimal</code> whose value is the absolute * value of this <code>BigDecimal</code>. * @stable ICU 2.0 */ //--public com.ibm.icu.math.BigDecimal abs(com.ibm.icu.math.MathContext set){ function abs() { var set; if (abs.arguments.length == 1) { set = abs.arguments[0]; } else if (abs.arguments.length == 0) { set = this.plainMC; } else { throw "abs(): " + abs.arguments.length + " arguments given; expected 0 or 1"; } if (this.ind==this.isneg) return this.negate(set); return this.plus(set); } /** * Returns a plain <code>BigDecimal</code> whose value is * <code>this+rhs</code>, using fixed point arithmetic. * <p> * The same as {@link #add(BigDecimal, MathContext)}, * where the <code>BigDecimal</code> is <code>rhs</code>, * and the context is <code>new MathContext(0, MathContext.PLAIN)</code>. * <p> * The length of the decimal part (the scale) of the result will be * the maximum of the scales of the two operands. * * @param rhs The <code>BigDecimal</code> for the right hand side of * the addition. * @return A <code>BigDecimal</code> whose value is * <code>this+rhs</code>, using fixed point arithmetic. * @stable ICU 2.0 */ //--public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs){ //-- return this.add(rhs,plainMC); //-- } /** * Returns a <code>BigDecimal</code> whose value is <code>this+rhs</code>. * <p> * Implements the addition (<b><code>+</code></b>) operator * (as defined in the decimal documentation, see {@link BigDecimal * class header}), * and returns the result as a <code>BigDecimal</code> object. * * @param rhs The <code>BigDecimal</code> for the right hand side of * the addition. * @param set The <code>MathContext</code> arithmetic settings. * @return A <code>BigDecimal</code> whose value is * <code>this+rhs</code>. * @stable ICU 2.0 */ //--public com.ibm.icu.math.BigDecimal add(com.ibm.icu.math.BigDecimal rhs,com.ibm.icu.math.MathContext set){ function add() { var set; if (add.arguments.length == 2) { set = add.arguments[1]; } else if (add.arguments.length == 1) { set = this.plainMC; } else { throw "add(): " + add.arguments.length + " arguments given; expected 1 or 2"; } var rhs = add.arguments[0]; //--com.ibm.icu.math.BigDecimal lhs; var lhs; //--int reqdig; var reqdig; //--com.ibm.icu.math.BigDecimal res; var res; //--byte usel[]; var usel; //--int usellen; var usellen; //--byte user[]; var user; //--int userlen; var userlen; //--int newlen=0; var newlen=0; //--int tlen=0; var tlen=0; //--int mult=0; var mult=0; //--byte t[]=null; var t=null; //--int ia=0; var ia=0; //--int ib=0; var ib=0; //--int ea=0; var ea=0; //int eb=0; var eb=0; //byte ca=0; var ca=0; //--byte cb=0; var cb=0; /* determine requested digits and form */ if (set.lostDigits) this.checkdigits(rhs,set.digits); lhs=this; // name for clarity and proxy /* Quick exit for add floating 0 */ // plus() will optimize to return same object if possible if (lhs.ind==0) if (set.form!=MathContext.prototype.PLAIN) return rhs.plus(set); if (rhs.ind==0) if (set.form!=MathContext.prototype.PLAIN) return lhs.plus(set); /* Prepare numbers (round, unless unlimited precision) */ reqdig=set.digits; // local copy (heavily used) if (reqdig>0) { if (lhs.mant.length>reqdig) lhs=this.clone(lhs).round(set); if (rhs.mant.length>reqdig) rhs=this.clone(rhs).round(set); // [we could reuse the new LHS for result in this case] } res=new BigDecimal(); // build result here /* Now see how much we have to pad or truncate lhs or rhs in order to align the numbers. If one number is much larger than the other, then the smaller cannot affect the answer [but we may still need to pad with up to DIGITS trailing zeros]. */ // Note sign may be 0 if digits (reqdig) is 0 // usel and user will be the byte arrays passed to the adder; we'll //