⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bigdecimal.java

📁 《移动Agent技术》一书的所有章节源代码。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    }


    // Rounding Modes

    /**
     * Always increment the digit prior to a non-zero discarded fraction.
     * Note that this rounding mode never decreases the magnitude.
     * (Rounds away from zero.)
     */
    public final static int ROUND_UP = 		 0;

    /**
     * Never increment the digit prior to a discarded fraction (i.e.,
     * truncate).  Note that this rounding mode never increases the magnitude.
     * (Rounds towards zero.)
     */
    public final static int ROUND_DOWN = 	 1;

    /**
     * If the BigDecimal is positive, behave as for ROUND_UP; if negative,
     * behave as for ROUND_DOWN.  Note that this rounding mode never decreases
     * the value.  (Rounds towards positive infinity.)
     */
    public final static int ROUND_CEILING = 	 2;

    /**
     * If the BigDecimal is positive, behave as for ROUND_DOWN; if negative
     * behave as for ROUND_UP.  Note that this rounding mode never increases
     * the value.  (Rounds towards negative infinity.)
     */
    public final static int ROUND_FLOOR = 	 3;

    /**
     * Behave as for ROUND_UP if the discarded fraction is >= .5; otherwise,
     * behave as for ROUND_DOWN.  (Rounds towards "nearest neighbor" unless
     * both neighbors are equidistant, in which case rounds up.)
     */
    public final static int ROUND_HALF_UP = 	 4;

    /**
     * Behave as for ROUND_UP if the discarded fraction is > .5; otherwise,
     * behave as for ROUND_DOWN.   (Rounds towards "nearest neighbor" unless
     * both neighbors are equidistant, in which case rounds down.)
     */
    public final static int ROUND_HALF_DOWN = 	 5;

    /**
     * Behave as for ROUND_HALF_UP if the digit to the left of the discarded
     * fraction is odd; behave as for ROUND_HALF_DOWN if it's even.  (Rounds
     * towards the "nearest neighbor" unless both neighbors are equidistant,
     * in which case, rounds towards the even neighbor.)
     */
    public final static int ROUND_HALF_EVEN = 	 6;

    /**
     * This "pseudo-rounding-mode" is actually an assertion that the requested
     * operation has an exact result, hence no rounding is necessary.  If this
     * rounding mode is specified on an operation that yields an inexact result,
     * an arithmetic exception is thrown.
     */
    public final static int ROUND_UNNECESSARY =  7;


    // Scaling/Rounding Operations

    /**
     * Returns a BigDecimal whose scale is the specified value, and whose
     * integer value is determined by multiplying or dividing this BigDecimal's
     * integer value by the appropriate power of ten to maintain the overall
     * value.  If the scale is reduced by the operation, the integer value
     * must be divided (rather than multiplied), and precision may be lost;
     * in this case, the specified rounding mode is applied to the division.
     * Throws an ArithmeticException if scale is negative, or the rounding
     * mode is ROUND_UNNECESSARY and it is impossible to perform the
     * specified scaling operation without loss of precision.  Throws an
     * IllegalArgumentException if roundingMode does not represent a valid
     * rounding mode.
     */
    public BigDecimal setScale(int scale, int roundingMode)
	throws ArithmeticException, IllegalArgumentException {
	if (scale < 0)
	    throw new ArithmeticException("Negative scale");
	if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
	    throw new IllegalArgumentException("Invalid rounding mode");

	/* Handle the easy cases */
	if (scale == this.scale)
	    return this;
	else if (scale > this.scale)
	    return new BigDecimal(timesTenToThe(intVal, scale-this.scale),
				  scale);
	else /* scale < this.scale */
	    return divide(valueOf(1), scale, roundingMode);
    }

    /**
     * Returns a BigDecimal whose scale is the specified value, and whose
     * value is exactly equal to this number's.  Throws an ArithmeticException
     * if this is not possible.  This call is typically used to increase
     * the scale, in which case it is guaranteed that there exists a BigDecimal
     * of the specified scale and the correct value.  The call can also be used
     * to reduce the scale if the caller knows that the number has sufficiently
     * many zeros at the end of its fractional part (i.e., factors of ten in
     * its integer value) to allow for the rescaling without loss of precision.
     * Note that this call returns the same result as the two argument version
     * of setScale, but saves the caller the trouble of specifying a rounding
     * mode in cases where it is irrelevant.
     */
    public BigDecimal setScale(int scale)
	throws ArithmeticException, IllegalArgumentException
    {
	return setScale(scale, ROUND_UNNECESSARY);
    }


    // Decimal Point Motion Operations

    /**
     * Returns a BigDecimal which is equivalent to this one with the decimal
     * point moved n places to the left.  If n is non-negative, the call merely
     * adds n to the scale.  If n is negative, the call is equivalent to
     * movePointRight(-n).  (The BigDecimal returned by this call has value
     * (this * 10**-n) and scale MAX(this.scale()+n, 0).)
     */
    public BigDecimal movePointLeft(int n){
	return (n>=0 ? new BigDecimal(intVal, scale+n) : movePointRight(-n));
    }

    /**
     * Moves the decimal point the specified number of places to the right.
     * If this number's scale is >= n, the call merely subtracts n from the
     * scale; otherwise, it sets the scale to zero, and multiplies the integer
     * value by 10 ** (n - this.scale).  If n is negative, the call is
     * equivalent to movePointLeft(-n). (The BigDecimal returned by this call
     * has value (this * 10**n) and scale MAX(this.scale()-n, 0).)
     */
    public BigDecimal movePointRight(int n){
	return (scale >= n ? new BigDecimal(intVal, scale-n)
		           : new BigDecimal(timesTenToThe(intVal, n-scale),0));
    }

    // Comparison Operations

    /**
     * Returns -1, 0 or 1 as this number is less than, equal to, or greater
     * than val.  Two BigDecimals that are equal in value but have a
     * different scale (e.g., 2.0, 2.00) are considered equal by this method.
     * This method is provided in preference to individual methods for each
     * of the six boolean comparison operators (<, ==, >, >=, !=, <=).  The
     * suggested idiom for performing these comparisons is:  (x.compareTo(y)
     * <op> 0), where <op> is one of the six comparison operators.
     */
    public int compareTo(BigDecimal val){
	/* Optimization: would run fine without the next three lines */
	int sigDiff = signum() - val.signum();
	if (sigDiff != 0)
	    return (sigDiff > 0 ? 1 : -1);

	/* If signs match, scale and compare intVals */
	BigDecimal arg[] = new BigDecimal[2];
	arg[0] = this;	arg[1] = val;
	matchScale(arg);
	return arg[0].intVal.compareTo(arg[1].intVal);
    }

    /**
     * Returns true iff x is a BigDecimal whose value is equal to this number.
     * This method is provided so that BigDecimals can be used as hash keys.
     * Unlike compareTo, this method considers two BigDecimals equal only
     * if they are equal in value and scale.
     */
    public boolean equals(Object x){
	if (!(x instanceof BigDecimal))
	    return false;
	BigDecimal xDec = (BigDecimal) x;

	return scale == xDec.scale && intVal.equals(xDec.intVal);
    }

    /**
     * Returns the BigDecimal whose value is the lesser of this and val.
     * If the values are equal (as defined by the compareTo operator),
     * either may be returned.
     */
    public BigDecimal min(BigDecimal val){
	return (compareTo(val)<0 ? this : val);
    }

    /**
     * Returns the BigDecimal whose value is the greater of this and val.
     * If the values are equal (as defined by the compareTo operator),
     * either may be returned.
     */
    public BigDecimal max(BigDecimal val){
	return (compareTo(val)>0 ? this : val);
    }


    // Hash Function

    /**
     * Computes a hash code for this object.  Note that two BigDecimals
     * that are numerically equal but differ in scale (e.g., 2.0, 2.00) will
     * not generally have the same hash code.
     */
    public int hashCode(){
	return 37*intVal.hashCode() + scale;
    }

    // Format Converters

    /**
     * Returns the string representation of this number.  The digit-to-
     * character mapping provided by Character.forDigit is used.  The minus
     * sign and decimal point are used to indicate sign and scale.  (This
     * representation is compatible with the (String, int) constructor.)
     */
    public String toString(){
	if (scale == 0)	/* No decimal point */
	    return intVal.toString();

	/* Insert decimal point */
	StringBuffer buf;
	String intString = intVal.abs().toString();
	int signum = signum();
	int insertionPoint = intString.length() - scale;
	if (insertionPoint == 0) {  /* Point goes right before intVal */
	    return (signum<0 ? "-0." : "0.") + intString;
	} else if (insertionPoint > 0) { /* Point goes inside intVal */
	    buf = new StringBuffer(intString);
	    buf.insert(insertionPoint, '.');
	    if (signum < 0)
		buf.insert(0, '-');
	} else { /* We must insert zeros between point and intVal */
	    buf = new StringBuffer(3-insertionPoint + intString.length());
	    buf.append(signum<0 ? "-0." : "0.");
	    for (int i=0; i<-insertionPoint; i++)
		buf.append('0');
	    buf.append(intString);
	}
	return buf.toString();
    }

    /**
     * Converts this number to a BigInteger.  Standard narrowing primitive
     * conversion as per The Java Language Specification.  In particular,
     * note that any fractional part of this number will be truncated.
     */
    public BigInteger toBigInteger(){
	return (scale==0 ? intVal
			 : intVal.divide(BigInteger.valueOf(10).pow(scale)));
    }

    /**
     * Converts this number to an int.  Standard narrowing primitive conversion
     * as per The Java Language Specification.  In particular, note that any
     * fractional part of this number will be truncated.
     */
    public int intValue(){
	return toBigInteger().intValue();
    }

    /**
     * Converts this number to a long.  Standard narrowing primitive conversion
     * as per The Java Language Specification.  In particular, note that any
     * fractional part of this number will be truncated.
     */
    public long longValue(){
	return toBigInteger().longValue();
    }

    /**
     * Converts this number to a float.  Similar to the double-to-float
     * narrowing primitive conversion defined in The Java Language
     * Specification: if the number has too great a magnitude to represent
     * as a float, it will be converted to infinity or negative infinity,
     * as appropriate.
     */
    public float floatValue(){
	/* Somewhat inefficient, but guaranteed to work. */
	return Float.valueOf(this.toString()).floatValue();
    }

    /**
     * Converts the number to a double.  Similar to the double-to-float
     * narrowing primitive conversion defined in The Java Language
     * Specification: if the number has too great a magnitude to represent
     * as a double, it will be converted to infinity or negative infinity,
     * as appropriate.
     */
    public double doubleValue(){
	/* Somewhat inefficient, but guaranteed to work. */
	return Double.valueOf(this.toString()).doubleValue();
    }


    // Private "Helper" Methods

    /* Returns (a * 10^b) */
    private static BigInteger timesTenToThe(BigInteger a, int b) {
	return a.multiply(BigInteger.valueOf(10).pow(b));
    }

    /*
     * If the scales of val[0] and val[1] differ, rescale (non-destructively)
     * the lower-scaled BigDecimal so they match.
     */
    private static void matchScale(BigDecimal[] val) {
	if (val[0].scale < val[1].scale)
	    val[0] = val[0].setScale(val[1].scale);
	else if (val[1].scale < val[0].scale)
	    val[1] = val[1].setScale(val[0].scale);
    }

    /**
     * Reconstitute the <tt>BigDecimal</tt> instance from a stream (that is,
     * deserialize it).
     */
    private synchronized void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in all fields
	s.defaultReadObject();

        // Validate scale factor
        if (scale < 0)
	    throw new java.io.StreamCorruptedException(
                                      "BigDecimal: Negative scale");
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -