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

📄 bigdecimal.java

📁 《移动Agent技术》一书的所有章节源代码。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * @(#)BigDecimal.java	1.8 98/10/28
 *
 * Copyright 1996-1998 by Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Sun Microsystems, Inc. ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Sun.
 */

package java.math;

/**
 * Immutable, arbitrary-precision signed decimal numbers.  A BigDecimal
 * consists of an arbitrary precision integer value and a non-negative
 * integer scale, which represents the number of decimal digits to the
 * right of the decimal point.  (The number represented by the BigDecimal
 * is intVal/10**scale.)  BigDecimals provide operations for basic arithmetic,
 * scale manipulation, comparison, format conversion and hashing.
 *
 * <p>The BigDecimal class gives its user complete control over rounding
 * behavior, forcing the user to explicitly specify a rounding behavior for
 * operations capable of discarding precision (divide and setScale).  Eight
 * <em>rounding modes</em> are provided for this purpose.
 *
 * Two types of operations are provided for manipulating the scale of a
 * BigDecimal: scaling/rounding operations and decimal point motion operations.
 * Scaling/Rounding operations (SetScale) return a BigDecimal whose value is
 * approximately (or exactly) equal to that of the operand, but whose scale is
 * the specified value; that is, they increase or decrease the precision
 * of the number with minimal effect on its value.  Decimal point motion
 * operations (movePointLeft and movePointRight) return a BigDecimal created
 * from the operand by moving the decimal point a specified distance in the
 * specified direction; that is, they change a number's value without affecting
 * its precision.
 *
 * @see BigInteger
 * @version 	1.8, 98/10/29
 * @author      Josh Bloch
 */
public class BigDecimal extends Number {
    private BigInteger intVal;
    private int	       scale = 0;

    /* Appease the serialization gods */
    private static final long serialVersionUID = 6108874887143696463L;

    // Constructors

    /**
     * Constructs a BigDecimal from a string containing an optional minus
     * sign followed by a sequence of zero or more decimal digits, optionally
     * followed by a fraction, which consists of a decimal point followed by
     * zero or more decimal digits.  The string must contain at least one
     * digit in the integer or fractional part.  The scale of the resulting
     * BigDecimal will be the number of digits to the right of the decimal
     * point in the string, or 0 if the string contains no decimal point.
     * The character-to-digit mapping is provided by Character.digit.
     * Any extraneous characters (including whitespace) will result in
     * a NumberFormatException.
     */
    public BigDecimal(String val) throws NumberFormatException {
	int pointPos = val.indexOf('.');
	if (pointPos == -1) {			 /* e.g. "123" */
	    intVal = new BigInteger(val);
	} else if (pointPos == val.length()-1) { /* e.g. "123." */
	    intVal = new BigInteger(val.substring(0, val.length()-1));
	} else {    /* Fraction part exists */
	    String fracString = val.substring(pointPos+1);
	    scale = fracString.length();
	    BigInteger fraction =  new BigInteger(fracString);
	    if (fraction.signum() < 0)		 /* ".-123" illegal! */
		throw new NumberFormatException();

	    if (pointPos==0) {			 /* e.g.  ".123" */
		intVal = fraction;
	    } else if (val.charAt(0)=='-' && pointPos==1) {
		intVal = fraction.negate();	 /* e.g. "-.123" */
	    } else  {				 /* e.g. "-123.456" */
		String intString = val.substring(0, pointPos);
		BigInteger intPart = new BigInteger(intString);
		if (val.charAt(0) == '-')
		    fraction = fraction.negate();
		intVal = timesTenToThe(intPart, scale).add(fraction);
	    }
	}
    }

    /**
     * Translates a double into a BigDecimal.  The scale of the BigDecimal
     * is the smallest value such that (10**scale * val) is an integer.
     * A double whose value is -infinity, +infinity or NaN will result in a
     * NumberFormatException.
     */
    public BigDecimal(double val) throws NumberFormatException{
	if (Double.isInfinite(val) || Double.isNaN(val))
	    throw new NumberFormatException("Infinite or NaN");

	/*
	 * Translate the double into sign, exponent and mantissa, according
	 * to the formulae in JLS, Section 20.10.22.
	 */
	long valBits = Double.doubleToLongBits(val);
	int sign = ((valBits >> 63)==0 ? 1 : -1);
	int exponent = (int) ((valBits >> 52) & 0x7ffL);
	long mantissa = (exponent==0 ? (valBits & ((1L<<52) - 1)) << 1
				     : (valBits & ((1L<<52) - 1)) | (1L<<52));
	exponent -= 1075;
	/* At this point, val == sign * mantissa * 2**exponent */

	/*
	 * Special case zero to to supress nonterminating normalization
	 * and bogus scale calculation.
	 */
	if (mantissa == 0) {
	    intVal = BigInteger.valueOf(0);
	    return;
	}

	/* Normalize */
	while((mantissa & 1) == 0) {    /*  i.e., Mantissa is even */
	    mantissa >>= 1;
	    exponent++;
	}

	/* Calculate intVal and scale */
	intVal = BigInteger.valueOf(sign*mantissa);
	if (exponent < 0) {
	    intVal = intVal.multiply(BigInteger.valueOf(5).pow(-exponent));
	    scale = -exponent;
	} else if (exponent > 0) {
	    intVal = intVal.multiply(BigInteger.valueOf(2).pow(exponent));
	}
    }

    /**
     * Translates a BigInteger into a BigDecimal.  The scale of the BigDecimal
     * is zero.
     */
    public BigDecimal(BigInteger val) {
	intVal = val;
    }

    /**
     * Translates a BigInteger and a scale into a BigDecimal.  The value
     * of the BigDecimal is (BigInteger/10**scale).  A negative scale
     * will result in a NumberFormatException.
     */
    public BigDecimal(BigInteger val, int scale) throws NumberFormatException {
	if (scale < 0)
	    throw new NumberFormatException("Negative scale");

	intVal = val;
	this.scale = scale;
    }


    // Static Factory Methods

    /**
     * Returns a BigDecimal with a value of (val/10**scale).  This factory
     * is provided in preference to a (long) constructor because it allows
     * for reuse of frequently used BigDecimals (like 0 and 1), obviating
     * the need for exported constants.  A negative scale will result in a
     * NumberFormatException.
     */
    public static BigDecimal valueOf(long val, int scale)
	    throws NumberFormatException {
	return new BigDecimal(BigInteger.valueOf(val), scale);
    }

    /**
     * Returns a BigDecimal with the given value and a scale of zero.
     * This factory is provided in preference to a (long) constructor
     * because it allows for reuse of frequently used BigDecimals (like
     * 0 and 1), obviating the need for exported constants.
     */
    public static BigDecimal valueOf(long val) {
	return valueOf(val, 0);
    }


    // Arithmetic Operations

    /**
     * Returns a BigDecimal whose value is (this + val), and whose scale is
     * MAX(this.scale(), val.scale).
     */
    public BigDecimal add(BigDecimal val){
	BigDecimal arg[] = new BigDecimal[2];
	arg[0] = this;	arg[1] = val;
	matchScale(arg);
	return new BigDecimal(arg[0].intVal.add(arg[1].intVal), arg[0].scale);
    }

    /**
     * Returns a BigDecimal whose value is (this - val), and whose scale is
     * MAX(this.scale(), val.scale).
     */
    public BigDecimal subtract(BigDecimal val){
	BigDecimal arg[] = new BigDecimal[2];
	arg[0] = this;	arg[1] = val;
	matchScale(arg);
	return new BigDecimal(arg[0].intVal.subtract(arg[1].intVal),
			      arg[0].scale);
    }

    /**
     * Returns a BigDecimal whose value is (this * val), and whose scale is
     * this.scale() + val.scale.
     */
    public BigDecimal multiply(BigDecimal val){
	return new BigDecimal(intVal.multiply(val.intVal), scale+val.scale);
    }

    /**
     * Returns a BigDecimal whose value is (this / val), and whose scale
     * is as specified.  If rounding must be performed to generate a
     * result with the given scale, the specified rounding mode is
     * applied.  Throws an ArithmeticException if val == 0, scale < 0,
     * or the rounding mode is ROUND_UNNECESSARY and the specified scale
     * is insufficient to represent the result of the division exactly.
     * Throws an IllegalArgumentException if roundingMode does not
     * represent a valid rounding mode.
     */
    public BigDecimal divide(BigDecimal val, 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");

	/*
	 * Rescale dividend or divisor (whichever can be "upscaled" to
	 * produce correctly scaled quotient).
	 */
	BigDecimal dividend, divisor;
	if (scale + val.scale >= this.scale) {
	    dividend = this.setScale(scale + val.scale);
	    divisor = val;
	} else {
	    dividend = this;
	    divisor = val.setScale(this.scale - scale);
	}

	/* Do the division and return result if it's exact */
	BigInteger i[] = dividend.intVal.divideAndRemainder(divisor.intVal);
	BigInteger q = i[0], r = i[1];
	if (r.signum() == 0)
	    return new BigDecimal(q, scale);
	else if (roundingMode == ROUND_UNNECESSARY) /* Rounding prohibited */
	    throw new ArithmeticException("Rounding necessary");

	/* Round as appropriate */
	int signum = dividend.signum() * divisor.signum(); /* Sign of result */
	boolean increment;
	if (roundingMode == ROUND_UP) {		    /* Away from zero */
	    increment = true;
	} else if (roundingMode == ROUND_DOWN) {    /* Towards zero */
	    increment = false;
	} else if (roundingMode == ROUND_CEILING) { /* Towards +infinity */
	    increment = (signum > 0);
	} else if (roundingMode == ROUND_FLOOR) {   /* Towards -infinity */
	    increment = (signum < 0);
	} else { /* Remaining modes based on nearest-neighbor determination */
	    int cmpFracHalf = r.abs().multiply(BigInteger.valueOf(2)).
					 compareTo(divisor.intVal.abs());
	    if (cmpFracHalf < 0) {	   /* We're closer to higher digit */
		increment = false;
	    } else if (cmpFracHalf > 0) {  /* We're closer to lower digit */
		increment = true;
	    } else { 			   /* We're dead-center */
		if (roundingMode == ROUND_HALF_UP)
		    increment = true;
		else if (roundingMode == ROUND_HALF_DOWN)
		    increment = false;
		else  /* roundingMode == ROUND_HALF_EVEN */
		    increment = q.testBit(0);	/* true iff q is odd */
	    }
	}
	return (increment
		? new BigDecimal(q.add(BigInteger.valueOf(signum)), scale)
		: new BigDecimal(q, scale));
    }

    /**
     * Returns a BigDecimal whose value is (this / val), and whose scale
     * is this.scale().  If rounding must be performed to generate a
     * result with the given scale, the specified rounding mode is
     * applied.  Throws an ArithmeticException if val == 0.  Throws
     * an IllegalArgumentException if roundingMode does not represent a
     * valid rounding mode.
     */
    public BigDecimal divide(BigDecimal val, int roundingMode)
	throws ArithmeticException, IllegalArgumentException{
	    return this.divide(val, scale, roundingMode);
    }

   /**
    * Returns a BigDecimal whose value is the absolute value of this
    * number, and whose scale is this.scale().
    */
    public BigDecimal abs(){
	return (signum() < 0 ? negate() : this);
    }

    /**
     * Returns a BigDecimal whose value is -1 * this, and whose scale is
     * this.scale().
     */
    public BigDecimal negate(){
	return new BigDecimal(intVal.negate(), scale);
    }

    /**
     * Returns the signum function of this number (i.e., -1, 0 or 1 as
     * the value of this number is negative, zero or positive).
     */
    public int signum(){
	return intVal.signum();
    }

    /**
     * Returns the scale of this number.
     */
    public int scale(){
	return scale;

⌨️ 快捷键说明

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