学过java的同学应该都知道,java中有一个BigDecimal 是专门用来算金额的,今天这里的BigDecimal是从java翻译成js的。
先看用法:
加法(四舍五入保留两位小数):
var a = new BigDecimal("2.555555").add(new BigDecimal("5.222222")).setScale(2, MathContext.ROUND_HALF_UP).toString();
(a);
减法:
new BigDecimal("2.40").subtract(new BigDecimal("2"))
乘法:
new BigDecimal("2.40").multiply(new BigDecimal("2"))
除法:
new BigDecimal("2.40").divide(new BigDecimal("2"), def)
下面来看看源代码:
/** @license Copyright (c) 2012 Daniel Trebbien and other contributors
Portions Copyright (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany
Portions Copyright (c) 1995-2001 International Business Machines Corporation and others
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
*/
(function () {
var MathContext = (function () {
/* Generated from '' 8 Sep 2000 11:07:48 [v2.00] */
/* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
//--package ;
/* ------------------------------------------------------------------ */
/* MathContext -- Math context settings */
/* ------------------------------------------------------------------ */
/* Copyright IBM Corporation, 1997, 2000. All Rights Reserved. */
/* */
/* The MathContext object encapsulates the settings used by the */
/* BigDecimal class; it could also be used by other arithmetics. */
/* ------------------------------------------------------------------ */
/* Notes: */
/* */
/* 1. The properties are checked for validity on construction, so */
/* the BigDecimal class may assume that they are correct. */
/* ------------------------------------------------------------------ */
/* Author: Mike Cowlishaw */
/* 1997.09.03 Initial version (edited from ) */
/* 1997.09.12 Add lostDigits property */
/* 1998.05.02 Make the class immutable and final; drop set methods */
/* 1998.06.05 Add Round (rounding modes) property */
/* 1998.06.25 Rename from DecimalContext; allow digits=0 */
/* 1998.10.12 change to package */
/* 1999.02.06 add javadoc comments */
/* 1999.03.05 simplify; changes from discussion with J. Bloch */
/* 1999.03.13 1.00 release to IBM Centre for Java Technology */
/* 1999.07.10 1.04 flag serialization unused */
/* 2000.01.01 1.06 copyright update */
/* ------------------------------------------------------------------ */
/* JavaScript conversion (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany */
/**
* The <code>MathContext</code> immutable class encapsulates the
* settings understood by the operator methods of the {@link BigDecimal}
* class (and potentially other classes). Operator methods are those
* that effect an operation on a number or a pair of numbers.
* <p>
* The settings, which are not base-dependent, comprise:
* <ol>
* <li><code>digits</code>:
* the number of digits (precision) to be used for an operation
* <li><code>form</code>:
* the form of any exponent that results from the operation
* <li><code>lostDigits</code>:
* whether checking for lost digits is enabled
* <li><code>roundingMode</code>:
* the algorithm to be used for rounding.
* </ol>
* <p>
* When provided, a <code>MathContext</code> object supplies the
* settings for an operation directly.
* <p>
* When <code></code> is provided for a
* <code>MathContext</code> parameter then the default settings are used
* (<code>9, SCIENTIFIC, false, ROUND_HALF_UP</code>).
* <p>
* In the <code>BigDecimal</code> class, all methods which accept a
* <code>MathContext</code> object defaults) also have a version of the
* method which does not accept a MathContext parameter. These versions
* carry out unlimited precision fixed point arithmetic (as though the
* settings were (<code>0, PLAIN, false, ROUND_HALF_UP</code>).
* <p>
* The instance variables are shared with default access (so they are
* directly accessible to the <code>BigDecimal</code> class), but must
* never be changed.
* <p>
* The rounding mode constants have the same names and values as the
* constants of the same name in <code></code>, to
* maintain compatibility with earlier versions of
* <code>BigDecimal</code>.
*
* @see BigDecimal
* @author Mike Cowlishaw
* @stable ICU 2.0
*/
//--public final class MathContext implements {
//--private static final $0="";
//-- methods
= getDigits;
= getForm;
= getLostDigits;
= getRoundingMode;
= toString;
= isValidRound;
/* ----- Properties ----- */
/* properties public constant */
/**
* Plain (fixed point) notation, without any exponent.
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #ENGINEERING
* @see #SCIENTIFIC
* @stable ICU 2.0
*/
//--public static final int PLAIN=0; // [no exponent]
= = 0; // [no exponent]
/**
* Standard floating point notation (with scientific exponential
* format, where there is one digit before any decimal point).
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #ENGINEERING
* @see #PLAIN
* @stable ICU 2.0
*/
//--public static final int SCIENTIFIC=1; // 1 digit before .
= = 1; // 1 digit before .
/**
* Standard floating point notation (with engineering exponential
* format, where the power of ten is a multiple of 3).
* Used as a setting to control the form of the result of a
* <code>BigDecimal</code> operation.
* A zero result in plain form may have a decimal part of one or
* more zeros.
*
* @see #PLAIN
* @see #SCIENTIFIC
* @stable ICU 2.0
*/
//--public static final int ENGINEERING=2; // 1-3 digits before .
= = 2; // 1-3 digits before .
// The rounding modes match the original BigDecimal class values
/**
* Rounding mode to round to a more positive number.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result
* should be rounded towards the next more positive digit.
* @stable ICU 2.0
*/
//--public static final int ROUND_CEILING=2;
MathContext.ROUND_CEILING = .ROUND_CEILING = 2;
/**
* Rounding mode to round towards zero.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* All discarded digits are ignored (truncated). The result is
* neither incremented nor decremented.
* @stable ICU 2.0
*/
//--public static final int ROUND_DOWN=1;
MathContext.ROUND_DOWN = .ROUND_DOWN = 1;
/**
* Rounding mode to round to a more negative number.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result
* should be rounded towards the next more negative digit.
* @stable ICU 2.0
*/
//--public static final int ROUND_FLOOR=3;
MathContext.ROUND_FLOOR = .ROUND_FLOOR = 3;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded down.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than half (0.5 times)
* the value of a one in the next position then the result should be
* rounded up (away from zero). Otherwise the discarded digits are
* ignored.
* @stable ICU 2.0
*/
//--public static final int ROUND_HALF_DOWN=5;
MathContext.ROUND_HALF_DOWN = .ROUND_HALF_DOWN = 5;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded to the nearest even neighbor.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than half (0.5 times)
* the value of a one in the next position then the result should be
* rounded up (away from zero). If they represent less than half,
* then the result should be rounded down.
* <p>
* Otherwise (they represent exactly half) the result is rounded
* down if its rightmost digit is even, or rounded up if its
* rightmost digit is odd (to make an even digit).
* @stable ICU 2.0
*/
//--public static final int ROUND_HALF_EVEN=6;
MathContext.ROUND_HALF_EVEN = .ROUND_HALF_EVEN = 6;
/**
* Rounding mode to round to nearest neighbor, where an equidistant
* value is rounded up.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If the discarded digits represent greater than or equal to half
* (0.5 times) the value of a one in the next position then the result
* should be rounded up (away from zero). Otherwise the discarded
* digits are ignored.
* @stable ICU 2.0
*/
//--public static final int ROUND_HALF_UP=4;
MathContext.ROUND_HALF_UP = .ROUND_HALF_UP = 4;
/**
* Rounding mode to assert that no rounding is necessary.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* Rounding (potential loss of information) is not permitted.
* If any of the discarded digits are non-zero then an
* <code>ArithmeticException</code> should be thrown.
* @stable ICU 2.0
*/
//--public static final int ROUND_UNNECESSARY=7;
MathContext.ROUND_UNNECESSARY = .ROUND_UNNECESSARY = 7;
/**
* Rounding mode to round away from zero.
* Used as a setting to control the rounding mode used during a
* <code>BigDecimal</code> operation.
* <p>
* If any of the discarded digits are non-zero then the result will
* be rounded up (away from zero).
* @stable ICU 2.0
*/
//--public static final int ROUND_UP=0;
MathContext.ROUND_UP = .ROUND_UP = 0;
/* properties shared */
/**
* The number of digits (precision) to be used for an operation.
* A value of 0 indicates that unlimited precision (as many digits
* as are required) will be used.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the precision of results.
* Note that leading zeros (in the integer part of a number) are
* never significant.
* <p>
* <code>digits</code> will always be non-negative.
*
* @serial
*/
//--int digits;
/**
* The form of results from an operation.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the form of results, in particular whether and how
* exponential notation should be used.
*
* @see #ENGINEERING
* @see #PLAIN
* @see #SCIENTIFIC
* @serial
*/
//--int form; // values for this must fit in a byte
/**
* Controls whether lost digits checking is enabled for an
* operation.
* Set to <code>true</code> to enable checking, or
* to <code>false</code> to disable checking.
* <p>
* When enabled, the {@link BigDecimal} operator methods check
* the precision of their operand or operands, and throw an
* <code>ArithmeticException</code> if an operand is more precise
* than the digits setting (that is, digits would be lost).
* When disabled, operands are rounded to the specified digits.
*
* @serial
*/
//--boolean lostDigits;
/**
* The rounding algorithm to be used for an operation.
* <p>
* The {@link BigDecimal} operator methods use this value to
* determine the algorithm to be used when non-zero digits have to
* be discarded in order to reduce the precision of a result.
* The value must be one of the public constants whose name starts
* with <code>ROUND_</code>.
*
* @see #ROUND_CEILING
* @see #ROUND_DOWN
* @see #ROUND_FLOOR
* @see #ROUND_HALF_DOWN
* @see #ROUND_HALF_EVEN
* @see #ROUND_HALF_UP
* @see #ROUND_UNNECESSARY
* @see #ROUND_UP
* @serial
*/
//--int roundingMode;
/* properties private constant */
// default settings
//--private static final int DEFAULT_FORM=SCIENTIFIC;
//--private static final int DEFAULT_DIGITS=9;
//--private static final boolean DEFAULT_LOSTDIGITS=false;
//--private static final int DEFAULT_ROUNDINGMODE=ROUND_HALF_UP;
.DEFAULT_FORM=;
.DEFAULT_DIGITS=9;
.DEFAULT_LOSTDIGITS=false;
.DEFAULT_ROUNDINGMODE=.ROUND_HALF_UP;
/* properties private constant */
//--private static final int MIN_DIGITS=0; // smallest value for DIGITS.
//--private static final int MAX_DIGITS=999999999; // largest value for DIGITS. If increased,
.MIN_DIGITS=0; // smallest value for DIGITS.
.MAX_DIGITS=999999999; // largest value for DIGITS. If increased,
// the BigDecimal class may need update.
// list of valid rounding mode values, most common two first
//--private static final int ROUNDS[]=new int[]{ROUND_HALF_UP,ROUND_UNNECESSARY,ROUND_CEILING,ROUND_DOWN,ROUND_FLOOR,ROUND_HALF_DOWN,ROUND_HALF_EVEN,ROUND_UP};
=new Array(.ROUND_HALF_UP,.ROUND_UNNECESSARY,.ROUND_CEILING,.ROUND_DOWN,.ROUND_FLOOR,.ROUND_HALF_DOWN,.ROUND_HALF_EVEN,.ROUND_UP);
//--private static final ROUNDWORDS[]=new []{"ROUND_HALF_UP","ROUND_UNNECESSARY","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_UP"}; // matching names of the ROUNDS values
=new Array("ROUND_HALF_UP","ROUND_UNNECESSARY","ROUND_CEILING","ROUND_DOWN","ROUND_FLOOR","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_UP"); // matching names of the ROUNDS values
/* properties private constant unused */
// Serialization version
//--private static final long serialVersionUID=7163376998892515376L;
/* properties public constant */
/**
* A <code>MathContext</code> object initialized to the default
* settings for general-purpose arithmetic. That is,
* <code>digits=9 form=SCIENTIFIC lostDigits=false
* roundingMode=ROUND_HALF_UP</code>.
*
* @see #SCIENTIFIC
* @see #ROUND_HALF_UP
* @stable ICU 2.0
*/
//--public static final DEFAULT=new (DEFAULT_DIGITS,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
=new MathContext(.DEFAULT_DIGITS,.DEFAULT_FORM,.DEFAULT_LOSTDIGITS,.DEFAULT_ROUNDINGMODE);
/* ----- Constructors ----- */
/**
* Constructs a new <code>MathContext</code> with a specified
* precision.
* The other settings are set to the default values
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (<0 or >999999999).
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
* @stable ICU 2.0
*/
//--public MathContext(int setdigits){
//-- this(setdigits,DEFAULT_FORM,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
//-- return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision and form.
* The other settings are set to the default values
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (<0 or >999999999), or if the value given for the
* <code>setform</code> parameter is not one of the appropriate
* constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
* @stable ICU 2.0
*/
//--public MathContext(int setdigits,int setform){
//-- this(setdigits,setform,DEFAULT_LOSTDIGITS,DEFAULT_ROUNDINGMODE);
//-- return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision, form, and lostDigits setting.
* The roundingMode setting is set to its default value
* (see {@link #DEFAULT}).
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (<0 or >999999999), or if the value given for the
* <code>setform</code> parameter is not one of the appropriate
* constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @param setlostdigits The <code>boolean</code> lostDigits
* setting for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
* @stable ICU 2.0
*/
//--public MathContext(int setdigits,int setform,boolean setlostdigits){
//-- this(setdigits,setform,setlostdigits,DEFAULT_ROUNDINGMODE);
//-- return;}
/**
* Constructs a new <code>MathContext</code> with a specified
* precision, form, lostDigits, and roundingMode setting.
*
* An <code>IllegalArgumentException</code> is thrown if the
* <code>setdigits</code> parameter is out of range
* (<0 or >999999999), or if the value given for the
* <code>setform</code> or <code>setroundingmode</code> parameters is
* not one of the appropriate constants.
*
* @param setdigits The <code>int</code> digits setting
* for this <code>MathContext</code>.
* @param setform The <code>int</code> form setting
* for this <code>MathContext</code>.
* @param setlostdigits The <code>boolean</code> lostDigits
* setting for this <code>MathContext</code>.
* @param setroundingmode The <code>int</code> roundingMode setting
* for this <code>MathContext</code>.
* @throws IllegalArgumentException parameter out of range.
* @stable ICU 2.0
*/
//--public MathContext(int setdigits,int setform,boolean setlostdigits,int setroundingmode){super();
function MathContext() {
//-- members
= 0;
= 0; // values for this must fit in a byte
= false;
= 0;
//-- overloaded ctor
var setform = this.DEFAULT_FORM;
var setlostdigits = this.DEFAULT_LOSTDIGITS;
var setroundingmode = this.DEFAULT_ROUNDINGMODE;
if ( == 4)
{
setform = [1];
setlostdigits = [2];
setroundingmode = [3];
}
else if ( == 3)
{
setform = [1];
setlostdigits = [2];
}
else if ( == 2)
{
setform = [1];
}
else if ( != 1)
{
throw "MathContext(): " + + " arguments given; expected 1 to 4";
}
var setdigits = [0];
// set values, after checking
if (setdigits!=this.DEFAULT_DIGITS)
{
if (setdigits<this.MIN_DIGITS)
throw "MathContext(): Digits too small: "+setdigits;
if (setdigits>this.MAX_DIGITS)
throw "MathContext(): Digits too large: "+setdigits;
}
{/*select*/
if (setform==)
{} // [most common]
else if (setform==)
{}
else if (setform==)
{}
else{
throw "MathContext() Bad form value: "+setform;
}
}
if ((!((setroundingmode))))
throw "MathContext(): Bad roundingMode value: "+setroundingmode;
=setdigits;
=setform;
=setlostdigits; // [no bad value possible]
=setroundingmode;
return;}
/**
* Returns the digits setting.
* This value is always non-negative.
*
* @return an <code>int</code> which is the value of the digits
* setting
* @stable ICU 2.0
*/
//--public int getDigits(){
function getDigits() {
return ;
}
/**
* Returns the form setting.
* This will be one of
* {@link #ENGINEERING},
* {@link #PLAIN}, or
* {@link #SCIENTIFIC}.
*
* @return an <code>int</code> which is the value of the form setting
* @stable ICU 2.0
*/
//--public int getForm(){
function getForm() {
return ;
}
/**
* Returns the lostDigits setting.
* This will be either <code>true</code> (enabled) or
* <code>false</code> (disabled).
*
* @return a <code>boolean</code> which is the value of the lostDigits
* setting
* @stable ICU 2.0
*/
//--public boolean getLostDigits(){
function getLostDigits() {
return ;
}
/**
* Returns the roundingMode setting.
* This will be one of
* {@link #ROUND_CEILING},
* {@link #ROUND_DOWN},
* {@link #ROUND_FLOOR},
* {@link #ROUND_HALF_DOWN},
* {@link #ROUND_HALF_EVEN},
* {@link #ROUND_HALF_UP},
* {@link #ROUND_UNNECESSARY}, or
* {@link #ROUND_UP}.
*
* @return an <code>int</code> which is the value of the roundingMode
* setting
* @stable ICU 2.0
*/
//--public int getRoundingMode(){
function getRoundingMode() {
return ;
}
/** Returns the <code>MathContext</code> as a readable string.
* The <code>String</code> returned represents the settings of the
* <code>MathContext</code> object as four blank-delimited words
* separated by a single blank and with no leading or trailing blanks,
* as follows:
* <ol>
* <li>
* <code>digits=</code>, immediately followed by
* the value of the digits setting as a numeric word.
* <li>
* <code>form=</code>, immediately followed by
* the value of the form setting as an uppercase word
* (one of <code>SCIENTIFIC</code>, <code>PLAIN</code>, or
* <code>ENGINEERING</code>).
* <li>
* <code>lostDigits=</code>, immediately followed by
* the value of the lostDigits setting
* (<code>1</code> if enabled, <code>0</code> if disabled).
* <li>
* <code>roundingMode=</code>, immediately followed by
* the value of the roundingMode setting as a word.
* This word will be the same as the name of the corresponding public
* constant.
* </ol>
* <p>
* For example:
* <br><code>
* digits=9 form=SCIENTIFIC lostDigits=0 roundingMode=ROUND_HALF_UP
* </code>
* <p>
* Additional words may be appended to the result of
* <code>toString</code> in the future if more properties are added
* to the class.
*
* @return a <code>String</code> representing the context settings.
* @stable ICU 2.0
*/
//--public toString(){
function toString() {
//-- formstr=null;
var formstr=null;
//--int r=0;
var r=0;
//-- roundword=null;
var roundword=null;
{/*select*/
if (==)
formstr="SCIENTIFIC";
else if (==)
formstr="ENGINEERING";
else{
formstr="PLAIN";/* form=PLAIN */
}
}
{var $1=;r=0;r:for(;$1>0;$1--,r++){
if (==[r])
{
roundword=[r];
break r;
}
}
}/*r*/
return "digits="++" "+"form="+formstr+" "+"lostDigits="+(?"1":"0")+" "+"roundingMode="+roundword;
}
/* <sgml> Test whether round is valid. </sgml> */
// This could be made shared for use by BigDecimal for setScale.
//--private static boolean isValidRound(int testround){
function isValidRound(testround) {
//--int r=0;
var r=0;
{var $2=;r=0;r:for(;$2>0;$2--,r++){
if (testround==[r])
return true;
}
}/*r*/
return false;
}
return MathContext;
})();
var BigDecimal = (function (MathContext) {
/* Generated from '' 8 Sep 2000 11:10:50 [v2.00] */
/* Options: Binary Comments Crossref Format Java Logo Strictargs Strictcase Trace2 Verbose3 */
//--package ;
//--import ;
//--import ;
/* ------------------------------------------------------------------ */
/* 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. 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 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 (., 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 */
/* 1998.12.14 power operator no longer rounds RHS [to match ANSI] */
/* add toBigDecimal() and 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 [., 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;
}
= 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];
}
}
}
= arraycopy;
function createArrayWithZeros(length) {
var retVal = new Array(length);
var i;
for (i = 0; i < length; ++i) {
retVal[i] = 0;
}
return retVal;
}
= 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>/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>
* (extra)
* <br>(extra, )
* <br>(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></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")) => "4.40"
* <br>new BigDecimal("2.40").subtract(new BigDecimal("2")) => "0.40"
* <br>new BigDecimal("2.40").multiply(new BigDecimal("2")) => "4.80"
* <br>new BigDecimal("2.40").divide( new BigDecimal("2"), def) => "1.2"
* </code>
* <p>where the value on the right of the <code>=></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></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></code>, <code></code>,
* and <code></code> in Java 1.1 and Java 1.2.
*
* @see MathContext
* @author Mike Cowlishaw
* @stable ICU 2.0
*/
//--public class BigDecimal extends implements ,{
//-- private static final $0="";
//-- methods
= abs;
= add;
= compareTo;
= divide;
= divideInteger;
= max;
= min;
= multiply;
= negate;
= plus;
= pow;
= remainder;
= subtract;
= equals;
= format;
= intValueExact;
= movePointLeft;
= movePointRight;
= scale;
= setScale;
= signum;
= toString;
= layout;
= intcheck;
= dodivide;
= bad;
= badarg;
= extend;
= byteaddsub;
= diginit;
= clone;
= checkdigits;
= round;
= allzero;
= finish;
// Convenience methods
= isGreaterThan;
= isLessThan;
= isGreaterThanOrEqualTo;
= isLessThanOrEqualTo;
= isPositive;
= isNegative;
= 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=.ROUND_CEILING;
BigDecimal.ROUND_CEILING = .ROUND_CEILING = .ROUND_CEILING;
/**
* Rounding mode to round towards zero.
* @see MathContext#ROUND_DOWN
* @stable ICU 2.0
*/
//--public static final int ROUND_DOWN=.ROUND_DOWN;
BigDecimal.ROUND_DOWN = .ROUND_DOWN = .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=.ROUND_FLOOR;
BigDecimal.ROUND_FLOOR = .ROUND_FLOOR = .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=.ROUND_HALF_DOWN;
BigDecimal.ROUND_HALF_DOWN = .ROUND_HALF_DOWN = .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=.ROUND_HALF_EVEN;
BigDecimal.ROUND_HALF_EVEN = .ROUND_HALF_EVEN = .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=.ROUND_HALF_UP;
BigDecimal.ROUND_HALF_UP = .ROUND_HALF_UP = .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=.ROUND_UNNECESSARY;
BigDecimal.ROUND_UNNECESSARY = .ROUND_UNNECESSARY = .ROUND_UNNECESSARY;
/**
* Rounding mode to round away from zero.
* @see MathContext#ROUND_UP
* @stable ICU 2.0
*/
//--public static final int ROUND_UP=.ROUND_UP;
BigDecimal.ROUND_UP = .ROUND_UP = .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)
= 1;
= 0;
= -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
=-999999999; // minimum exponent allowed
=999999999; // maximum exponent allowed
=-999999999; // minimum argument integer
=999999999; // maximum argument integer
//--private static final plainMC=new (0,); // context for plain unlimited math
=new MathContext(0, );
/* properties constant private unused */ // present but not referenced
// Serialization version
//--private static final long serialVersionUID=8245355804974198832L;
//--private static final 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
= new Array((90+99)+1);
= diginit();
/**
* The <code>BigDecimal</code> constant "0".
*
* @see #ONE
* @see #TEN
* @stable ICU 2.0
*/
//--public static final ZERO=new ((long)0); // use long as we want the int constructor
// .. to be able to use this, for speed
= = new BigDecimal("0");
/**
* The <code>BigDecimal</code> constant "1".
*
* @see #TEN
* @see #ZERO
* @stable ICU 2.0
*/
//--public static final ONE=new ((long)1); // use long as we want the int constructor
// .. to be able to use this, for speed
= = new BigDecimal("1");
/**
* The <code>BigDecimal</code> constant "10".
*
* @see #ONE
* @see #ZERO
* @stable ICU 2.0
*/
//--public static final TEN=new (10);
= = 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> -- no exponent needed
* <li> -- scientific notation required
* <li> -- 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); // 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
* =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></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()} constructor had then been
* used.
* The parameter must not be <code>null</code>.
* <p>
* <i>(Note: this constructor is provided only in the
* <code></code> version of the BigDecimal class.
* It would not be present in a <code></code> version.)</i>
*
* @param bd The <code>BigDecimal</code> to be translated.
* @stable ICU 2.0
*/
//--public BigDecimal( bd){
//-- this(());
//-- 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( bi){
//-- this((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( bi,int scale){
//-- this((10));
//-- if (scale<0)
//-- throw new ("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()} 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,);
//-- 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()} 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
= 0;
= ;
= null;
= 0;
//-- overloaded ctor
if ( == 0)
return;
var inchars;
var offset;
var length;
if ( == 1)
{
inchars = [0];
offset = 0;
length = ;
}
else
{
inchars = [0];
offset = [1];
length = [2];
}
if (typeof inchars == "string")
{
inchars = ("");
}
//--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)
("BigDecimal(): ", inchars); // bad conversion (empty string)
// [bad offset will raise array bounds exception]
/* Handle and step past sign */
=; // assume positive
if (inchars[0]==('-'))
{
length--;
if (length==0)
("BigDecimal(): ", inchars); // nothing after sign
=;
offset++;
}
else
if (inchars[0]==('+'))
{
length--;
if (length==0)
("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)
("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')
("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))
("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))
("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')
("BigDecimal(): ", inchars); // always bad
if (sj>'9')
{ // maybe an exotic digit
/*if (si<'0' || si>'9')
(inchars); // not a number
dvalue=(sj,10); // check base
if (dvalue<0)
bad(inchars); // not base 10*/
("BigDecimal(): ", inchars);
}
else
dvalue=sj-'0';
=(*10)+dvalue;
}
}/*j*/
if (eneg)
=-; // was negative
hadexp=true; // remember we had one
break i; // we are done
}
}/*i*/
/* Here when all inspected */
if (d==0)
("BigDecimal(): ", inchars); // no mantissa digits
if (dotoff>=0)
=(+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 (((si,10))!=0)
break i; // non-0 or bad
// is 0 .. strip like '0'
//offset++;
//dotoff--;
//d--;
}
}
}/*i*/
/* Create the mantissa array */
=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')
[i]=sj-'0';/* easy */
else
{
//dvalue=(sj,10);
//if (dvalue<0)
("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++;
[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 ([0]==0)
{
=; // force to show zero
// negative exponent is significant (., -3 for 0.000) if plain
if (>0)
=0; // positive exponent can be ignored
if (hadexp)
{ // zero becomes single digit from add
=;
=0;
}
}
else
{ // non-zero
// [ind was set earlier]
// now determine form
if (hadexp)
{
=;
// 1999.06.29 check for overflow
mag=(+)-1; // true exponent in scientific notation
if ((mag<)||(mag>))
("BigDecimal(): ", inchars);
}
}
// say 'BD(c[]): mant[0] mantlen exp ind form:' mant[0] 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>()</code> method
* and then using the {@link #BigDecimal()}
* 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 (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=;
//-- ind=iszero;
//-- }
//-- else if (num==1)
//-- {
//-- mant=;
//-- ind=ispos;
//-- }
//-- else if (num==(-1))
//-- {
//-- 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((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>(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( string){
//-- this((),0,());
//-- 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, )</code>.
* <p>
* The length of the decimal part (the scale) of the result will
* be <code>()</code>
*
* @return A <code>BigDecimal</code> whose value is the absolute
* value of this <code>BigDecimal</code>.
* @stable ICU 2.0
*/
//--public abs(){
//- return (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 abs( set){
function abs() {
var set;
if ( == 1)
{
set = [0];
}
else if ( == 0)
{
set = ;
}
else
{
throw "abs(): " + + " arguments given; expected 0 or 1";
}
if (==)
return (set);
return (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, )</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 add( rhs){
//-- return (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 add( rhs, set){
function add() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "add(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
//-- lhs;
var lhs;
//--int reqdig;
var reqdig;
//-- 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 ()
(rhs,);
lhs=this; // name for clarity and proxy
/* Quick exit for add floating 0 */
// plus() will optimize to return same object if possible
if (==0)
if (!=)
return (set);
if (==0)
if (!=)
return (set);
/* Prepare numbers (round, unless unlimited precision) */
reqdig=; // local copy (heavily used)
if (reqdig>0)
{
if (>reqdig)
lhs=(lhs).round(set);
if (>reqdig)
rhs=(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
// use them on all paths except quick exits
usel=;
usellen=;
user=;
userlen=;
{padder:do{/*select*/
if (==)
{/* no padding needed */
// This is the most common, and fastest, path
=;
}
else if (>)
{ // need to pad lhs and/or truncate rhs
newlen=(usellen+)-;
/* If, after pad, lhs would be longer than rhs by digits+1 or
more (and digits>0) then rhs cannot affect answer, so we only
need to pad up to a length of DIGITS+1. */
if (newlen>=((userlen+reqdig)+1))
if (reqdig>0)
{
// LHS is sufficient
=usel;
=;
=;
if (usellen<reqdig)
{ // need 0 padding
=(,reqdig);
=-((reqdig-usellen));
}
return (set,false);
}
// RHS may affect result
=; // expected final exponent
if (newlen>(reqdig+1))
if (reqdig>0)
{
// LHS will be max; RHS truncated
tlen=(newlen-reqdig)-1; // truncation length
userlen=userlen-tlen;
=+tlen;
newlen=reqdig+1;
}
if (newlen>usellen)
usellen=newlen; // need to pad LHS
}
else{ // need to pad rhs and/or truncate lhs
newlen=(userlen+)-;
if (newlen>=((usellen+reqdig)+1))
if (reqdig>0)
{
// RHS is sufficient
=user;
=;
=;
if (userlen<reqdig)
{ // need 0 padding
=(,reqdig);
=-((reqdig-userlen));
}
return (set,false);
}
// LHS may affect result
=; // expected final exponent
if (newlen>(reqdig+1))
if (reqdig>0)
{
// RHS will be max; LHS truncated
tlen=(newlen-reqdig)-1; // truncation length
usellen=usellen-tlen;
=+tlen;
newlen=reqdig+1;
}
if (newlen>userlen)
userlen=newlen; // need to pad RHS
}
}while(false);}/*padder*/
/* OK, we have aligned mantissas. Now add or subtract. */
// 1998.06.27 Sign may now be 0 [., 0.000] .. treat as positive
// 1999.05.27 Allow for 00 on lhs [is not larger than 2 on rhs]
// 1999.07.10 Allow for 00 on rhs [is not larger than 2 on rhs]
if (==)
=;
else
=; // likely sign, all paths
if (((==)?1:0)==((==)?1:0)) // same sign, 0 non-negative
mult=1;
else
{signdiff:do{ // different signs, so subtraction is needed
mult=-1; // will cause subtract
/* Before we can subtract we must determine which is the larger,
as our add/subtract routine only handles non-negative results
so we may need to swap the operands. */
{swaptest:do{/*select*/
if (==)
{} // original A bigger
else if ((usellen<userlen)||(==))
{ // original B bigger
t=usel;
usel=user;
user=t; // swap
tlen=usellen;
usellen=userlen;
userlen=tlen; // ..
=-; // and set sign
}
else if (usellen>userlen)
{} // original A bigger
else{
{/* logical lengths the same */ // need compare
/* may still need to swap: compare the strings */
ia=0;
ib=0;
ea=-1;
eb=-1;
{compare:for(;;){
if (ia<=ea)
ca=usel[ia];
else
{
if (ib>eb)
{/* identical */
if (!=)
return ;
// [if PLAIN we must do the subtract, in case of 0.000 results]
break compare;
}
ca=0;
}
if (ib<=eb)
cb=user[ib];
else
cb=0;
if (ca!=cb)
{
if (ca<cb)
{/* swap needed */
t=usel;
usel=user;
user=t; // swap
tlen=usellen;
usellen=userlen;
userlen=tlen; // ..
=-;
}
break compare;
}
/* mantissas the same, so far */
ia++;
ib++;
}
}/*compare*/
} // lengths the same
}
}while(false);}/*swaptest*/
}while(false);}/*signdiff*/
/* here, A is > B if subtracting */
// add [A+B*1] or subtract [A+(B*-1)]
=(usel,usellen,user,userlen,mult,false);
// [reuse possible only after chop; accounting makes not worthwhile]
// Finish() rounds before stripping leading 0's, then sets form, etc.
return (set,false);
}
/**
* Compares this <code>BigDecimal</code> to another, using unlimited
* precision.
* <p>
* The same as {@link #compareTo(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @return An <code>int</code> whose value is -1, 0, or 1 as
* <code>this</code> is numerically less than, equal to,
* or greater than <code>rhs</code>.
* @see #compareTo(Object)
* @stable ICU 2.0
*/
//--public int compareTo( rhs){
//-- return (rhs,plainMC);
//-- }
/**
* Compares this <code>BigDecimal</code> to another.
* <p>
* Implements numeric comparison,
* (as defined in the decimal documentation, see {@link BigDecimal
* class header}),
* and returns a result of type <code>int</code>.
* <p>
* The result will be:
* <table cellpadding=2><tr>
* <td align=right><b>-1</b></td>
* <td>if the current object is less than the first parameter</td>
* </tr><tr>
* <td align=right><b>0</b></td>
* <td>if the current object is equal to the first parameter</td>
* </tr><tr>
* <td align=right><b>1</b></td>
* <td>if the current object is greater than the first parameter.</td>
* </tr></table>
* <p>
* A {@link #compareTo(Object)} method is also provided.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @param set The <code>MathContext</code> arithmetic settings.
* @return An <code>int</code> whose value is -1, 0, or 1 as
* <code>this</code> is numerically less than, equal to,
* or greater than <code>rhs</code>.
* @see #compareTo(Object)
* @stable ICU 2.0
*/
//public int compareTo( rhs, set){
function compareTo() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "compareTo(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
//--int thislength=0;
var thislength=0;
//--int i=0;
var i=0;
//-- newrhs;
var newrhs;
// rhs=null will raise NullPointerException, as per Comparable interface
if ()
(rhs,);
// [add will recheck in slowpath cases .. but would report -rhs]
if ((==)&&(==))
{
/* sign & exponent the same [very common] */
thislength=;
if (thislength<)
return -;
if (thislength>)
return ;
/* lengths are the same; we can do a straight mantissa compare
unless maybe rounding [rounding is very unusual] */
if ((thislength<=)||(==0))
{
{var $6=thislength;i=0;i:for(;$6>0;$6--,i++){
if ([i]<[i])
return -;
if ([i]>[i])
return ;
}
}/*i*/
return 0; // identical
}
/* drop through for full comparison */
}
else
{
/* More fastpaths possible */
if (<)
return -1;
if (>)
return 1;
}
/* carry out a subtract to make the comparison */
newrhs=(rhs); // safe copy
=-; // prepare to subtract
return (newrhs,set).ind; // add, and return sign of result
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic.
* <p>
* The same as {@link #divide(BigDecimal, int)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the rounding mode is {@link MathContext#ROUND_HALF_UP}.
*
* The length of the decimal part (the scale) of the result will be
* the same as the scale of the current object, if the latter were
* formatted without exponential notation.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the division.
* @return A plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @stable ICU 2.0
*/
//--public divide( rhs){
//-- return ('D',rhs,plainMC,-1);
//-- }
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic and a
* rounding mode.
* <p>
* The same as {@link #divide(BigDecimal, int, int)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the second parameter is <code>()</code>, and
* the third is <code>round</code>.
* <p>
* The length of the decimal part (the scale) of the result will
* therefore be the same as the scale of the current object, if the
* latter were formatted without exponential notation.
* <p>
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the division.
* @param round The <code>int</code> rounding mode to be used for
* the division (see the {@link MathContext} class).
* @return A plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic
* and the specified rounding mode.
* @throws IllegalArgumentException if <code>round</code> is not a
* valid rounding mode.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @throws ArithmeticException if <code>round</code> is {@link
* MathContext#ROUND_UNNECESSARY} and
* <code>()</code> is insufficient to
* represent the result exactly.
* @stable ICU 2.0
*/
//--public divide( rhs,int round){
//-- set;
//-- set=new (0,,false,round); // [checks round, too]
//-- return ('D',rhs,set,-1); // take scale from LHS
//-- }
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic and a
* given scale and rounding mode.
* <p>
* The same as {@link #divide(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* <code>new MathContext(0, , false, round)</code>,
* except that the length of the decimal part (the scale) to be used
* for the result is explicit rather than being taken from
* <code>this</code>.
* <p>
* The length of the decimal part (the scale) of the result will be
* the same as the scale of the current object, if the latter were
* formatted without exponential notation.
* <p>
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the division.
* @param scale The <code>int</code> scale to be used for the result.
* @param round The <code>int</code> rounding mode to be used for
* the division (see the {@link MathContext} class).
* @return A plain <code>BigDecimal</code> whose value is
* <code>this/rhs</code>, using fixed point arithmetic
* and the specified rounding mode.
* @throws IllegalArgumentException if <code>round</code> is not a
* valid rounding mode.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @throws ArithmeticException if <code>scale</code> is negative.
* @throws ArithmeticException if <code>round</code> is {@link
* MathContext#ROUND_UNNECESSARY} and <code>scale</code>
* is insufficient to represent the result exactly.
* @stable ICU 2.0
*/
//--public divide( rhs,int scale,int round){
//-- set;
//-- if (scale<0)
//-- throw new ("Negative scale:"+" "+scale);
//-- set=new (0,,false,round); // [checks round]
//-- return ('D',rhs,set,scale);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is <code>this/rhs</code>.
* <p>
* Implements the division (<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 division.
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* <code>this/rhs</code>.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @stable ICU 2.0
*/
//--public divide( rhs, set){
function divide() {
var set;
var scale = -1;
if ( == 2)
{
if (typeof [1] == 'number')
{
set=new MathContext(0,,false,[1]); // [checks round, too]
}
else
{
set = [1];
}
}
else if ( == 3)
{
scale = [1];
if (scale<0)
throw "divide(): Negative scale: "+scale;
set=new MathContext(0,,false,[2]); // [checks round]
}
else if ( == 1)
{
set = ;
}
else
{
throw "divide(): " + + " arguments given; expected between 1 and 3";
}
var rhs = [0];
return ('D',rhs,set,scale);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is the integer
* part of <code>this/rhs</code>.
* <p>
* The same as {@link #divideInteger(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the integer division.
* @return A <code>BigDecimal</code> whose value is the integer
* part of <code>this/rhs</code>.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @stable ICU 2.0
*/
//--public divideInteger( rhs){
//-- // scale 0 to drop .000 when plain
//-- return ('I',rhs,plainMC,0);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is the integer
* part of <code>this/rhs</code>.
* <p>
* Implements the integer division 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 integer division.
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is the integer
* part of <code>this/rhs</code>.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @throws ArithmeticException if the result will not fit in the
* number of digits specified for the context.
* @stable ICU 2.0
*/
//--public divideInteger( rhs, set){
function divideInteger() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "divideInteger(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
// scale 0 to drop .000 when plain
return ('I',rhs,set,0);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* the maximum of <code>this</code> and <code>rhs</code>.
* <p>
* The same as {@link #max(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @return A <code>BigDecimal</code> whose value is
* the maximum of <code>this</code> and <code>rhs</code>.
* @stable ICU 2.0
*/
//--public max( rhs){
//-- return (rhs,plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is
* the maximum of <code>this</code> and <code>rhs</code>.
* <p>
* Returns the larger of the current object and the first parameter.
* <p>
* If calling the {@link #compareTo(BigDecimal, MathContext)} method
* with the same parameters would return <code>1</code> or
* <code>0</code>, then the result of calling the
* {@link #plus(MathContext)} method on the current object (using the
* same <code>MathContext</code> parameter) is returned.
* Otherwise, the result of calling the {@link #plus(MathContext)}
* method on the first parameter object (using the same
* <code>MathContext</code> parameter) is returned.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* the maximum of <code>this</code> and <code>rhs</code>.
* @stable ICU 2.0
*/
//--public max( rhs, set){
function max() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "max(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
if (((rhs,set))>=0)
return (set);
else
return (set);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* the minimum of <code>this</code> and <code>rhs</code>.
* <p>
* The same as {@link #min(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @return A <code>BigDecimal</code> whose value is
* the minimum of <code>this</code> and <code>rhs</code>.
* @stable ICU 2.0
*/
//--public min( rhs){
//-- return (rhs,plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is
* the minimum of <code>this</code> and <code>rhs</code>.
* <p>
* Returns the smaller of the current object and the first parameter.
* <p>
* If calling the {@link #compareTo(BigDecimal, MathContext)} method
* with the same parameters would return <code>-1</code> or
* <code>0</code>, then the result of calling the
* {@link #plus(MathContext)} method on the current object (using the
* same <code>MathContext</code> parameter) is returned.
* Otherwise, the result of calling the {@link #plus(MathContext)}
* method on the first parameter object (using the same
* <code>MathContext</code> parameter) is returned.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the comparison.
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* the minimum of <code>this</code> and <code>rhs</code>.
* @stable ICU 2.0
*/
//--public min( rhs, set){
function min() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "min(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
if (((rhs,set))<=0)
return (set);
else
return (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, )</code>.
* <p>
* The length of the decimal part (the scale) of the result will be
* the sum of the scales of the operands, if they were formatted
* without exponential notation.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the multiplication.
* @return A <code>BigDecimal</code> whose value is
* <code>this*rhs</code>, using fixed point arithmetic.
* @stable ICU 2.0
*/
//--public multiply( rhs){
//-- return (rhs,plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is <code>this*rhs</code>.
* <p>
* Implements the multiplication (<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 multiplication.
* @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 multiply( rhs, set){
function multiply() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "multiply(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
//-- lhs;
var lhs;
//--int padding;
var padding;
//--int reqdig;
var reqdig;
//--byte multer[]=null;
var multer=null;
//--byte multand[]=null;
var multand=null;
//--int multandlen;
var multandlen;
//--int acclen=0;
var acclen=0;
//-- res;
var res;
//--byte acc[];
var acc;
//--int n=0;
var n=0;
//--byte mult=0;
var mult=0;
if ()
(rhs,);
lhs=this; // name for clarity and proxy
/* Prepare numbers (truncate, unless unlimited precision) */
padding=0; // trailing 0's to add
reqdig=; // local copy
if (reqdig>0)
{
if (>reqdig)
lhs=(lhs).round(set);
if (>reqdig)
rhs=(rhs).round(set);
// [we could reuse the new LHS for result in this case]
}
else
{/* unlimited */
// fixed point arithmetic will want every trailing 0; we add these
// after the calculation rather than before, for speed.
if (>0)
padding=padding+;
if (>0)
padding=padding+;
}
// For best speed, as in DMSRCN, we use the shorter number as the
// multiplier and the longer as the multiplicand.
// 1999.12.22: We used to special case when the result would fit in
// a long, but with Java 1.3 this gave no advantage.
if (<)
{
multer=;
multand=;
}
else
{
multer=;
multand=;
}
/* Calculate how long result byte array will be */
multandlen=(+)-1; // effective length
// optimize for 75% of the cases where a carry is expected...
if ((multer[0]*multand[0])>9)
acclen=multandlen+1;
else
acclen=multandlen;
/* Now the main long multiplication loop */
res=new BigDecimal(); // where we'll build result
acc=(acclen); // accumulator, all zeros
// 1998.07.01: calculate from left to right so that accumulator goes
// to likely final length on first addition; this avoids a one-digit
// extension (and object allocation) each time around the loop.
// Initial number therefore has virtual zeros added to right.
{var $7=;n=0;n:for(;$7>0;$7--,n++){
mult=multer[n];
if (mult!=0)
{ // [optimization]
// accumulate [accumulator is reusable array]
acc=(acc,,multand,multandlen,mult,true);
}
// divide multiplicand by 10 for next digit to right
multandlen--; // 'virtual length'
}
}/*n*/
=*; // final sign
=(+)-padding; // final exponent
// [overflow is checked by finish]
/* add trailing zeros to the result, if necessary */
if (padding==0)
=acc;
else
=(acc,+padding); // add trailing 0s
return (set,false);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>-this</code>.
* <p>
* The same as {@link #negate(MathContext)}, where the context is
* <code>new MathContext(0, )</code>.
* <p>
* The length of the decimal part (the scale) of the result will be
* be <code>()</code>
*
*
* @return A <code>BigDecimal</code> whose value is
* <code>-this</code>.
* @stable ICU 2.0
*/
//--public negate(){
//-- return (plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is <code>-this</code>.
* <p>
* Implements the negation (Prefix <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 set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* <code>-this</code>.
* @stable ICU 2.0
*/
//public negate( set){
function negate() {
var set;
if ( == 1)
{
set = [0];
}
else if ( == 0)
{
set = ;
}
else
{
throw "negate(): " + + " arguments given; expected 0 or 1";
}
//-- res;
var res;
// Originally called minus(), changed to matched Java precedents
// This simply clones, flips the sign, and possibly rounds
if ()
(null,);
res=(this); // safe copy
=-;
return (set,false);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>+this</code>.
* Note that <code>this</code> is not necessarily a
* plain <code>BigDecimal</code>, but the result will always be.
* <p>
* The same as {@link #plus(MathContext)}, where the context is
* <code>new MathContext(0, )</code>.
* <p>
* The length of the decimal part (the scale) of the result will be
* be <code>()</code>
*
* @return A <code>BigDecimal</code> whose value is
* <code>+this</code>.
* @stable ICU 2.0
*/
//--public plus(){
//-- return (plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is
* <code>+this</code>.
* <p>
* Implements the plus (Prefix <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.
* <p>
* This method is useful for rounding or otherwise applying a context
* to a decimal value.
*
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* <code>+this</code>.
* @stable ICU 2.0
*/
//public plus( set){
function plus() {
var set;
if ( == 1)
{
set = [0];
}
else if ( == 0)
{
set = ;
}
else
{
throw "plus(): " + + " arguments given; expected 0 or 1";
}
// This clones and forces the result to the new settings
// May return same object
if ()
(null,);
// Optimization: returns same object for some common cases
if (==)
if (==)
{
if (<=)
return this;
if (==0)
return this;
}
return (this).finish(set,false);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>this**rhs</code>, using fixed point arithmetic.
* <p>
* The same as {@link #pow(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
* <p>
* The parameter is the power to which the <code>this</code> will be
* raised; it must be in the range 0 through 999999999, and must
* have a decimal part of zero. Note that these restrictions may be
* removed in the future, so they should not be used as a test for a
* whole number.
* <p>
* In addition, the power must not be negative, as no
* <code>MathContext</code> is used and so the result would then
* always be 0.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the operation (the power).
* @return A <code>BigDecimal</code> whose value is
* <code>this**rhs</code>, using fixed point arithmetic.
* @throws ArithmeticException if <code>rhs</code> is out of range or
* is not a whole number.
* @stable ICU 2.0
*/
//--public pow( rhs){
//-- return (rhs,plainMC);
//-- }
// The name for this method is inherited from the precedent set by the
// BigInteger and Math classes.
/**
* Returns a <code>BigDecimal</code> whose value is <code>this**rhs</code>.
* <p>
* Implements the power (<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.
* <p>
* The first parameter is the power to which the <code>this</code>
* will be raised; it must be in the range -999999999 through
* 999999999, and must have a decimal part of zero. Note that these
* restrictions may be removed in the future, so they should not be
* used as a test for a whole number.
* <p>
* If the <code>digits</code> setting of the <code>MathContext</code>
* parameter is 0, the power must be zero or positive.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the operation (the power).
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is
* <code>this**rhs</code>.
* @throws ArithmeticException if <code>rhs</code> is out of range or
* is not a whole number.
* @stable ICU 2.0
*/
//--public pow( rhs, set){
function pow() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "pow(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
//--int n;
var n;
//-- lhs;
var lhs;
//--int reqdig;
var reqdig;
//-- int workdigits=0;
var workdigits=0;
//--int L=0;
var L=0;
//-- workset;
var workset;
//-- res;
var res;
//--boolean seenbit;
var seenbit;
//--int i=0;
var i=0;
if ()
(rhs,);
n=(,); // check RHS by the rules
lhs=this; // clarified name
reqdig=; // local copy (heavily used)
if (reqdig==0)
{
if (==)
//--throw new ("Negative power:"+" "+());
throw "pow(): Negative power: " + ();
workdigits=0;
}
else
{/* non-0 digits */
if ((+)>reqdig)
//--throw new ("Too many digits:"+" "+());
throw "pow(): Too many digits: " + ();
/* Round the lhs to DIGITS if need be */
if (>reqdig)
lhs=(lhs).round(set);
/* L for precision calculation [see ANSI X3.274-1996] */
L=+; // length without decimal zeros/exp
workdigits=(reqdig+L)+1; // calculate the working DIGITS
}
/* Create a copy of set for working settings */
// Note: no need to check for lostDigits again.
// 1999.07.17 Note: this construction must follow RHS check
workset=new MathContext(workdigits,,false,);
res=; // accumulator
if (n==0)
return res; // x**0 == 1
if (n<0)
n=-n; // [ records the sign]
seenbit=false; // set once we've seen a 1-bit
{i=1;i:for(;;i++){ // for each bit [top bit ignored]
//n=n+n; // shift left 1 bit
n<<=1;
if (n<0)
{ // top bit is set
seenbit=true; // OK, we're off
res=(lhs,workset); // acc=acc*x
}
if (i==31)
break i; // that was the last bit
if ((!seenbit))
continue i; // we don't have to square 1
res=(res,workset); // acc=acc*acc [square]
}
}/*i*/ // 32 bits
if (<0) // was a **-n [hence digits>0]
res=(res,workset); // .. so acc=1/acc
return (set,true); // round and strip [original digits]
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* the remainder of <code>this/rhs</code>, using fixed point arithmetic.
* <p>
* The same as {@link #remainder(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</code>.
* <p>
* This is not the modulo operator -- the result may be negative.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the remainder operation.
* @return A <code>BigDecimal</code> whose value is the remainder
* of <code>this/rhs</code>, using fixed point arithmetic.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @stable ICU 2.0
*/
//--public remainder( rhs){
//-- return ('R',rhs,plainMC,-1);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is the remainder of
* <code>this/rhs</code>.
* <p>
* Implements the remainder operator
* (as defined in the decimal documentation, see {@link BigDecimal
* class header}),
* and returns the result as a <code>BigDecimal</code> object.
* <p>
* This is not the modulo operator -- the result may be negative.
*
* @param rhs The <code>BigDecimal</code> for the right hand side of
* the remainder operation.
* @param set The <code>MathContext</code> arithmetic settings.
* @return A <code>BigDecimal</code> whose value is the remainder
* of <code>this+rhs</code>.
* @throws ArithmeticException if <code>rhs</code> is zero.
* @throws ArithmeticException if the integer part of the result will
* not fit in the number of digits specified for the
* context.
* @stable ICU 2.0
*/
//--public remainder( rhs, set){
function remainder() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "remainder(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
return ('R',rhs,set,-1);
}
/**
* Returns a plain <code>BigDecimal</code> whose value is
* <code>this-rhs</code>, using fixed point arithmetic.
* <p>
* The same as {@link #subtract(BigDecimal, MathContext)},
* where the <code>BigDecimal</code> is <code>rhs</code>,
* and the context is <code>new MathContext(0, )</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 subtraction.
* @return A <code>BigDecimal</code> whose value is
* <code>this-rhs</code>, using fixed point arithmetic.
* @stable ICU 2.0
*/
//--public subtract( rhs){
//-- return (rhs,plainMC);
//-- }
/**
* Returns a <code>BigDecimal</code> whose value is <code>this-rhs</code>.
* <p>
* Implements the subtraction (<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 subtraction.
* @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 subtract( rhs, set){
function subtract() {
var set;
if ( == 2)
{
set = [1];
}
else if ( == 1)
{
set = ;
}
else
{
throw "subtract(): " + + " arguments given; expected 1 or 2";
}
var rhs = [0];
//-- newrhs;
var newrhs;
if ()
(rhs,);
// [add will recheck .. but would report -rhs]
/* carry out the subtraction */
// we could fastpath -0, but it is too rare.
newrhs=(rhs); // safe copy
=-; // prepare to subtract
return (newrhs,set); // arithmetic
}
/* ---------------------------------------------------------------- */
/* Other methods */
/* ---------------------------------------------------------------- */
/**
* Converts this <code>BigDecimal</code> to a <code>byte</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part or is
* out of the possible range for a <code>byte</code> (8-bit signed
* integer) result then an <code>ArithmeticException</code> is thrown.
*
* @return A <code>byte</code> equal in value to <code>this</code>.
* @throws ArithmeticException if <code>this</code> has a non-zero
* decimal part, or will not fit in a <code>byte</code>.
* @stable ICU 2.0
*/
//--public byte byteValueExact(){
//-- int num;
//-- num=(); // will check decimal part too
//-- if ((num>127)|(num<(-128)))
//-- throw new ("Conversion overflow:"+" "+());
//-- return (byte)num;
//-- }
/**
* Compares this <code>BigDecimal</code> with the value of the parameter.
* <p>
* If the parameter is <code>null</code>, or is not an instance of the
* <code>BigDecimal</code> type, an exception is thrown.
* Otherwise, the parameter is cast to type <code>BigDecimal</code>
* and the result of the {@link #compareTo(BigDecimal)} method,
* using the cast parameter, is returned.
* <p>
* The {@link #compareTo(BigDecimal, MathContext)} method should be
* used when a <code>MathContext</code> is needed for the comparison.
*
* @param rhs The <code>Object</code> for the right hand side of
* the comparison.
* @return An <code>int</code> whose value is -1, 0, or 1 as
* <code>this</code> is numerically less than, equal to,
* or greater than <code>rhs</code>.
* @throws ClassCastException if <code>rhs</code> cannot be cast to
* a <code>BigDecimal</code> object.
* @see #compareTo(BigDecimal)
* @stable ICU 2.0
*/
//--public int compareTo( rhsobj){
//-- // the cast in the next line will raise ClassCastException if necessary
//-- return compareTo(()rhsobj,plainMC);
//-- }
/**
* Converts this <code>BigDecimal</code> to a <code>double</code>.
* If the <code>BigDecimal</code> is out of the possible range for a
* <code>double</code> (64-bit signed floating point) result then an
* <code>ArithmeticException</code> is thrown.
* <p>
* The double produced is identical to result of expressing the
* <code>BigDecimal</code> as a <code>String</code> and then
* converting it using the <code>Double(String)</code> constructor;
* this can result in values of <code>Double.NEGATIVE_INFINITY</code>
* or <code>Double.POSITIVE_INFINITY</code>.
*
* @return A <code>double</code> corresponding to <code>this</code>.
* @stable ICU 2.0
*/
//--public double doubleValue(){
//-- // We go via a String [as does BigDecimal in JDK 1.2]
//-- // Next line could possibly raise NumberFormatException
//-- return (()).doubleValue();
//-- }
/**
* Compares this <code>BigDecimal</code> with <code>rhs</code> for
* equality.
* <p>
* If the parameter is <code>null</code>, or is not an instance of the
* BigDecimal type, or is not exactly equal to the current
* <code>BigDecimal</code> object, then <i>false</i> is returned.
* Otherwise, <i>true</i> is returned.
* <p>
* "Exactly equal", here, means that the <code>String</code>
* representations of the <code>BigDecimal</code> numbers are
* identical (they have the same characters in the same sequence).
* <p>
* The {@link #compareTo(BigDecimal, MathContext)} method should be
* used for more general comparisons.
* @param rhs The <code>Object</code> for the right hand side of
* the comparison.
* @return A <code>boolean</code> whose value <i>true</i> if and
* only if the operands have identical string representations.
* @throws ClassCastException if <code>rhs</code> cannot be cast to
* a <code>BigDecimal</code> object.
* @stable ICU 2.0
* @see #compareTo(Object)
* @see #compareTo(BigDecimal)
* @see #compareTo(BigDecimal, MathContext)
*/
//--public boolean equals( obj){
function equals(obj) {
//-- rhs;
var rhs;
//--int i=0;
var i=0;
//--char lca[]=null;
var lca=null;
//--char rca[]=null;
var rca=null;
// We are equal iff toString of both are exactly the same
if (obj==null)
return false; // not equal
if ((!(((obj instanceof BigDecimal)))))
return false; // not a decimal
rhs=obj; // cast; we know it will work
if (!=)
return false; // different signs never match
if (((==)&&(==))&&(==))
{ // mantissas say all
// here with equal-length byte arrays to compare
{var $8=;i=0;i:for(;$8>0;$8--,i++){
if ([i]!=[i])
return false;
}
}/*i*/
}
else
{ // need proper layout
lca=(); // layout to character array
rca=();
if (!=)
return false; // mismatch
// here with equal-length character arrays to compare
{var $9=;i=0;i:for(;$9>0;$9--,i++){
if (lca[i]!=rca[i])
return false;
}
}/*i*/
}
return true; // arrays have identical content
}
/**
* Converts this <code>BigDecimal</code> to a <code>float</code>.
* If the <code>BigDecimal</code> is out of the possible range for a
* <code>float</code> (32-bit signed floating point) result then an
* <code>ArithmeticException</code> is thrown.
* <p>
* The float produced is identical to result of expressing the
* <code>BigDecimal</code> as a <code>String</code> and then
* converting it using the <code>Float(String)</code> constructor;
* this can result in values of <code>Float.NEGATIVE_INFINITY</code>
* or <code>Float.POSITIVE_INFINITY</code>.
*
* @return A <code>float</code> corresponding to <code>this</code>.
* @stable ICU 2.0
*/
//--public float floatValue(){
//-- return (()).floatValue();
//-- }
/**
* Returns the <code>String</code> representation of this
* <code>BigDecimal</code>, modified by layout parameters.
* <p>
* <i>This method is provided as a primitive for use by more
* sophisticated classes, such as <code>DecimalFormat</code>, that
* can apply locale-sensitive editing of the result. The level of
* formatting that it provides is a necessary part of the BigDecimal
* class as it is sensitive to and must follow the calculation and
* rounding rules for BigDecimal arithmetic.
* However, if the function is provided elsewhere, it may be removed
* from this class. </i>
* <p>
* The parameters, for both forms of the <code>format</code> method
* are all of type <code>int</code>.
* A value of -1 for any parameter indicates that the default action
* or value for that parameter should be used.
* <p>
* The parameters, <code>before</code> and <code>after</code>,
* specify the number of characters to be used for the integer part
* and decimal part of the result respectively. Exponential notation
* is not used. If either parameter is -1 (which indicates the default
* action), the number of characters used will be exactly as many as
* are needed for that part.
* <p>
* <code>before</code> must be a positive number; if it is larger than
* is needed to contain the integer part, that part is padded on the
* left with blanks to the requested length. If <code>before</code> is
* not large enough to contain the integer part of the number
* (including the sign, for negative numbers) an exception is thrown.
* <p>
* <code>after</code> must be a non-negative number; if it is not the
* same size as the decimal part of the number, the number will be
* rounded (or extended with zeros) to fit. Specifying 0 for
* <code>after</code> will cause the number to be rounded to an
* integer (that is, it will have no decimal part or decimal point).
* The rounding method will be the default,
* <code>MathContext.ROUND_HALF_UP</code>.
* <p>
* Other rounding methods, and the use of exponential notation, can
* be selected by using {@link #format(int,int,int,int,int,int)}.
* Using the two-parameter form of the method has exactly the same
* effect as using the six-parameter form with the final four
* parameters all being -1.
*
* @param before The <code>int</code> specifying the number of places
* before the decimal point. Use -1 for 'as many as
* are needed'.
* @param after The <code>int</code> specifying the number of places
* after the decimal point. Use -1 for 'as many as are
* needed'.
* @return A <code>String</code> representing this
* <code>BigDecimal</code>, laid out according to the
* specified parameters
* @throws ArithmeticException if the number cannot be laid out as
* requested.
* @throws IllegalArgumentException if a parameter is out of range.
* @stable ICU 2.0
* @see #toString
* @see #toCharArray
*/
//--public format(int before,int after){
//-- return format(before,after,-1,-1,,ROUND_HALF_UP);
//-- }
/**
* Returns the <code>String</code> representation of this
* <code>BigDecimal</code>, modified by layout parameters and allowing
* exponential notation.
* <p>
* <i>This method is provided as a primitive for use by more
* sophisticated classes, such as <code>DecimalFormat</code>, that
* can apply locale-sensitive editing of the result. The level of
* formatting that it provides is a necessary part of the BigDecimal
* class as it is sensitive to and must follow the calculation and
* rounding rules for BigDecimal arithmetic.
* However, if the function is provided elsewhere, it may be removed
* from this class. </i>
* <p>
* The parameters are all of type <code>int</code>.
* A value of -1 for any parameter indicates that the default action
* or value for that parameter should be used.
* <p>
* The first two parameters (<code>before</code> and
* <code>after</code>) specify the number of characters to be used for
* the integer part and decimal part of the result respectively, as
* defined for {@link #format(int,int)}.
* If either of these is -1 (which indicates the default action), the
* number of characters used will be exactly as many as are needed for
* that part.
* <p>
* The remaining parameters control the use of exponential notation
* and rounding. Three (<code>explaces</code>, <code>exdigits</code>,
* and <code>exform</code>) control the exponent part of the result.
* As before, the default action for any of these parameters may be
* selected by using the value -1.
* <p>
* <code>explaces</code> must be a positive number; it sets the number
* of places (digits after the sign of the exponent) to be used for
* any exponent part, the default (when <code>explaces</code> is -1)
* being to use as many as are needed.
* If <code>explaces</code> is not -1, space is always reserved for
* an exponent; if one is not needed (for example, if the exponent
* will be 0) then <code>explaces</code>+2 blanks are appended to the
* result.
* <!-- (This preserves vertical alignment of similarly formatted
* numbers in a monospace font.) -->
* If <code>explaces</code> is not -1 and is not large enough to
* contain the exponent, an exception is thrown.
* <p>
* <code>exdigits</code> sets the trigger point for use of exponential
* notation. If, before any rounding, the number of places needed
* before the decimal point exceeds <code>exdigits</code>, or if the
* absolute value of the result is less than <code>0.000001</code>,
* then exponential form will be used, provided that
* <code>exdigits</code> was specified.
* When <code>exdigits</code> is -1, exponential notation will never
* be used. If 0 is specified for <code>exdigits</code>, exponential
* notation is always used unless the exponent would be 0.
* <p>
* <code>exform</code> sets the form for exponential notation (if
* needed).
* It may be either {@link MathContext#SCIENTIFIC} or
* {@link MathContext#ENGINEERING}.
* If the latter, engineering, form is requested, up to three digits
* (plus sign, if negative) may be needed for the integer part of the
* result (<code>before</code>). Otherwise, only one digit (plus
* sign, if negative) is needed.
* <p>
* Finally, the sixth argument, <code>exround</code>, selects the
* rounding algorithm to be used, and must be one of the values
* indicated by a public constant in the {@link MathContext} class
* whose name starts with <code>ROUND_</code>.
* The default (<code>ROUND_HALF_UP</code>) may also be selected by
* using the value -1, as before.
* <p>
* The special value <code>MathContext.ROUND_UNNECESSARY</code> may be
* used to detect whether non-zero digits are discarded -- if
* <code>exround</code> has this value than if non-zero digits would
* be discarded (rounded) during formatting then an
* <code>ArithmeticException</code> is thrown.
*
* @param before The <code>int</code> specifying the number of places
* before the decimal point.
* Use -1 for 'as many as are needed'.
* @param after The <code>int</code> specifying the number of places
* after the decimal point.
* Use -1 for 'as many as are needed'.
* @param explaces The <code>int</code> specifying the number of places
* to be used for any exponent.
* Use -1 for 'as many as are needed'.
* @param exdigits The <code>int</code> specifying the trigger
* (digits before the decimal point) which if
* exceeded causes exponential notation to be used.
* Use 0 to force exponential notation.
* Use -1 to force plain notation (no exponential
* notation).
* @param exform The <code>int</code> specifying the form of
* exponential notation to be used
* ({@link MathContext#SCIENTIFIC} or
* {@link MathContext#ENGINEERING}).
* @param exround The <code>int</code> specifying the rounding mode
* to use.
* Use -1 for the default, {@link MathContext#ROUND_HALF_UP}.
* @return A <code>String</code> representing this
* <code>BigDecimal</code>, laid out according to the
* specified parameters
* @throws ArithmeticException if the number cannot be laid out as
* requested.
* @throws IllegalArgumentException if a parameter is out of range.
* @see #toString
* @see #toCharArray
* @stable ICU 2.0
*/
//--public format(int before,int after,int explaces,int exdigits,int exformint,int exround){
function format() {
var explaces;
var exdigits;
var exformint;
var exround;
if ( == 6)
{
explaces = [2];
exdigits = [3];
exformint = [4];
exround = [5];
}
else if ( == 2)
{
explaces = -1;
exdigits = -1;
exformint = ;
exround = this.ROUND_HALF_UP;
}
else
{
throw "format(): " + + " arguments given; expected 2 or 6";
}
var before = [0];
var after = [1];
//-- num;
var num;
//--int mag=0;
var mag=0;
//--int thisafter=0;
var thisafter=0;
//--int lead=0;
var lead=0;
//--byte newmant[]=null;
var newmant=null;
//--int chop=0;
var chop=0;
//--int need=0;
var need=0;
//--int oldexp=0;
var oldexp=0;
//--char a[];
var a;
//--int p=0;
var p=0;
//--char newa[]=null;
var newa=null;
//--int i=0;
var i=0;
//--int places=0;
var places=0;
/* Check arguments */
if ((before<(-1))||(before==0))
("format",1,before);
if (after<(-1))
("format",2,after);
if ((explaces<(-1))||(explaces==0))
("format",3,explaces);
if (exdigits<(-1))
("format",4,exdigits);
{/*select*/
if (exformint==)
{}
else if (exformint==)
{}
else if (exformint==(-1))
exformint=;
// note PLAIN isn't allowed
else{
("format",5,exformint);
}
}
// checking the rounding mode is done by trying to construct a
// MathContext object with that mode; it will fail if bad
if (exround!=this.ROUND_HALF_UP)
{try{ // if non-default...
if (exround==(-1))
exround=this.ROUND_HALF_UP;
else
new MathContext(9,,false,exround);
}
catch ($10){
("format",6,exround);
}}
num=(this); // make private copy
/* Here:
num is BigDecimal to format
before is places before point [>0]
after is places after point [>=0]
explaces is exponent places [>0]
exdigits is exponent digits [>=0]
exformint is exponent form [one of two]
exround is rounding mode [one of eight]
'before' through 'exdigits' are -1 if not specified
*/
/* determine form */
{setform:do{/*select*/
if (exdigits==(-1))
=;
else if (==)
=;
else{
// determine whether triggers
mag=+;
if (mag>exdigits)
=exformint;
else
if (mag<(-5))
=exformint;
else
=;
}
}while(false);}/*setform*/
/* If 'after' was specified then we may need to adjust the
mantissa. This is a little tricky, as we must conform to the
rules of exponential layout if necessary (., we cannot end up
with 10.0 if scientific). */
if (after>=0)
{setafter:for(;;){
// calculate the current after-length
{/*select*/
if (==)
thisafter=-; // has decimal part
else if (==)
thisafter=-1;
else{ // engineering
lead=(((+)-1))%3; // exponent to use
if (lead<0)
lead=3+lead; // negative exponent case
lead++; // number of leading digits
if (lead>=)
thisafter=0;
else
thisafter=-lead;
}
}
if (thisafter==after)
break setafter; // we're in luck
if (thisafter<after)
{ // need added trailing zeros
// [thisafter can be negative]
newmant=(,(+after)-thisafter);
=newmant;
=-((after-thisafter)); // adjust exponent
if (<)
throw "format(): Exponent Overflow: " + ;
break setafter;
}
// We have too many digits after the decimal point; this could
// cause a carry, which could change the mantissa...
// Watch out for implied leading zeros in PLAIN case
chop=thisafter-after; // digits to lop [is >0]
if (chop>)
{ // all digits go, no chance of carry
// carry on with zero
=;
=;
=0;
continue setafter; // recheck: we may need trailing zeros
}
// we have a digit to inspect from existing mantissa
// round the number as required
need=-chop; // digits to end up with [may be 0]
oldexp=; // save old exponent
(need,exround);
// if the exponent grew by more than the digits we chopped, then
// we must have had a carry, so will need to recheck the layout
if ((-oldexp)==chop)
break setafter; // number did not have carry
// mantissa got extended .. so go around and check again
}
}/*setafter*/
a=(); // lay out, with exponent if required, etc.
/* Here we have laid-out number in 'a' */
// now apply 'before' and 'explaces' as needed
if (before>0)
{
// look for '.' or 'E'
{var $11=;p=0;p:for(;$11>0;$11--,p++){
if (a[p]=='.')
break p;
if (a[p]=='E')
break p;
}
}/*p*/
// p is now offset of '.', 'E', or character after end of array
// that is, the current length of before part
if (p>before)
("format",1,before); // won't fit
if (p<before)
{ // need leading blanks
newa=new Array((+before)-p);
{var $12=before-p;i=0;i:for(;$12>0;$12--,i++){
newa[i]=' ';
}
}/*i*/
//--(()a,0,()newa,i,);
(a,0,newa,i,);
a=newa;
}
// [if p=before then it's just the right length]
}
if (explaces>0)
{
// look for 'E' [cannot be at offset 0]
{var $13=-1;p=-1;p:for(;$13>0;$13--,p--){
if (a[p]=='E')
break p;
}
}/*p*/
// p is now offset of 'E', or 0
if (p==0)
{ // no E part; add trailing blanks
newa=new Array((+explaces)+2);
//--(()a,0,()newa,0,);
(a,0,newa,0,);
{var $14=explaces+2;i=;i:for(;$14>0;$14--,i++){
newa[i]=' ';
}
}/*i*/
a=newa;
}
else
{/* found E */ // may need to insert zeros
places=(-p)-2; // number so far
if (places>explaces)
("format",3,explaces);
if (places<explaces)
{ // need to insert zeros
newa=new Array((+explaces)-places);
//--(()a,0,()newa,0,p+2); // through E and sign
(a,0,newa,0,p+2);
{var $15=explaces-places;i=p+2;i:for(;$15>0;$15--,i++){
newa[i]='0';
}
}/*i*/
//--(()a,p+2,()newa,i,places); // remainder of exponent
(a,p+2,newa,i,places);
a=newa;
}
// [if places=explaces then it's just the right length]
}
}
return ("");
}
/**
* Returns the hashcode for this <code>BigDecimal</code>.
* This hashcode is suitable for use by the
* <code></code> class.
* <p>
* Note that two <code>BigDecimal</code> objects are only guaranteed
* to produce the same hashcode if they are exactly equal (that is,
* the <code>String</code> representations of the
* <code>BigDecimal</code> numbers are identical -- they have the same
* characters in the same sequence).
*
* @return An <code>int</code> that is the hashcode for <code>this</code>.
* @stable ICU 2.0
*/
//--public int hashCode(){
//-- // Maybe calculate ourselves, later. If so, note that there can be
//-- // more than one internal representation for a given toString() result.
//-- return ().hashCode();
//-- }
/**
* Converts this <code>BigDecimal</code> to an <code>int</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part it is
* discarded. If the <code>BigDecimal</code> is out of the possible
* range for an <code>int</code> (32-bit signed integer) result then
* only the low-order 32 bits are used. (That is, the number may be
* <i>decapitated</i>.) To avoid unexpected errors when these
* conditions occur, use the {@link #intValueExact} method.
*
* @return An <code>int</code> converted from <code>this</code>,
* truncated and decapitated if necessary.
* @stable ICU 2.0
*/
//--public int intValue(){
//-- return toBigInteger().intValue();
//-- }
/**
* Converts this <code>BigDecimal</code> to an <code>int</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part or is
* out of the possible range for an <code>int</code> (32-bit signed
* integer) result then an <code>ArithmeticException</code> is thrown.
*
* @return An <code>int</code> equal in value to <code>this</code>.
* @throws ArithmeticException if <code>this</code> has a non-zero
* decimal part, or will not fit in an
* <code>int</code>.
* @stable ICU 2.0
*/
//--public int intValueExact(){
function intValueExact() {
//--int lodigit;
var lodigit;
//--int useexp=0;
var useexp=0;
//--int result;
var result;
//--int i=0;
var i=0;
//--int topdig=0;
var topdig=0;
// This does not use longValueExact() as the latter can be much
// slower.
// intcheck (from pow) relies on this to check decimal part
if (==)
return 0; // easy, and quite common
/* test and drop any trailing decimal part */
lodigit=-1;
if (<0)
{
lodigit=lodigit+; // reduces by -(-exp)
/* all decimal places must be 0 */
if ((!((,lodigit+1))))
throw "intValueExact(): Decimal part non-zero: " + ();
if (lodigit<0)
return 0; // -1<this<1
useexp=0;
}
else
{/* >=0 */
if ((+lodigit)>9) // early exit
throw "intValueExact(): Conversion overflow: "+();
useexp=;
}
/* convert the mantissa to binary, inline for speed */
result=0;
{var $16=lodigit+useexp;i=0;i:for(;i<=$16;i++){
result=result*10;
if (i<=lodigit)
result=result+[i];
}
}/*i*/
/* Now, if the risky length, check for overflow */
if ((lodigit+useexp)==9)
{
// note we cannot just test for -ve result, as overflow can move a
// zero into the top bit [consider 5555555555]
topdig=div(result,1000000000); // get top digit, preserving sign
if (topdig!=[0])
{ // digit must match and be positive
// except in the special case ...
if (result==-2147483648) // looks like the special
if (==) // really was negative
if ([0]==2)
return result; // really had top digit 2
throw "intValueExact(): Conversion overflow: "+();
}
}
/* Looks good */
if (==)
return result;
return -result;
}
/**
* Converts this <code>BigDecimal</code> to a <code>long</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part it is
* discarded. If the <code>BigDecimal</code> is out of the possible
* range for a <code>long</code> (64-bit signed integer) result then
* only the low-order 64 bits are used. (That is, the number may be
* <i>decapitated</i>.) To avoid unexpected errors when these
* conditions occur, use the {@link #longValueExact} method.
*
* @return A <code>long</code> converted from <code>this</code>,
* truncated and decapitated if necessary.
* @stable ICU 2.0
*/
//--public long longValue(){
//-- return toBigInteger().longValue();
//-- }
/**
* Converts this <code>BigDecimal</code> to a <code>long</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part or is
* out of the possible range for a <code>long</code> (64-bit signed
* integer) result then an <code>ArithmeticException</code> is thrown.
*
* @return A <code>long</code> equal in value to <code>this</code>.
* @throws ArithmeticException if <code>this</code> has a non-zero
* decimal part, or will not fit in a
* <code>long</code>.
* @stable ICU 2.0
*/
//--public long longValueExact(){
//-- int lodigit;
//-- int cstart=0;
//-- int useexp=0;
//-- long result;
//-- int i=0;
//-- long topdig=0;
//-- // Identical to intValueExact except for result=long, and exp>=20 test
//-- if (ind==0)
//-- return 0; // easy, and quite common
//-- lodigit=-1; // last included digit
//-- if (exp<0)
//-- {
//-- lodigit=lodigit+exp; // -(-exp)
//-- /* all decimal places must be 0 */
//-- if (lodigit<0)
//-- cstart=0;
//-- else
//-- cstart=lodigit+1;
//-- if ((!(allzero(mant,cstart))))
//-- throw new ("Decimal part non-zero:"+" "+());
//-- if (lodigit<0)
//-- return 0; // -1<this<1
//-- useexp=0;
//-- }
//-- else
//-- {/* >=0 */
//-- if ((exp+)>18) // early exit
//-- throw new ("Conversion overflow:"+" "+());
//-- useexp=exp;
//-- }
//--
//-- /* convert the mantissa to binary, inline for speed */
//-- // note that we could safely use the 'test for wrap to negative'
//-- // algorithm here, but instead we parallel the intValueExact
//-- // algorithm for ease of checking and maintenance.
//-- result=(long)0;
//-- {int $17=lodigit+useexp;i=0;i:for(;i<=$17;i++){
//-- result=result*10;
//-- if (i<=lodigit)
//-- result=result+mant[i];
//-- }
//-- }/*i*/
//--
//-- /* Now, if the risky length, check for overflow */
//-- if ((lodigit+useexp)==18)
//-- {
//-- topdig=result/1000000000000000000L; // get top digit, preserving sign
//-- if (topdig!=mant[0])
//-- { // digit must match and be positive
//-- // except in the special case ...
//-- if (result==.MIN_VALUE) // looks like the special
//-- if (ind==isneg) // really was negative
//-- if (mant[0]==9)
//-- return result; // really had top digit 9
//-- throw new ("Conversion overflow:"+" "+());
//-- }
//-- }
//--
//-- /* Looks good */
//-- if (ind==ispos)
//-- return result;
//-- return (long)-result;
//-- }
/**
* Returns a plain <code>BigDecimal</code> whose decimal point has
* been moved to the left by a specified number of positions.
* The parameter, <code>n</code>, specifies the number of positions to
* move the decimal point.
* That is, if <code>n</code> is 0 or positive, the number returned is
* given by:
* <p><code>
* ((new BigDecimal(-n)))
* </code>
* <p>
* <code>n</code> may be negative, in which case the method returns
* the same result as <code>movePointRight(-n)</code>.
*
* @param n The <code>int</code> specifying the number of places to
* move the decimal point leftwards.
* @return A <code>BigDecimal</code> derived from
* <code>this</code>, with the decimal point moved
* <code>n</code> places to the left.
* @stable ICU 2.0
*/
//--public movePointLeft(int n){
function movePointLeft(n) {
//-- res;
var res;
// very little point in optimizing for shift of 0
res=(this);
=-n;
return (,false); // finish sets form and checks exponent
}
/**
* Returns a plain <code>BigDecimal</code> whose decimal point has
* been moved to the right by a specified number of positions.
* The parameter, <code>n</code>, specifies the number of positions to
* move the decimal point.
* That is, if <code>n</code> is 0 or positive, the number returned is
* given by:
* <p><code>
* ((new BigDecimal(n)))
* </code>
* <p>
* <code>n</code> may be negative, in which case the method returns
* the same result as <code>movePointLeft(-n)</code>.
*
* @param n The <code>int</code> specifying the number of places to
* move the decimal point rightwards.
* @return A <code>BigDecimal</code> derived from
* <code>this</code>, with the decimal point moved
* <code>n</code> places to the right.
* @stable ICU 2.0
*/
//--public movePointRight(int n){
function movePointRight(n) {
//-- res;
var res;
res=(this);
=+n;
return (,false);
}
/**
* Returns the scale of this <code>BigDecimal</code>.
* Returns a non-negative <code>int</code> which is the scale of the
* number. The scale is the number of digits in the decimal part of
* the number if the number were formatted without exponential
* notation.
*
* @return An <code>int</code> whose value is the scale of this
* <code>BigDecimal</code>.
* @stable ICU 2.0
*/
//--public int scale(){
function scale() {
if (>=0)
return 0; // scale can never be negative
return -;
}
/**
* Returns a plain <code>BigDecimal</code> with a given scale.
* <p>
* If the given scale (which must be zero or positive) is the same as
* or greater than the length of the decimal part (the scale) of this
* <code>BigDecimal</code> then trailing zeros will be added to the
* decimal part as necessary.
* <p>
* If the given scale is less than the length of the decimal part (the
* scale) of this <code>BigDecimal</code> then trailing digits
* will be removed, and in this case an
* <code>ArithmeticException</code> is thrown if any discarded digits
* are non-zero.
* <p>
* The same as {@link #setScale(int, int)}, where the first parameter
* is the scale, and the second is
* <code>MathContext.ROUND_UNNECESSARY</code>.
*
* @param scale The <code>int</code> specifying the scale of the
* resulting <code>BigDecimal</code>.
* @return A plain <code>BigDecimal</code> with the given scale.
* @throws ArithmeticException if <code>scale</code> is negative.
* @throws ArithmeticException if reducing scale would discard
* non-zero digits.
* @stable ICU 2.0
*/
//--public setScale(int scale){
//-- return setScale(scale,ROUND_UNNECESSARY);
//-- }
/**
* Returns a plain <code>BigDecimal</code> with a given scale.
* <p>
* If the given scale (which must be zero or positive) is the same as
* or greater than the length of the decimal part (the scale) of this
* <code>BigDecimal</code> then trailing zeros will be added to the
* decimal part as necessary.
* <p>
* If the given scale is less than the length of the decimal part (the
* scale) of this <code>BigDecimal</code> then trailing digits
* will be removed, and the rounding mode given by the second
* parameter is used to determine if the remaining digits are
* affected by a carry.
* In this case, an <code>IllegalArgumentException</code> is thrown if
* <code>round</code> is not a valid rounding mode.
* <p>
* If <code>round</code> is <code>MathContext.ROUND_UNNECESSARY</code>,
* an <code>ArithmeticException</code> is thrown if any discarded
* digits are non-zero.
*
* @param scale The <code>int</code> specifying the scale of the
* resulting <code>BigDecimal</code>.
* @param round The <code>int</code> rounding mode to be used for
* the division (see the {@link MathContext} class).
* @return A plain <code>BigDecimal</code> with the given scale.
* @throws IllegalArgumentException if <code>round</code> is not a
* valid rounding mode.
* @throws ArithmeticException if <code>scale</code> is negative.
* @throws ArithmeticException if <code>round</code> is
* <code>MathContext.ROUND_UNNECESSARY</code>, and
* reducing scale would discard non-zero digits.
* @stable ICU 2.0
*/
//--public setScale(int scale,int round){
function setScale() {
var round;
if ( == 2)
{
round = [1];
}
else if ( == 1)
{
round = this.ROUND_UNNECESSARY;
}
else
{
throw "setScale(): " + + " given; expected 1 or 2";
}
var scale = [0];
//--int ourscale;
var ourscale;
//-- res;
var res;
//--int padding=0;
var padding=0;
//--int newlen=0;
var newlen=0;
// at present this naughtily only checks the round value if it is
// needed (used), for speed
ourscale=();
if (ourscale==scale) // already correct scale
if (==) // .. and form
return this;
res=(this); // need copy
if (ourscale<=scale)
{ // simply zero-padding/changing form
// if ourscale is 0 we may have lots of 0s to add
if (ourscale==0)
padding=+scale;
else
padding=scale-ourscale;
=(,+padding);
=-scale; // as requested
}
else
{/* ourscale>scale: shortening, probably */
if (scale<0)
//--throw new ("Negative scale:"+" "+scale);
throw "setScale(): Negative scale: " + scale;
// [round() will raise exception if invalid round]
newlen=-((ourscale-scale)); // [<=0 is OK]
res=(newlen,round); // round to required length
// This could have shifted left if round (say) 0.9->1[.0]
// Repair if so by adding a zero and reducing exponent
if (!=(-scale))
{
=(,+1);
=-1;
}
}
=; // by definition
return res;
}
/**
* Converts this <code>BigDecimal</code> to a <code>short</code>.
* If the <code>BigDecimal</code> has a non-zero decimal part or is
* out of the possible range for a <code>short</code> (16-bit signed
* integer) result then an <code>ArithmeticException</code> is thrown.
*
* @return A <code>short</code> equal in value to <code>this</code>.
* @throws ArithmeticException if <code>this</code> has a non-zero
* decimal part, or will not fit in a
* <code>short</code>.
* @stable ICU 2.0
*/
//--public short shortValueExact(){
//-- int num;
//-- num=(); // will check decimal part too
//-- if ((num>32767)|(num<(-32768)))
//-- throw new ("Conversion overflow:"+" "+());
//-- return (short)num;
//-- }
/**
* Returns the sign of this <code>BigDecimal</code>, as an
* <code>int</code>.
* This returns the <i>signum</i> function value that represents the
* sign of this <code>BigDecimal</code>.
* That is, -1 if the <code>BigDecimal</code> is negative, 0 if it is
* numerically equal to zero, or 1 if it is positive.
*
* @return An <code>int</code> which is -1 if the
* <code>BigDecimal</code> is negative, 0 if it is
* numerically equal to zero, or 1 if it is positive.
* @stable ICU 2.0
*/
//--public int signum(){
function signum() {
return ; // [note this assumes values for ind.]
}
/**
* Converts this <code>BigDecimal</code> to a
* <code></code>.
* <p>
* This is an exact conversion; the result is the same as if the
* <code>BigDecimal</code> were formatted as a plain number without
* any rounding or exponent and then the
* <code>()</code> constructor
* were used to construct the result.
* <p>
* <i>(Note: this method is provided only in the
* <code></code> version of the BigDecimal class.
* It would not be present in a <code></code> version.)</i>
*
* @return The <code></code> equal in value
* to this <code>BigDecimal</code>.
* @stable ICU 2.0
*/
//--public toBigDecimal(){
//-- return new ((),());
//-- }
/**
* Converts this <code>BigDecimal</code> to a
* <code></code>.
* <p>
* Any decimal part is truncated (discarded).
* If an exception is desired should the decimal part be non-zero,
* use {@link #toBigIntegerExact()}.
*
* @return The <code></code> equal in value
* to the integer part of this <code>BigDecimal</code>.
* @stable ICU 2.0
*/
//--public toBigInteger(){
//-- res=null;
//-- int newlen=0;
//-- byte newmant[]=null;
//-- {/*select*/
//-- if ((exp>=0)&(form==))
//-- res=this; // can layout simply
//-- else if (exp>=0)
//-- {
//-- res=clone(this); // safe copy
//-- =(byte); // .. and request PLAIN
//-- }
//-- else{
//-- { // exp<0; scale to be truncated
//-- // we could use divideInteger, but we may as well be quicker
//-- if (((int)-)>=)
//-- res=ZERO; // all blows away
//-- else
//-- {
//-- res=clone(this); // safe copy
//-- newlen=+;
//-- newmant=new byte[newlen]; // [shorter]
//-- ((),0,()newmant,0,newlen);
//-- =newmant;
//-- =(byte);
//-- =0;
//-- }
//-- }
//-- }
//-- }
//-- return new BigInteger(new (()));
//-- }
/**
* Converts this <code>BigDecimal</code> to a
* <code></code>.
* <p>
* An exception is thrown if the decimal part (if any) is non-zero.
*
* @return The <code></code> equal in value
* to the integer part of this <code>BigDecimal</code>.
* @throws ArithmeticException if <code>this</code> has a non-zero
* decimal part.
* @stable ICU 2.0
*/
//--public toBigIntegerExact(){
//-- /* test any trailing decimal part */
//-- if (exp<0)
//-- { // possible decimal part
//-- /* all decimal places must be 0; note exp<0 */
//-- if ((!(allzero(mant,+exp))))
//-- throw new ("Decimal part non-zero:"+" "+());
//-- }
//-- return toBigInteger();
//-- }
/**
* Returns the <code>BigDecimal</code> as a character array.
* The result of this method is the same as using the
* sequence <code>toString().toCharArray()</code>, but avoids creating
* the intermediate <code>String</code> and <code>char[]</code>
* objects.
*
* @return The <code>char[]</code> array corresponding to this
* <code>BigDecimal</code>.
* @stable ICU 2.0
*/
//--public char[] toCharArray(){
//-- return layout();
//-- }
/**
* Returns the <code>BigDecimal</code> as a <code>String</code>.
* This returns a <code>String</code> that exactly represents this
* <code>BigDecimal</code>, as defined in the decimal documentation
* (see {@link BigDecimal class header}).
* <p>
* By definition, using the {@link #BigDecimal(String)} constructor
* on the result <code>String</code> will create a
* <code>BigDecimal</code> that is exactly equal to the original
* <code>BigDecimal</code>.
*
* @return The <code>String</code> exactly corresponding to this
* <code>BigDecimal</code>.
* @see #format(int, int)
* @see #format(int, int, int, int, int, int)
* @see #toCharArray()
* @stable ICU 2.0
*/
//--public toString(){
function toString() {
return ().join("");
}
/**
* Returns the number as a <code>BigInteger</code> after removing the
* scale.
* That is, the number is expressed as a plain number, any decimal
* point is then removed (retaining the digits of any decimal part),
* and the result is then converted to a <code>BigInteger</code>.
*
* @return The <code></code> equal in value to
* this <code>BigDecimal</code> multiplied by ten to the
* power of <code>()</code>.
* @stable ICU 2.0
*/
//--public unscaledValue(){
//-- res=null;
//-- if (exp>=0)
//-- res=this;
//-- else
//-- {
//-- res=clone(this); // safe copy
//-- =0; // drop scale
//-- }
//-- return ();
//-- }
/**
* Translates a <code>double</code> to a <code>BigDecimal</code>.
* <p>
* Returns a <code>BigDecimal</code> which is the decimal
* representation of the 64-bit signed binary floating point
* parameter. If the parameter is infinite, or is not a number (NaN),
* a <code>NumberFormatException</code> is thrown.
* <p>
* The number is constructed as though <code>num</code> had been
* converted to a <code>String</code> using the
* <code>()</code> method and the
* {@link #BigDecimal()} constructor had then been used.
* This is typically not an exact conversion.
*
* @param dub The <code>double</code> to be translated.
* @return The <code>BigDecimal</code> equal in value to
* <code>dub</code>.
* @throws NumberFormatException if the parameter is infinite or
* not a number.
* @stable ICU 2.0
*/
//--public static valueOf(double dub){
//-- // Reminder: a zero double returns '0.0', so we cannot fastpath to
//-- // use the constant ZERO. This might be important enough to justify
//-- // a factory approach, a cache, or a few private constants, later.
//-- return new ((new (dub)).toString());
//-- }
/**
* Translates a <code>long</code> to a <code>BigDecimal</code>.
* That is, returns a plain <code>BigDecimal</code> whose value is
* equal to the given <code>long</code>.
*
* @param lint The <code>long</code> to be translated.
* @return The <code>BigDecimal</code> equal in value to
* <code>lint</code>.
* @stable ICU 2.0
*/
//--public static valueOf(long lint){
//-- return valueOf(lint,0);
//-- }
/**
* Translates a <code>long</code> to a <code>BigDecimal</code> with a
* given scale.
* That is, returns a plain <code>BigDecimal</code> whose unscaled
* value is equal to the given <code>long</code>, adjusted by the
* second parameter, <code>scale</code>.
* <p>
* The result is given by:
* <p><code>
* (new BigDecimal(lint)).divide((new BigDecimal(scale)))
* </code>
* <p>
* A <code>NumberFormatException</code> is thrown if <code>scale</code>
* is negative.
*
* @param lint The <code>long</code> to be translated.
* @param scale The <code>int</code> scale to be applied.
* @return The <code>BigDecimal</code> equal in value to
* <code>lint</code>.
* @throws NumberFormatException if the scale is negative.
* @stable ICU 2.0
*/
//--public static valueOf(long lint,int scale){
//-- res=null;
//-- {/*select*/
//-- if (lint==0)
//-- res=ZERO;
//-- else if (lint==1)
//-- res=ONE;
//-- else if (lint==10)
//-- res=TEN;
//-- else{
//-- res=new (lint);
//-- }
//-- }
//-- if (scale==0)
//-- return res;
//-- if (scale<0)
//-- throw new ("Negative scale:"+" "+scale);
//-- res=clone(res); // safe copy [do not mutate]
//-- =(int)-scale; // exponent is -scale
//-- return res;
//-- }
/* ---------------------------------------------------------------- */
/* Private methods */
/* ---------------------------------------------------------------- */
/* <sgml> Return char array value of a BigDecimal (conversion from
BigDecimal to laid-out canonical char array).
<p>The mantissa will either already have been rounded (following an
operation) or will be of length appropriate (in the case of
construction from an int, for example).
<p>We must not alter the mantissa, here.
<p>'form' describes whether we are to use exponential notation (and
if so, which), or if we are to lay out as a plain/pure numeric.
</sgml> */
//--private char[] layout(){
function layout() {
//--char cmant[];
var cmant;
//--int i=0;
var i=0;
//-- sb=null;
var sb=null;
//--int euse=0;
var euse=0;
//--int sig=0;
var sig=0;
//--char csign=0;
var csign=0;
//--char rec[]=null;
var rec=null;
//--int needsign;
var needsign;
//--int mag;
var mag;
//--int len=0;
var len=0;
cmant=new Array(); // copy byte[] to a char[]
{var $18=;i=0;i:for(;$18>0;$18--,i++){
cmant[i]=[i]+'';
}
}/*i*/
if (!=)
{/* exponential notation needed */
//--sb=new (+15); // -+999999999
sb="";
if (==)
sb += '-';
euse=(+)-1; // exponent to use
/* setup sig=significant digits and copy to result */
if (==)
{ // [default]
sb += cmant[0]; // significant character
if (>1) // have decimal part
//--('.').append(cmant,1,-1);
sb += '.';
sb += (1).join("");
}
else
{engineering:do{
sig=euse%3; // common
if (sig<0)
sig=3+sig; // negative exponent
euse=euse-sig;
sig++;
if (sig>=)
{ // zero padding may be needed
//--(cmant,0,);
sb += ("");
{var $19=;for(;$19>0;$19--){
sb += '0';
}
}
}
else
{ // decimal point needed
//--(cmant,0,sig).append('.').append(cmant,sig,-sig);
sb += (0,sig).join("");
sb += '.';
sb += (sig).join("");
}
}while(false);}/*engineering*/
if (euse!=0)
{
if (euse<0)
{
csign='-';
euse=-euse;
}
else
csign='+';
//--('E').append(csign).append(euse);
sb += 'E';
sb += csign;
sb += euse;
}
//--rec=new Array();
//--(sb, 0,(),rec,0);
//--return rec;
return ("");
}
/* Here for non-exponential (plain) notation */
if (==0)
{/* easy */
if (>=0)
return cmant; // non-negative integer
rec=new Array(+1);
rec[0]='-';
//--(()cmant,0,()rec,1,);
(cmant,0,rec,1,);
return rec;
}
/* Need a '.' and/or some zeros */
needsign=((==)?1:0); // space for sign? 0 or 1
/* MAG is the position of the point in the mantissa (index of the
character it follows) */
mag=+;
if (mag<1)
{/* 0.00xxxx form */
len=(needsign+2)-; // needsign+2+(-mag)+
rec=new Array(len);
if (needsign!=0)
rec[0]='-';
rec[needsign]='0';
rec[needsign+1]='.';
{var $20=-mag;i=needsign+2;i:for(;$20>0;$20--,i++){ // maybe none
rec[i]='0';
}
}/*i*/
//--(()cmant,0,()rec,(needsign+2)-mag,);
(cmant,0,rec,(needsign+2)-mag,);
return rec;
}
if (mag>)
{/* xxxx0000 form */
len=needsign+mag;
rec=new Array(len);
if (needsign!=0)
rec[0]='-';
//--(()cmant,0,()rec,needsign,);
(cmant,0,rec,needsign,);
{var $21=;i=needsign+;i:for(;$21>0;$21--,i++){ // never 0
rec[i]='0';
}
}/*i*/
return rec;
}
/* decimal point is in the middle of the mantissa */
len=(needsign+1)+;
rec=new Array(len);
if (needsign!=0)
rec[0]='-';
//--(()cmant,0,()rec,needsign,mag);
(cmant,0,rec,needsign,mag);
rec[needsign+mag]='.';
//--(()cmant,mag,()rec,(needsign+mag)+1,-mag);
(cmant,mag,rec,(needsign+mag)+1,-mag);
return rec;
}
/* <sgml> Checks a BigDecimal argument to ensure it's a true integer
in a given range.
<p>If OK, returns it as an int. </sgml> */
// [currently only used by pow]
//--private int intcheck(int min,int max){
function intcheck(min, max) {
//--int i;
var i;
i=(); // [checks for non-0 decimal part]
// Use same message as though intValueExact failed due to size
if ((i<min)||(i>max))
throw "intcheck(): Conversion overflow: "+i;
return i;
}
/* <sgml> Carry out division operations. </sgml> */
/*
Arg1 is operation code: D=divide, I=integer divide, R=remainder
Arg2 is the rhs.
Arg3 is the context.
Arg4 is explicit scale iff code='D' or 'I' (-1 if none).
Underlying algorithm (complications for Remainder function and
scaled division are omitted for clarity):
Test for x/0 and then 0/x
Exp =Exp1 - Exp2
Exp =Exp +len(var1) -len(var2)
Sign=Sign1 * Sign2
Pad accumulator (Var1) to double-length with 0's (pad1)
Pad Var2 to same length as Var1
B2B=1st two digits of var2, +1 to allow for roundup
have=0
Do until (have=digits+1 OR residue=0)
if exp<0 then if integer divide/residue then leave
this_digit=0
Do forever
compare numbers
if <0 then leave inner_loop
if =0 then (- quick exit without subtract -) do
this_digit=this_digit+1; output this_digit
leave outer_loop; end
Compare lengths of numbers (mantissae):
If same then CA=first_digit_of_Var1
else CA=first_two_digits_of_Var1
mult=ca*10/b2b -- Good and safe guess at divisor
if mult=0 then mult=1
this_digit=this_digit+mult
subtract
end inner_loop
if have\=0 | this_digit\=0 then do
output this_digit
have=have+1; end
var2=var2/10
exp=exp-1
end outer_loop
exp=exp+1 -- set the proper exponent
if have=0 then generate answer=0
Return to FINISHED
Result defined by MATHV1
For extended commentary, see DMSRCN.
*/
//--private dodivide(char code, rhs, set,int scale){
function dodivide(code, rhs, set, scale) {
//-- lhs;
var lhs;
//--int reqdig;
var reqdig;
//--int newexp;
var newexp;
//-- res;
var res;
//--int newlen;
var newlen;
//--byte var1[];
var var1;
//--int var1len;
var var1len;
//--byte var2[];
var var2;
//--int var2len;
var var2len;
//--int b2b;
var b2b;
//--int have;
var have;
//--int thisdigit=0;
var thisdigit=0;
//--int i=0;
var i=0;
//--byte v2=0;
var v2=0;
//--int ba=0;
var ba=0;
//--int mult=0;
var mult=0;
//--int start=0;
var start=0;
//--int padding=0;
var padding=0;
//--int d=0;
var d=0;
//--byte newvar1[]=null;
var newvar1=null;
//--byte lasthave=0;
var lasthave=0;
//--int actdig=0;
var actdig=0;
//--byte newmant[]=null;
var newmant=null;
if ()
(rhs,);
lhs=this; // name for clarity
// [note we must have checked lostDigits before the following checks]
if (==0)
throw "dodivide(): Divide by 0"; // includes 0/0
if (==0)
{ // 0/x => 0 [possibly with .0s]
if (!=)
return ;
if (scale==(-1))
return lhs;
return (scale);
}
/* Prepare numbers according to BigDecimal rules */
reqdig=; // local copy (heavily used)
if (reqdig>0)
{
if (>reqdig)
lhs=(lhs).round(set);
if (>reqdig)
rhs=(rhs).round(set);
}
else
{/* scaled divide */
if (scale==(-1))
scale=();
// set reqdig to be at least large enough for the computation
reqdig=; // base length
// next line handles both positive and also scale mismatch
if (scale!=(-))
reqdig=(reqdig+scale)+;
reqdig=(reqdig-((-1)))-; // reduce by RHS effect
if (reqdig<)
reqdig=; // clamp
if (reqdig<)
reqdig=; // ..
}
/* precalculate exponent */
newexp=(()+)-;
/* If new exponent -ve, then some quick exits are possible */
if (newexp<0)
if (code!='D')
{
if (code=='I')
return ; // easy - no integer part
/* Must be 'R'; remainder is [finished clone of] input value */
return (lhs).finish(set,false);
}
/* We need slow division */
res=new BigDecimal(); // where we'll build result
=(*); // final sign (for D/I)
=newexp; // initial exponent (for D/I)
=(reqdig+1); // where build the result
/* Now [virtually pad the mantissae with trailing zeros */
// Also copy the LHS, which will be our working array
newlen=(reqdig+reqdig)+1;
var1=(,newlen); // always makes longer, so new safe array
var1len=newlen; // [remaining digits are 0]
var2=;
var2len=newlen;
/* Calculate first two digits of rhs (var2), +1 for later estimations */
b2b=(var2[0]*10)+1;
if (>1)
b2b=b2b+var2[1];
/* start the long-division loops */
have=0;
{outer:for(;;){
thisdigit=0;
/* find the next digit */
{inner:for(;;){
if (var1len<var2len)
break inner; // V1 too low
if (var1len==var2len)
{ // compare needed
{compare:do{ // comparison
{var $22=var1len;i=0;i:for(;$22>0;$22--,i++){
// var1len is always <=
if (i<)
v2=var2[i];
else
v2=0;
if (var1[i]<v2)
break inner; // V1 too low
if (var1[i]>v2)
break compare; // OK to subtract
}
}/*i*/
/* reach here if lhs and rhs are identical; subtraction will
increase digit by one, and the residue will be 0 so we
are done; leave the loop with residue set to 0 (in case
code is 'R' or ROUND_UNNECESSARY or a ROUND_HALF_xxxx is
being checked) */
thisdigit++;
[have]=thisdigit;
have++;
var1[0]=0; // residue to 0 [this is all we'll test]
// var1len=1 -- [optimized out]
break outer;
}while(false);}/*compare*/
/* prepare for subtraction. Estimate BA (lengths the same) */
ba=var1[0]; // use only first digit
} // lengths the same
else
{/* lhs longer than rhs */
/* use first two digits for estimate */
ba=var1[0]*10;
if (var1len>1)
ba=ba+var1[1];
}
/* subtraction needed; V1>=V2 */
mult=div((ba*10),b2b);
if (mult==0)
mult=1;
thisdigit=thisdigit+mult;
// subtract; var1 reusable
var1=(var1,var1len,var2,var2len,-mult,true);
if (var1[0]!=0)
continue inner; // maybe another subtract needed
/* V1 now probably has leading zeros, remove leading 0's and try
again. (It could be longer than V2) */
{var $23=var1len-2;start=0;start:for(;start<=$23;start++){
if (var1[start]!=0)
break start;
var1len--;
}
}/*start*/
if (start==0)
continue inner;
// shift left
//--(()var1,start,()var1,0,var1len);
(var1,start,var1,0,var1len);
}
}/*inner*/
/* We have the next digit */
if ((have!=0)||(thisdigit!=0))
{ // put the digit we got
[have]=thisdigit;
have++;
if (have==(reqdig+1))
break outer; // we have all we need
if (var1[0]==0)
break outer; // residue now 0
}
/* can leave now if a scaled divide and exponent is small enough */
if (scale>=0)
if ((-)>scale)
break outer;
/* can leave now if not Divide and no integer part left */
if (code!='D')
if (<=0)
break outer;
=-1; // reduce the exponent
/* to get here, V1 is less than V2, so divide V2 by 10 and go for
the next digit */
var2len--;
}
}/*outer*/
/* here when we have finished dividing, for some reason */
// have is the number of digits we collected in
if (have==0)
have=1; // [0] is 0; we always want a digit
if ((code=='I')||(code=='R'))
{/* check for integer overflow needed */
if ((have+)>reqdig)
throw "dodivide(): Integer overflow";
if (code=='R')
{remainder:do{
/* We were doing Remainder -- return the residue */
if ([0]==0) // no integer part was found
return (lhs).finish(set,false); // .. so return lhs, canonical
if (var1[0]==0)
return ; // simple 0 residue
=; // sign is always as LHS
/* Calculate the exponent by subtracting the number of padding zeros
we added and adding the original exponent */
padding=((reqdig+reqdig)+1)-;
=(-padding)+;
/* strip insignificant padding zeros from residue, and create/copy
the resulting mantissa if need be */
d=var1len;
{i=d-1;i:for(;i>=1;i--){if(!((<)&&(<)))break;
if (var1[i]!=0)
break i;
d--;
=+1;
}
}/*i*/
if (d<)
{/* need to reduce */
newvar1=new Array(d);
//--(()var1,0,()newvar1,0,d); // shorten
(var1,0,newvar1,0,d);
var1=newvar1;
}
=var1;
return (set,false);
}while(false);}/*remainder*/
}
else
{/* 'D' -- no overflow check needed */
// If there was a residue then bump the final digit (iff 0 or 5)
// so that the residue is visible for ROUND_UP, ROUND_HALF_xxx and
// ROUND_UNNECESSARY checks (etc.) later.
// [if we finished early, the residue will be 0]
if (var1[0]!=0)
{ // residue not 0
lasthave=[have-1];
if (((lasthave%5))==0)
[have-1]=(lasthave+1);
}
}
/* Here for Divide or Integer Divide */
// handle scaled results first ['I' always scale 0, optional for 'D']
if (scale>=0)
{scaled:do{
// say 'scale have len' scale have
if (have!=)
// already padded with 0's, so just adjust exponent
=-((-have));
// calculate number of digits we really want [may be 0]
actdig=-(((-)-scale));
(actdig,); // round to desired length
// This could have shifted left if round (say) 0.9->1[.0]
// Repair if so by adding a zero and reducing exponent
if (!=(-scale))
{
=(,+1);
=-1;
}
return (set,true); // [strip if not PLAIN]
}while(false);}/*scaled*/
// reach here only if a non-scaled
if (have==)
{ // got digits+1 digits
(set);
have=reqdig;
}
else
{/* have<=reqdig */
if ([0]==0)
return ; // fastpath
// make the mantissa truly just 'have' long
// [we could let finish do this, during strip, if we adjusted
// the exponent; however, truncation avoids the strip loop]
newmant=new Array(have); // shorten
//--((),0,()newmant,0,have);
(,0,newmant,0,have);
=newmant;
}
return (set,true);
}
/* <sgml> Report a conversion exception. </sgml> */
//--private void bad(char s[]){
function bad(prefix, s) {
throw prefix + "Not a number: "+s;
}
/* <sgml> Report a bad argument to a method. </sgml>
Arg1 is method name
Arg2 is argument position
Arg3 is what was found */
//--private void badarg( name,int pos, value){
function badarg(name, pos, value) {
throw "Bad argument "+pos+" to "+name+": "+value;
}
/* <sgml> Extend byte array to given length, padding with 0s. If no
extension is required then return the same array. </sgml>
Arg1 is the source byte array
Arg2 is the new length (longer)
*/
//--private static final byte[] extend(byte inarr[],int newlen){
function extend(inarr, newlen) {
//--byte newarr[];
var newarr;
if (==newlen)
return inarr;
newarr=createArrayWithZeros(newlen);
//--(()inarr,0,()newarr,0,);
(inarr,0,newarr,0,);
// 0 padding is carried out by the JVM on allocation initialization
return newarr;
}
/* <sgml> Add or subtract two >=0 integers in byte arrays
<p>This routine performs the calculation:
<pre>
C=A+(B*M)
</pre>
Where M is in the range -9 through +9
<p>
If M<0 then A>=B must be true, so the result is always
non-negative.
Leading zeros are not removed after a subtraction. The result is
either the same length as the longer of A and B, or 1 longer than
that (if a carry occurred).
A is not altered unless Arg6 is 1.
B is never altered.
Arg1 is A
Arg2 is A length to use (if longer than A, pad with 0's)
Arg3 is B
Arg4 is B length to use (if longer than B, pad with 0's)
Arg5 is M, the multiplier
Arg6 is 1 if A can be used to build the result (if it fits)
This routine is severely performance-critical; *any* change here
must be measured (timed) to assure no performance degradation.
*/
// 1996.02.20 -- enhanced version of DMSRCN algorithm (1981)
// 1997.10.05 -- changed to byte arrays (from char arrays)
// 1998.07.01 -- changed to allow destructive reuse of LHS
// 1998.07.01 -- changed to allow virtual lengths for the arrays
// 1998.12.29 -- use lookaside for digit/carry calculation
// 1999.08.07 -- avoid multiply when mult=1, and make db an int
// 1999.12.22 -- special case m=-1, also drop 0 special case
//--private static final byte[] byteaddsub(byte a[],int avlen,byte b[],int bvlen,int m,boolean reuse){
function byteaddsub(a, avlen, b, bvlen, m, reuse) {
//--int alength;
var alength;
//--int blength;
var blength;
//--int ap;
var ap;
//--int bp;
var bp;
//--int maxarr;
var maxarr;
//--byte reb[];
var reb;
//--boolean quickm;
var quickm;
//--int digit;
var digit;
//--int op=0;
var op=0;
//--int dp90=0;
var dp90=0;
//--byte newarr[];
var newarr;
//--int i=0;
var i=0;
// We'll usually be right if we assume no carry
alength=; // physical lengths
blength=; // ..
ap=avlen-1; // -> final (rightmost) digit
bp=bvlen-1; // ..
maxarr=bp;
if (maxarr<ap)
maxarr=ap;
reb=null; // result byte array
if (reuse)
if ((maxarr+1)==alength)
reb=a; // OK to reuse A
if (reb==null){
reb=(maxarr+1); // need new array
}
quickm=false; // 1 if no multiply needed
if (m==1)
quickm=true; // most common
else
if (m==(-1))
quickm=true; // also common
digit=0; // digit, with carry or borrow
{op=maxarr;op:for(;op>=0;op--){
if (ap>=0)
{
if (ap<alength)
digit=digit+a[ap]; // within A
ap--;
}
if (bp>=0)
{
if (bp<blength)
{ // within B
if (quickm)
{
if (m>0)
digit=digit+b[bp]; // most common
else
digit=digit-b[bp]; // also common
}
else
digit=digit+(b[bp]*m);
}
bp--;
}
/* result so far (digit) could be -90 through 99 */
if (digit<10)
if (digit>=0)
{quick:do{ // 0-9
reb[op]=digit;
digit=0; // no carry
continue op;
}while(false);}/*quick*/
dp90=digit+90;
reb[op]=[dp90]; // this digit
digit=[dp90]; // carry or borrow
}
}/*op*/
if (digit==0)
return reb; // no carry
// following line will become an Assert, later
// if digit<0 then signal ArithmeticException(" ["digit"]")
/* We have carry -- need to make space for the extra digit */
newarr=null;
if (reuse)
if ((maxarr+2)==)
newarr=a; // OK to reuse A
if (newarr==null)
newarr=new Array(maxarr+2);
newarr[0]=digit; // the carried digit ..
// .. and all the rest [use local loop for short numbers]
//--if (maxarr<10)
{var $24=maxarr+1;i=0;i:for(;$24>0;$24--,i++){
newarr[i+1]=reb[i];
}
}/*i*/
//--else
//--(()reb,0,()newarr,1,maxarr+1);
return newarr;
}
/* <sgml> Initializer for digit array properties (lookaside). </sgml>
Returns the digit array, and initializes the carry array. */
//--private static final byte[] diginit(){
function diginit() {
//--byte work[];
var work;
//--int op=0;
var op=0;
//--int digit=0;
var digit=0;
work=new Array((90+99)+1);
{op=0;op:for(;op<=(90+99);op++){
digit=op-90;
if (digit>=0)
{
work[op]=(digit%10);
[op]=(div(digit,10)); // calculate carry
continue op;
}
// borrowing...
digit=digit+100; // yes, this is right [consider -50]
work[op]=(digit%10);
[op]=((div(digit,10))-10); // calculate borrow [NB: - after %]
}
}/*op*/
return work;
}
/* <sgml> Create a copy of BigDecimal object for local use.
<p>This does NOT make a copy of the mantissa array.
</sgml>
Arg1 is the BigDecimal to clone (non-null)
*/
//--private static final clone( dec){
function clone(dec) {
//-- copy;
var copy;
copy=new BigDecimal();
=;
=;
=;
=;
return copy;
}
/* <sgml> Check one or two numbers for lost digits. </sgml>
Arg1 is RHS (or null, if none)
Arg2 is current DIGITS setting
returns quietly or throws an exception */
//--private void checkdigits( rhs,int dig){
function checkdigits(rhs, dig) {
if (dig==0)
return; // don't check if digits=0
// first check lhs...
if (>dig)
if ((!((,dig))))
throw "Too many digits: "+();
if (rhs==null)
return; // monadic
if (>dig)
if ((!((,dig))))
throw "Too many digits: "+();
return;
}
/* <sgml> Round to specified digits, if necessary. </sgml>
Arg1 is requested MathContext [with length and rounding mode]
returns this, for convenience */
//--private round( set){
//-- return round(,);
//-- }
/* <sgml> Round to specified digits, if necessary.
Arg1 is requested length (digits to round to)
[may be <=0 when called from format, dodivide, etc.]
Arg2 is rounding mode
returns this, for convenience
ind and exp are adjusted, but not cleared for a mantissa of zero
The length of the mantissa returned will be Arg1, except when Arg1
is 0, in which case the returned mantissa length will be 1.
</sgml>
*/
//private round(int len,int mode){
function round() {
var len;
var mode;
if ( == 2)
{
len = [0];
mode = [1];
}
else if ( == 1)
{
var set = [0];
len = ;
mode = ;
}
else
{
throw "round(): " + + " arguments given; expected 1 or 2";
}
//int adjust;
var adjust;
//int sign;
var sign;
//byte oldmant[];
var oldmant;
//boolean reuse=false;
var reuse=false;
//--byte first=0;
var first=0;
//--int increment;
var increment;
//--byte newmant[]=null;
var newmant=null;
adjust=-len;
if (adjust<=0)
return this; // nowt to do
=+adjust; // exponent of result
sign=; // save [assumes -1, 0, 1]
oldmant=; // save
if (len>0)
{
// remove the unwanted digits
=new Array(len);
//--(()oldmant,0,()mant,0,len);
(oldmant,0,,0,len);
reuse=true; // can reuse mantissa
first=oldmant[len]; // first of discarded digits
}
else
{/* len<=0 */
=;
=;
reuse=false; // cannot reuse mantissa
if (len==0)
first=oldmant[0];
else
first=0; // [virtual digit]
}
// decide rounding adjustment depending on mode, sign, and discarded digits
increment=0; // bumper
{modes:do{/*select*/
if (mode==this.ROUND_HALF_UP)
{ // default first [most common]
if (first>=5)
increment=sign;
}
else if (mode==this.ROUND_UNNECESSARY)
{ // default for setScale()
// discarding any non-zero digits is an error
if ((!((oldmant,len))))
throw "round(): Rounding necessary";
}
else if (mode==this.ROUND_HALF_DOWN)
{ // 0.5000 goes down
if (first>5)
increment=sign;
else
if (first==5)
if ((!((oldmant,len+1))))
increment=sign;
}
else if (mode==this.ROUND_HALF_EVEN)
{ // 0.5000 goes down if left digit even
if (first>5)
increment=sign;
else
if (first==5)
{
if ((!((oldmant,len+1))))
increment=sign;
else /* 0.5000 */
if (((([-1])%2))==1)
increment=sign;
}
}
else if (mode==this.ROUND_DOWN)
{} // never increment
else if (mode==this.ROUND_UP)
{ // increment if discarded non-zero
if ((!((oldmant,len))))
increment=sign;
}
else if (mode==this.ROUND_CEILING)
{ // more positive
if (sign>0)
if ((!((oldmant,len))))
increment=sign;
}
else if (mode==this.ROUND_FLOOR)
{ // more negative
if (sign<0)
if ((!((oldmant,len))))
increment=sign;
}
else{
throw "round(): Bad round value: "+mode;
}
}while(false);}/*modes*/
if (increment!=0)
{bump:do{
if (==)
{
// we must not subtract from 0, but result is trivial anyway
=;
=increment;
}
else
{
// mantissa is non-0; we can safely add or subtract 1
if (==)
increment=-increment;
newmant=(,,,1,increment,reuse);
if (>)
{ // had a carry
// drop rightmost digit and raise exponent
++;
// mant is already the correct length
//(()newmant,0,()mant,0,);
(newmant,0,,0,);
}
else
=newmant;
}
}while(false);}/*bump*/
// rounding can increase exponent significantly
if (>)
throw "round(): Exponent Overflow: "+;
return this;
}
/* <sgml> Test if rightmost digits are all 0.
Arg1 is a mantissa array to test
Arg2 is the offset of first digit to check
[may be negative; if so, digits to left are 0's]
returns 1 if all the digits starting at Arg2 are 0
Arg2 may be beyond array bounds, in which case 1 is returned
</sgml> */
//--private static final boolean allzero(byte array[],int start){
function allzero(array, start) {
//--int i=0;
var i=0;
if (start<0)
start=0;
{var $25=-1;i=start;i:for(;i<=$25;i++){
if (array[i]!=0)
return false;
}
}/*i*/
return true;
}
/* <sgml> Carry out final checks and canonicalization
<p>
This finishes off the current number by:
1. Rounding if necessary (NB: length includes leading zeros)
2. Stripping trailing zeros (if requested and \PLAIN)
3. Stripping leading zeros (always)
4. Selecting exponential notation (if required)
5. Converting a zero result to just '0' (if \PLAIN)
In practice, these operations overlap and share code.
It always sets form.
</sgml>
Arg1 is requested MathContext (length to round to, trigger, and FORM)
Arg2 is 1 if trailing insignificant zeros should be removed after
round (for division, etc.), provided that isn't PLAIN.
returns this, for convenience
*/
//--private finish( set,boolean strip){
function finish(set, strip) {
//--int d=0;
var d=0;
//--int i=0;
var i=0;
//--byte newmant[]=null;
var newmant=null;
//--int mag=0;
var mag=0;
//--int sig=0;
var sig=0;
/* Round if mantissa too long and digits requested */
if (!=0)
if (>)
(set);
/* If strip requested (and standard formatting), remove
insignificant trailing zeros. */
if (strip)
if (!=)
{
d=;
/* see if we need to drop any trailing zeros */
{i=d-1;i:for(;i>=1;i--){
if ([i]!=0)
break i;
d--;
++;
}
}/*i*/
if (d<)
{/* need to reduce */
newmant=new Array(d);
//--((),0,()newmant,0,d);
(,0,newmant,0,d);
=newmant;
}
}
=; // preset
/* Now check for leading- and all- zeros in mantissa */
{var $26=;i=0;i:for(;$26>0;$26--,i++){
if ([i]!=0)
{
// non-0 result; ind will be correct
// remove leading zeros [., after subtract]
if (i>0)
{delead:do{
newmant=new Array(-i);
//--((),i,()newmant,0,-i);
(,i,newmant,0,-i);
=newmant;
}while(false);}/*delead*/
// now determine form if not PLAIN
mag=+;
if (mag>0)
{ // most common path
if (mag>)
if (!=0)
=;
if ((mag-1)<=)
return this; // no overflow; quick return
}
else
if (mag<(-5))
=;
/* check for overflow */
mag--;
if ((mag<)||(mag>))
{overflow:do{
// possible reprieve if form is engineering
if (==)
{
sig=mag%3; // leftover
if (sig<0)
sig=3+sig; // negative exponent
mag=mag-sig; // exponent to use
// 1999.06.29: second test here must be MaxExp
if (mag>=)
if (mag<=)
break overflow;
}
throw "finish(): Exponent Overflow: "+mag;
}while(false);}/*overflow*/
return this;
}
}
}/*i*/
// Drop through to here only if mantissa is all zeros
=;
{/*select*/
if (!=)
=0; // standard result; go to '0'
else if (>0)
=0; // +ve exponent also goes to '0'
else{
// a plain number with -ve exponent; preserve and check exponent
if (<)
throw "finish(): Exponent Overflow: "+;
}
}
=; // canonical mantissa
return this;
}
function isGreaterThan(other) {
return (other) > 0;
};
function isLessThan(other) {
return (other) < 0;
};
function isGreaterThanOrEqualTo(other) {
return (other) >= 0;
};
function isLessThanOrEqualTo(other) {
return (other) <= 0;
};
function isPositive() {
return () > 0;
};
function isNegative() {
return () < 0;
};
function isZero() {
return () === 0;
};
return BigDecimal;
})(MathContext); // BigDecimal depends on MathContext
if (typeof define === "function" && != null) {
// AMD-loader compatible resource declaration
// require('bigdecimal') will return JS Object:
// {'BigDecimal':BigDecimalPointer, 'MathContext':MathContextPointer}
define({'BigDecimal':BigDecimal, 'MathContext':MathContext});
} else if (typeof this === "object"){
// global-polluting outcome.
= BigDecimal;
= MathContext;
}
}).call(this); // in browser 'this' will be 'window' or simulated window object in AMD-loading scenarios.
再来一份min版本的:
/*
Copyright (c) 2012 Daniel Trebbien and other contributors
Portions Copyright (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany
Portions Copyright (c) 1995-2001 International Business Machines Corporation and others
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
*/
(function(){var y=function(){function h(){==0;=!1;=0;var v=this.DEFAULT_FORM,r=this.DEFAULT_LOSTDIGITS,f=this.DEFAULT_ROUNDINGMODE;if(4==)v=[1],r=[2],f=[3];else if(3==)v=[1],r=[2];else if(2==)v=[1];else if(1!=)throw"MathContext(): "++" arguments given; expected 1 to 4";var t=[0];if(t!=
this.DEFAULT_DIGITS){if(t<this.MIN_DIGITS)throw"MathContext(): Digits too small: "+t;if(t>this.MAX_DIGITS)throw"MathContext(): Digits too large: "+t;}if(v!=&&v!=&&v!=)throw"MathContext() Bad form value: "+v;if(!(f))throw"MathContext(): Bad roundingMode value: "+f;=t;=v;=r;=f}=function(){return };=function(){return };=
function(){return };=function(){return };=function(){var h=null,r=0,f=null,h===?"SCIENTIFIC":==?"ENGINEERING":"PLAIN",t=,r=0;a:for(;0<t;t--,r++)if(==[r]){f=[r];break a}return"digits="++" form="+h+" lostDigits="+(?"1":"0")+" roundingMode="+f};=function(h){var r=0,
f=,r=0;for(;0<f;f--,r++)if(h==[r])return!0;return!1};==0;==1;==2;h.ROUND_CEILING=.ROUND_CEILING=2;h.ROUND_DOWN=.ROUND_DOWN=1;h.ROUND_FLOOR=.ROUND_FLOOR=3;h.ROUND_HALF_DOWN=.ROUND_HALF_DOWN=5;h.ROUND_HALF_EVEN=.ROUND_HALF_EVEN=6;h.ROUND_HALF_UP=.ROUND_HALF_UP=4;h.ROUND_UNNECESSARY=.ROUND_UNNECESSARY=7;
h.ROUND_UP=.ROUND_UP=0;.DEFAULT_FORM=;.DEFAULT_DIGITS=9;.DEFAULT_LOSTDIGITS=!1;.DEFAULT_ROUNDINGMODE=.ROUND_HALF_UP;.MIN_DIGITS=0;.MAX_DIGITS=999999999;=[.ROUND_HALF_UP,.ROUND_UNNECESSARY,.ROUND_CEILING,.ROUND_DOWN,.ROUND_FLOOR,.ROUND_HALF_DOWN,.ROUND_HALF_EVEN,.ROUND_UP];=
"ROUND_HALF_UP ROUND_UNNECESSARY ROUND_CEILING ROUND_DOWN ROUND_FLOOR ROUND_HALF_DOWN ROUND_HALF_EVEN ROUND_UP".split(" ");=new h(.DEFAULT_DIGITS,.DEFAULT_FORM,.DEFAULT_LOSTDIGITS,.DEFAULT_ROUNDINGMODE);return h}(),L=function(h){function v(a,b){return(a-a%b)/b}function r(a){var b=Array(a),c;for(c=0;c<a;++c)b[c]=0;return b}function f(){=0;=;=null;=0;if(0!=){var a,b,c;
1==?(a=[0],b=0,c=):(a=[0],b=[1],c=[2]);"string"==typeof a&&(a=(""));var d,e,n,g,k,l=0,m=0;e=!1;var q=m=m=l=0,p=0;g=0;0>=c&&("BigDecimal(): ",a);=;"-"==a[0]?(c--,0==c&&("BigDecimal(): ",a),=,b++):"+"==a[0]&&(c--,0==c&&("BigDecimal(): ",a),b++);e=d=!1;n=0;k=g=-1;q=c;l=b;a:for(;0<q;q--,l++){m=a[l];if("0"<=m&&"9">=m){k=l;n++;continue a}if("."==m){0<=g&&("BigDecimal(): ",
a);g=l-b;continue a}if("e"!=m&&"E"!=m){("0">m||"9"<m)&&("BigDecimal(): ",a);d=!0;k=l;n++;continue a}l-b>c-2&&("BigDecimal(): ",a);e=!1;"-"==a[l+1]?(e=!0,l+=2):l="+"==a[l+1]?l+2:l+1;m=c-(l-b);(0==m||9<m)&&("BigDecimal(): ",a);c=m;m=l;for(;0<c;c--,m++)q=a[m],"0">q&&("BigDecimal(): ",a),"9"<q?("BigDecimal(): ",a):p=q-0,=10*+p;e&&(=-);e=!0;break a}0==n&&("BigDecimal(): ",a);0<=g&&(=+g-n);p=k-1;l=b;a:for(;l<=
p;l++)if(m=a[l],"0"==m)b++,g--,n--;else if("."==m)b++,g--;else break a;=Array(n);m=b;if(d)for(b=n,l=0;0<b;b--,l++)l==g&&m++,q=a[m],"9">=q?[l]=q-0:("BigDecimal(): ",a),m++;else for(b=n,l=0;0<b;b--,l++)l==g&&m++,[l]=a[m]-0,m++;0==[0]?(=,0<&&(=0),e&&(=,=0)):e&&(=,g=+-1,(g<||g>)&&("BigDecimal(): ",a))}}function t(){var a;
if(1==)a=[0];else if(0==)a=;else throw"abs(): "++" arguments given; expected 0 or 1";return ==?(a):(a)}function z(){var a;if(2==)a=[1];else if(1==)a=;else throw"add(): "++" arguments given; expected 1 or 2";var b=[0],c,d,e,n,g,k,l,m=0;d=m=0;var m=null,q=m=0,p=0,r=0,t=0,s=0;&&(b,
);c=this;if(0==&&!=)return (a);if(0==&&!=)return (a);d=;0<d&&(>d&&(c=(c).round(a)),>d&&(b=(b).round(a)));e=new f;n=;g=;k=;l=;if(==)=;else if(>){m=g+;if(m>=l+d+1&&0<d)return =n,=,=,g<d&&(=(,d),-=d-g),(a,!1);=;m>d+1&&0<d&&
(m=m-d-1,l-=m,+=m,m=d+1);m>g&&(g=m)}else{m=l+;if(m>=g+d+1&&0<d)return =k,=,=,l<d&&(=(,d),-=d-l),(a,!1);=;m>d+1&&0<d&&(m=m-d-1,g-=m,+=m,m=d+1);m>l&&(l=m)}===?:;if((==?1:0)==(==?1:0))d=1;else{do{d=-1;do if(!=)if(g<l||==)m=n,n=k,k=m,m=g,g=l,l=m,=-;else if(!(g>l))c:for(q=m=0,p=-1,r=-1;;){if(m<=
p)t=n[m];else{if(q>r){if(!=)return ;break c}t=0}s=q<=r?k[q]:0;if(t!=s){t<s&&(m=n,n=k,k=m,m=g,g=l,l=m,=-);break c}m++;q++}while(0)}while(0)}=(n,g,k,l,d,!1);return (a,!1)}function A(){var a;if(2==)a=[1];else if(1==)a=;else throw"compareTo(): "++" arguments given; expected 1 or 2";var b=[0],c=0,c=0;&&(b,);if(==
&&==){c=;if(c<);if(c>)return ;if(c<=||0==){a=c;c=0;for(;0<a;a--,c++){if([c]<[c]);if([c]>[c])return }return 0}}else{if(<)return-1;if(>)return 1}b=(b);=-;return (b,a).ind}function u(){var a,b=-1;if(2==)a="number"==typeof [1]?new h(0,,!1,[1]):
[1];else if(3==){b=[1];if(0>b)throw"divide(): Negative scale: "+b;a=new h(0,,!1,[2])}else if(1==)a=;else throw"divide(): "++" arguments given; expected between 1 and 3";return ("D",[0],a,b)}function B(){var a;if(2==)a=[1];else if(1==)a=;else throw"divideInteger(): "++" arguments given; expected 1 or 2";
return ("I",[0],a,0)}function C(){var a;if(2==)a=[1];else if(1==)a=;else throw"max(): "++" arguments given; expected 1 or 2";var b=[0];return 0<=(b,a)?(a):(a)}function D(){var a;if(2==)a=[1];else if(1==)a=;else throw"min(): "++" arguments given; expected 1 or 2";var b=[0];
return 0>=(b,a)?(a):(a)}function E(){var a;if(2==)a=[1];else if(1==)a=;else throw"multiply(): "++" arguments given; expected 1 or 2";var b=[0],c,d,e,h=e=null,g,k=0,l,m=0,q=0;&&(b,);c=this;d=0;e=;0<e?(>e&&(c=(c).round(a)),>e&&(b=(b).round(a))):(0<&&(d+=),0<&&(d+=));<
?(e=,h=):(e=,h=);g=+-1;k=9<e[0]*h[0]?g+1:g;l=new f;var k=(k),p=,m=0;for(;0<p;p--,m++)q=e[m],0!=q&&(k=(k,,h,g,q,!0)),g--;=*;=+-d;=0==d?k:(k,+d);return (a,!1)}function J(){var a;if(1==)a=[0];else if(0==)a=;else throw"negate(): "++" arguments given; expected 0 or 1";
var b;&&(null,);b=(this);=-;return (a,!1)}function K(){var a;if(1==)a=[0];else if(0==)a=;else throw"plus(): "++" arguments given; expected 0 or 1";&&(null,);return ==&&==&&(<=||0==)?this:(this).finish(a,!1)}function F(){var a;if(2==)a=
[1];else if(1==)a=;else throw"pow(): "++" arguments given; expected 1 or 2";var b=[0],c,d,e,f=e=0,g,k=0;&&(b,);c=(,);d=this;e=;if(0==e){if(==)throw"pow(): Negative power: "+();e=0}else{if(+>e)throw"pow(): Too many digits: "+();>e&&(d=(d).round(a));f=+;e=e+f+1}e=
new h(e,,!1,);f=;if(0==c)return f;0>c&&(c=-c);g=!1;k=1;a:for(;;k++){c<<=1;0>c&&(g=!0,f=(d,e));if(31==k)break a;if(!g)continue a;f=(f,e)}0>&&(f=(f,e));return (a,!0)}function G(){var a;if(2==)a=[1];else if(1==)a=;else throw"remainder(): "++" arguments given; expected 1 or 2";return ("R",[0],a,-1)}function H(){var a;if(2==)a=
[1];else if(1==)a=;else throw"subtract(): "++" arguments given; expected 1 or 2";var b=[0];&&(b,);b=(b);=-;return (b,a)}function w(){var a,b,c,d;if(6==)a=[2],b=[3],c=[4],d=[5];else if(2==)b=a=-1,c=,d=this.ROUND_HALF_UP;else throw"format(): "++" arguments given; expected 2 or 6";
var e=[0],f=[1],g,k=0,k=k=0,l=null,m=l=k=0;g=0;k=null;m=l=0;(-1>e||0==e)&&("format",1,e);-1>f&&("format",2,f);(-1>a||0==a)&&("format",3,a);-1>b&&("format",4,b);c!=&&c!=&&(-1==c?c=:("format",5,c));if(d!=this.ROUND_HALF_UP)try{-1==d?d=this.ROUND_HALF_UP:new h(9,,!1,d)}catch(q){("format",6,d)}g=(this);-1==b?=:
==?=:(k=+,=k>b?c:-5>k?c:);if(0<=f)a:for(;;){==?k=-:==?k=-1:(k=(+-1)%3,0>k&&(k=3+k),k++,k=k>=?0:-k);if(k==f)break a;if(k<f){l=(,+f-k);=l;-=f-k;if(<)throw"format(): Exponent Overflow: "+;break a}k-=f;if(k>){=;=
;=0;continue a}l=-k;m=;(l,d);if(-m==k)break a}b=();if(0<e){c=;g=0;a:for(;0<c;c--,g++){if("."==b[g])break a;if("E"==b[g])break a}g>e&&("format",1,e);if(g<e){k=Array(+e-g);e-=g;l=0;for(;0<e;e--,l++)k[l]=" ";(b,0,k,l,);b=k}}if(0<a){e=-1;g=-1;a:for(;0<e;e--,g--)if("E"==b[g])break a;if(0==g){k=Array(+a+2);(b,0,k,0,);a+=2;l=;for(;0<a;a--,l++)k[l]=" ";
b=k}else if(m=-g-2,m>a&&("format",3,a),m<a){k=Array(+a-m);(b,0,k,0,g+2);a-=m;l=g+2;for(;0<a;a--,l++)k[l]="0";(b,g+2,k,l,m);b=k}}return ("")}function I(){var a;if(2==)a=[1];else if(1==)a=this.ROUND_UNNECESSARY;else throw"setScale(): "++" given; expected 1 or 2";var b=[0],c,d;c=c=0;c=();if(c==b&&==)return this;d=(this);
if(c<=b)c=0==c?+b:b-c,=(,+c),=-b;else{if(0>b)throw"setScale(): Negative scale: "+b;c=-(c-b);d=(c,a);!=-b&&(=(,+1),-=1)}=;return d}function y(){var a,b=0,c=0;a=Array(190);b=0;a:for(;189>=b;b++){c=b-90;if(0<=c){a[b]=c%10;[b]=v(c,10);continue a}c+=100;a[b]=c%10;[b]=v(c,10)-10}return a}function x(){var a,b;if(2==)a=
[0],b=[1];else if(1==)b=[0],a=,b=;else throw"round(): "++" arguments given; expected 1 or 2";var c,d,e=!1,f=0,g;c=null;c=-a;if(0>=c)return this;+=c;c=;d=;0<a?(=Array(a),(d,0,,0,a),e=!0,f=d[a]):(=,=,e=!1,f=0==a?d[0]:0);g=0;if(b==this.ROUND_HALF_UP)5<=f&&(g=c);else if(b==this.ROUND_UNNECESSARY){if(!(d,
a))throw"round(): Rounding necessary";}else if(b==this.ROUND_HALF_DOWN)5<f?g=c:5==f&&((d,a+1)||(g=c));else if(b==this.ROUND_HALF_EVEN)5<f?g=c:5==f&&((d,a+1)?1==[-1]%2&&(g=c):g=c);else if(b!=this.ROUND_DOWN)if(b==this.ROUND_UP)(d,a)||(g=c);else if(b==this.ROUND_CEILING)0<c&&((d,a)||(g=c));else if(b==this.ROUND_FLOOR)0>c&&((d,a)||(g=c));else throw"round(): Bad round value: "+b;0!=g&&(==?(=
,=g):(==&&(g=-g),c=(,,,1,g,e),>?(++,(c,0,,0,)):=c));if(>)throw"round(): Exponent Overflow: "+;return this}=v;=function(a,b,c,d,e){var f;if(d>b)for(f=e-1;0<=f;--f)c[f+d]=a[f+b];else for(f=0;f<e;++f)c[f+d]=a[f+b]};=r;=t;=
z;=A;=u;=B;=C;=D;=E;=J;=K;=F;=G;=H;=function(a){var b=0,c=null,d=null;if(null==a||!(a instanceof f)||!=)return!1;if(==&&==&&==)for(c=,b=0;0<c;c--,b++){if([b]!=[b])return!1}else{c=
();d=();if(!=)return!1;a=;b=0;for(;0<a;a--,b++)if(c[b]!=d[b])return!1}return!0};=w;=function(){var a,b=0,c,d=0;a=0;if(==)return 0;a=-1;if(0>){a+=;if(!(,a+1))throw"intValueExact(): Decimal part non-zero: "+();if(0>a)return 0;b=0}else{if(9<+a)throw"intValueExact(): Conversion overflow: "+();b=}c=0;var e=
a+b,d=0;for(;d<=e;d++)c*=10,d<=a&&(c+=[d]);if(9==a+b&&(a=v(c,1E9),a!=[0])){if(-2147483648==c&&==&&2==[0])return c;throw"intValueExact(): Conversion overflow: "+();}return ==?c:-c};=function(a){var b;b=(this);-=a;return (,!1)};=function(a){var b;b=(this);+=a;return (,!1)};=function(){return 0<=
?0:-};=I;=function(){return };=function(){return ().join("")};=function(){var a,b=0,b=null,c=0,d=0;a=0;var d=null,e,b=0;a=Array();c=;b=0;for(;0<c;c--,b++)a[b]=[b]+"";if(!=){b="";==&&(b+="-");c=+-1;if(==)b+=a[0],1<&&(b+="."),b+=(1).join("");else if(d=
c%3,0>d&&(d=3+d),c-=d,d++,d>=)for(b+=(""),a=;0<a;a--)b+="0";else b+=(0,d).join(""),b=b+"."+(d).join("");0!=c&&(0>c?(a="-",c=-c):a="+",b+="E",b+=a,b+=c);return ("")}if(0==){if(0<=)return a;d=Array(+1);d[0]="-";(a,0,d,1,);return d}c===?1:0;e=+;if(1>e){b=c+;d=Array(b);0!=c&&(d[0]="-");d[c]="0";d[c+1]=".";var f=-e,b=c+2;for(;0<f;f--,b++)d[b]="0";(a,0,d,c+
2-e,);return d}if(e>){d=Array(c+e);0!=c&&(d[0]="-");(a,0,d,c,);e-=;b=c+;for(;0<e;e--,b++)d[b]="0";return d}b=c+1+;d=Array(b);0!=c&&(d[0]="-");(a,0,d,c,e);d[c+e]=".";(a,e,d,c+e+1,-e);return d};=function(a,b){var c;c=();if(c<a||c>b)throw"intcheck(): Conversion overflow: "+c;return c};=function(a,b,c,d){var e,n,g,k,l,m,q,p,t,r=0,s=0,u=0;n=n=s=s=s=
0;e=null;e=e=0;e=null;&&(b,);e=this;if(0==)throw"dodivide(): Divide by 0";if(0==)return !=?:-1==d?e:(d);n=;0<n?(>n&&(e=(e).round(c)),>n&&(b=(b).round(c))):(-1==d&&(d=()),n=,d!=-&&(n=n+d+),n=n-(-1)-,n<&&(n=),n<&&(n=));g=+;
if(0>g&&"D"!=a)return"I"==a?:(e).finish(c,!1);k=new f;=*;=g;=(n+1);l=n+n+1;g=(,l);m=l;q=;p=l;t=10*q[0]+1;1<&&(t+=q[1]);l=0;a:for(;;){r=0;b:for(;;){if(m<p)break b;if(m==p){c:do{var w=m,s=0;for(;0<w;w--,s++){u=s<?q[s]:0;if(g[s]<u)break b;if(g[s]>u)break c}r++;[l]=r;l++;g[0]=0;break a}while(0);s=g[0]}else s=10*g[0],1<m&&(s+=g[1]);s=v(10*s,t);0==s&&(s=1);r+=s;g=(g,m,q,p,-s,
!0);if(0!=g[0])continue b;u=m-2;s=0;c:for(;s<=u;s++){if(0!=g[s])break c;m--}if(0==s)continue b;(g,s,g,0,m)}if(0!=l||0!=r){[l]=r;l++;if(l==n+1)break a;if(0==g[0])break a}if(0<=d&&->d)break a;if("D"!=a&&0>=)break a;-=1;p--}0==l&&(l=1);if("I"==a||"R"==a){if(l+>n)throw"dodivide(): Integer overflow";if("R"==a){do{if(0==[0])return (e).finish(c,!1);if(0==g[0])return ;=;n=n+n+;=-n+;n=m;s=n-1;b:for(;1<=
s&&<&&<;s--){if(0!=g[s])break b;n--;+=1}n<&&(e=Array(n),(g,0,e,0,n),g=e);=g;return (c,!1)}while(0)}}else 0!=g[0]&&(e=[l-1],0==e%5&&([l-1]=e+1));if(0<=d)return l!=&&(-=-l),e=-(--d),(e,),!=-d&&(=(,+1),-=1),(c,!0);if(l==)(c);else{if(0==[0])return ;e=Array(l);(,
0,e,0,l);=e}return (c,!0)};=function(a,b){throw a+"Not a number: "+b;};=function(a,b,c){throw"Bad argument "+b+" to "+a+": "+c;};=function(a,b){var c;if(==b)return a;c=r(b);(a,0,c,0,);return c};=function(a,b,c,d,e,f){var g,h,l,m,q,p,r=0;g=p=0;g=;h=;b-=1;m=l=d-1;m<b&&(m=b);d=null;f&&m+1==g&&(d=a);null==d&&(d=(m+1));q=!1;1==e?q=!0:-1==e&&(q=!0);
p=0;r=m;a:for(;0<=r;r--){0<=b&&(b<g&&(p+=a[b]),b--);0<=l&&(l<h&&(p=q?0<e?p+c[l]:p-c[l]:p+c[l]*e),l--);if(10>p&&0<=p){do{d[r]=p;p=0;continue a}while(0)}p+=90;d[r]=[p];p=[p]}if(0==p)return d;c=null;f&&m+2==&&(c=a);null==c&&(c=Array(m+2));c[0]=p;a=m+1;g=0;for(;0<a;a--,g++)c[g+1]=d[g];return c};=y;=function(a){var b;b=new f;=;=;=;=;return b};=function(a,b){if(0!=b){if(>
b&&!(,b))throw"Too many digits: "+();if(null!=a&&>b&&!(,b))throw"Too many digits: "+();}};=x;=function(a,b){var c=0;0>b&&(b=0);var d=-1,c=b;for(;c<=d;c++)if(0!=a[c])return!1;return!0};=function(a,b){var c=0,d=0,e=null,c=d=0;0!=&&>&&(a);if(b&&!=){c=;d=c-1;a:for(;1<=d;d--){if(0!=[d])break a;
c--;++}c<&&(e=Array(c),(,0,e,0,c),=e)}=;c=;d=0;for(;0<c;c--,d++)if(0!=[d]){0<d&&(e=Array(-d),(,d,e,0,-d),=e);d=+;if(0<d){if(d>&&0!=&&(=),d-1<=)return this}else-5>d&&(=);d--;if(d<||d>){b:do{if(==&&
(c=d%3,0>c&&(c=3+c),d-=c,d>=&&d<=))break b;throw"finish(): Exponent Overflow: "+d;}while(0)}return this}=;if(!=)=0;else if(0<)=0;else if(<)throw"finish(): Exponent Overflow: "+;=;return this};=function(a){return 0<(a)};=function(a){return 0>(a)};=function(a){return 0<=
(a)};=function(a){return 0>=(a)};=function(){return 0<()};=function(){return 0>()};=function(){return 0===()};f.ROUND_CEILING=.ROUND_CEILING=.ROUND_CEILING;f.ROUND_DOWN=.ROUND_DOWN=.ROUND_DOWN;f.ROUND_FLOOR=.ROUND_FLOOR=.ROUND_FLOOR;
f.ROUND_HALF_DOWN=.ROUND_HALF_DOWN=.ROUND_HALF_DOWN;f.ROUND_HALF_EVEN=.ROUND_HALF_EVEN=.ROUND_HALF_EVEN;f.ROUND_HALF_UP=.ROUND_HALF_UP=.ROUND_HALF_UP;f.ROUND_UNNECESSARY=.ROUND_UNNECESSARY=.ROUND_UNNECESSARY;f.ROUND_UP=.ROUND_UP=.ROUND_UP;=1;=0;=-1;=-999999999;=999999999;=-999999999;=
999999999;=new h(0,);=Array(190);=y();==new f("0");==new f("1");==new f("10");return f}(y);"function"===typeof define&&null!=?define({BigDecimal:L,MathContext:y}):"object"===typeof this&&(=L,=y)}).call(this);