| Classic JavaDoc |
Class BigDecimal
java.lang.Object └ java.lang.Number └ java.math.BigDecimal
Implemented Interfaces:
public class BigDecimal extends Number implements Comparable
The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. The method provides a canonical representation of a BigDecimal.
The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate object to the operation. In either case, eight rounding modes are provided for the control of rounding. Using the integer fields in this class (such as ) to represent rounding mode is largely obsolete; the enumeration values of the RoundingMode enum, (such as ) should be used instead.
When a MathContext object is supplied with a precision setting of 0 (for example, ), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.) As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
When the precision setting is not 0, the rules of BigDecimal arithmetic are broadly compatible with selected modes of operation of the arithmetic defined in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 (section 7.4). Unlike those standards, BigDecimal includes many rounding modes, which were mandatory for division in BigDecimal releases prior to 5. Any conflicts between these ANSI standards and the BigDecimal specification are resolved in favor of BigDecimal.
Since the same numerical value can have different representations (with different scales), the rules of arithmetic and rounding must specify both the numerical result and the scale used in the result's representation.
In general the rounding modes and precision setting determine how operations return results with a limited number of digits when the exact result has more digits (perhaps infinitely many in the case of division) than the number of digits returned. First, the total number of digits to return is specified by the MathContext's precision setting; this determines the result's precision. The digit count starts from the leftmost nonzero digit of the exact result. The rounding mode determines how any discarded trailing digits affect the returned result.
For all arithmetic operators , the operation is carried out as though an exact intermediate result were first calculated and then rounded to the number of digits specified by the precision setting (if necessary), using the selected rounding mode. If the exact result is not returned, some digit positions of the exact result are discarded. When rounding increases the magnitude of the returned result, it is possible for a new digit position to be created by a carry propagating to a leading "9" digit. For example, rounding the value 999.9 to three digits rounding up would be numerically equal to one thousand, represented as 100×101. In such cases, the new "1" is the leading digit position of the returned result.
Besides a logical exact result, each arithmetic operation has a preferred scale for representing a result. The preferred scale for each operation is listed in the table below.
| Operation | Preferred Scale of Result |
|---|---|
| Add | max(addend.scale(), augend.scale()) |
| Subtract | max(minuend.scale(), subtrahend.scale()) |
| Multiply | multiplier.scale() + multiplicand.scale() |
| Divide | dividend.scale() - divisor.scale() |
Before rounding, the scale of the logical exact intermediate
result is the preferred scale for that operation. If the exact
numerical result cannot be represented in precision
digits, rounding selects the set of digits to return and the scale
of the result is reduced from the scale of the intermediate result
to the least scale which can represent the precision
digits actually returned. If the exact result can be represented
with at most precision digits, the representation
of the result with the scale closest to the preferred scale is
returned. In particular, an exactly representable quotient may be
represented in fewer than precision digits by removing
trailing zeros and decreasing the scale. For example, rounding to
three digits using the {@linkplain RoundingMode#FLOOR floor}
rounding mode,
19/100 = 0.19 // integer=19, scale=2
but
21/110 = 0.190 // integer=190, scale=3
Note that for add, subtract, and multiply, the reduction in scale will equal the number of digit positions of the exact result which are discarded. If the rounding causes a carry propagation to create a new high-order digit position, an additional digit of the result is discarded than when no new digit position is created.
Other methods may have slightly different rounding semantics. For example, the result of the pow method using the {@linkplain #pow(int, MathContext) specified algorithm} can occasionally differ from the rounded mathematical result by more than one unit in the last place, one {@linkplain #ulp() ulp}.
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 and round) return a BigDecimal whose value is approximately (or exactly) equal to that of the operand, but whose scale or precision is the specified value; that is, they increase or decrease the precision of the stored 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.
For the sake of brevity and clarity, pseudo-code is used throughout the descriptions of BigDecimal methods. The pseudo-code expression (i + j) is shorthand for "a BigDecimal whose value is that of the BigDecimal i added to that of the BigDecimal j." The pseudo-code expression (i == j) is shorthand for "true if and only if the BigDecimal i represents the same value as the BigDecimal j." Other pseudo-code expressions are interpreted similarly. Square brackets are used to represent the particular BigInteger and scale pair defining a BigDecimal value; for example [19, 2] is the BigDecimal numerically equal to 0.19 having a scale of 2.
Note: care should be exercised if BigDecimal objects are used as keys in a SortedMap or elements in a SortedSet since BigDecimal's natural ordering is inconsistent with equals. See , or for more information.
All methods and constructors for this class throw NullPointerException when passed a null object reference for any input parameter.
Fields
static BigDecimal | ONE | |
The value 1, with a scale of 0. |
static int | ROUND_CEILING | |
Rounding mode to round towards positive infinity. If the BigDecimal is positive, behaves as for ROUND_UP; if negative, behaves as for ROUND_DOWN. Note that this rounding mode never decreases the calculated value. |
static int | ROUND_DOWN | |
Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value. |
static int | ROUND_FLOOR | |
Rounding mode to round towards negative infinity. 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 calculated value. |
static int | ROUND_HALF_DOWN | |
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as for ROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as for ROUND_DOWN. |
static int | ROUND_HALF_EVEN | |
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for ROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for ROUND_HALF_DOWN if it's even. ... more > |
static int | ROUND_HALF_UP | |
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as for ROUND_UP if the discarded fraction is >= 0.5; otherwise, behaves as for ROUND_DOWN. Note that this is the rounding mode that most of us were tau ... more > |
static int | ROUND_UNNECESSARY | |
Rounding mode to assert 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 ArithmeticException is thrown. |
static int | ROUND_UP | |
Rounding mode to round away from zero. Always increments the digit prior to a nonzero discarded fraction. Note that this rounding mode never decreases the magnitude of the calculated value. |
static BigDecimal | TEN | |
The value 10, with a scale of 0. |
static BigDecimal | ZERO | |
The value 0, with a scale of 0. |
Constructors
public | BigDecimal (char in, int offset, int len) | |
Translates a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the #BigDecimal(String) constructor, while allowing a sub-array to be specified. Note that if the sequence of characters is already available within a charact ... more > |
public | BigDecimal (char in, int offset, int len, MathContext mc) | |
Translates a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the #BigDecimal(String) constructor, while allowing a sub-array to be specified and with rounding according to the context settings. Note that if the sequence ... more > |
public | BigDecimal (char in) | |
Translates a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the #BigDecimal(String) constructor. Note that if the sequence of characters is already available as a character array, using this constructor is faster than ... more > |
public | BigDecimal (char in, MathContext mc) | |
Translates a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the #BigDecimal(String) constructor and with rounding according to the context settings. Note that if the sequence of characters is already available as a ch ... more > |
public | BigDecimal (String val) | |
Translates the string representation of a BigDecimal into a BigDecimal. The string representation consists of an optional sign, '+' ('\u002B') or '-' ('\u002D'), followed by a sequence of zero or more decimal digits ("the integer"), optionally followed by a fraction, optional ... more > |
public | BigDecimal (String val, MathContext mc) | |
Translates the string representation of a BigDecimal into a BigDecimal, accepting the same strings as the #BigDecimal(String) constructor, with rounding according to the context settings. |
public | BigDecimal (double val) | |
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer. Notes: The results of this constructor can be ... more > |
public | BigDecimal (double val, MathContext mc) | |
Translates a double into a BigDecimal, with rounding according to the context settings. The scale of the BigDecimal is the smallest value such that (10scale × val) is an integer. The results of this constructor can be somewhat unpredictable and its use is generally not recom ... more > |
public | BigDecimal (BigInteger val) | |
Translates a BigInteger into a BigDecimal. The scale of the BigDecimal is zero. |
public | BigDecimal (BigInteger val, MathContext mc) | |
Translates a BigInteger into a BigDecimal rounding according to the context settings. The scale of the BigDecimal is zero. |
public | BigDecimal (BigInteger unscaledVal, int scale) | |
Translates a BigInteger unscaled value and an int scale into a BigDecimal. The value of the BigDecimal is (unscaledVal × 10-scale). |
public | BigDecimal (BigInteger unscaledVal, int scale, MathContext mc) | |
Translates a BigInteger unscaled value and an int scale into a BigDecimal, with rounding according to the context settings. The value of the BigDecimal is (unscaledVal × 10-scale), rounded according to the precision and rounding mode settings. |
public | BigDecimal (int val) | |
Translates an int into a BigDecimal. The scale of the BigDecimal is zero. |
public | BigDecimal (int val, MathContext mc) | |
Translates an int into a BigDecimal, with rounding according to the context settings. The scale of the BigDecimal, before any rounding, is zero. |
public | BigDecimal (long val) | |
Translates a long into a BigDecimal. The scale of the BigDecimal is zero. |
public | BigDecimal (long val, MathContext mc) | |
Translates a long into a BigDecimal, with rounding according to the context settings. The scale of the BigDecimal, before any rounding, is zero. |
Methods
| abs () | ||
Returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale(). |
| abs (MathContext mc) | ||
Returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings. |
| add (BigDecimal augend) | ||
Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()). |
| add (BigDecimal augend, MathContext mc) | ||
Returns a BigDecimal whose value is (this + augend), with rounding according to the context settings. If either number is zero and the precision setting is nonzero then the other number, rounded if necessary, is used as the result. |
byte | byteValueExact () | |
Converts this BigDecimal to a byte, checking for lost information. If this BigDecimal has a nonzero fractional part or is out of the possible range for a byte result then an ArithmeticException is thrown. |
int | compareTo (BigDecimal val) | |
Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparis ... more > |
| divide (BigDecimal divisor, int scale, int roundingMode) | ||
Returns a BigDecimal whose value is (this / divisor), and whose scale is as specified. If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied. The new int, RoundingMode) method should be used in preference to this legacy method. |
| divide (BigDecimal divisor, int scale, RoundingMode roundingMode) | ||
Returns a BigDecimal whose value is (this / divisor), and whose scale is as specified. If rounding must be performed to generate a result with the specified scale, the specified rounding mode is applied. |
| divide (BigDecimal divisor, int roundingMode) | ||
Returns a BigDecimal whose value is (this / divisor), 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. The new RoundingMode) method should be used in preference to this legacy method. |
| divide (BigDecimal divisor, RoundingMode roundingMode) | ||
Returns a BigDecimal whose value is (this / divisor), 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. |
| divide (BigDecimal divisor) | ||
Returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown. |
| divide (BigDecimal divisor, MathContext mc) | ||
Returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings. |
| divideAndRemainder (BigDecimal divisor) | ||
Returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands. Note that if both the integer quotient and remainder are needed, this method is faster than using the divideToIntegralValue and remainder m ... more > |
| divideAndRemainder (BigDecimal divisor, MathContext mc) | ||
Returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings. Note that if both the integer quotient and remainder are needed, this method is ... more > |
| divideToIntegralValue (BigDecimal divisor) | ||
Returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down. The preferred scale of the result is (this.scale() - divisor.scale()). |
| divideToIntegralValue (BigDecimal divisor, MathContext mc) | ||
Returns a BigDecimal whose value is the integer part of (this / divisor). Since the integer part of the exact quotient does not depend on the rounding mode, the rounding mode does not affect the values returned by this method. The preferred scale of the result is (this.scale() - div ... more > |
double | doubleValue () | |
Converts this BigDecimal to a double. This conversion is similar to the narrowing primitive conversion from double to float as defined in the Java Language Specification: if this BigDecimal has too great a magnitude represent as a double, it will be converted to Double#NEGATIVE_INFIN ... more > |
boolean | equals (Object x) | |
Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method). |
float | floatValue () | |
Converts this BigDecimal to a float. This conversion is similar to the narrowing primitive conversion from double to float defined in the Java Language Specification: if this BigDecimal has too great a magnitude to represent as a float, it will be converted to Float#NEGATIVE_INFINITY ... more > |
int | hashCode () | |
Returns the hash code for this BigDecimal. Note that two BigDecimal objects that are numerically equal but differ in scale (like 2.0 and 2.00) will generally not have the same hash code. |
int | intValue () | |
Converts this BigDecimal to an int. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big t ... more > |
int | intValueExact () | |
Converts this BigDecimal to an int, checking for lost information. If this BigDecimal has a nonzero fractional part or is out of the possible range for an int result then an ArithmeticException is thrown. |
long | longValue () | |
Converts this BigDecimal to a long. This conversion is analogous to a narrowing primitive conversion from double to short as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big t ... more > |
long | longValueExact () | |
Converts this BigDecimal to a long, checking for lost information. If this BigDecimal has a nonzero fractional part or is out of the possible range for a long result then an ArithmeticException is thrown. |
| max (BigDecimal val) | ||
Returns the maximum of this BigDecimal and val. |
| min (BigDecimal val) | ||
Returns the minimum of this BigDecimal and val. |
| movePointLeft (int n) | ||
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 &t ... more > |
| movePointRight (int n) | ||
Returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right. If n is non-negative, the call merely subtracts n from the scale. If n is negative, the call is equivalent to movePointLeft(-n). The BigDecimal returned by this call has value (t ... more > |
| multiply (BigDecimal multiplicand) | ||
Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()). |
| multiply (BigDecimal multiplicand, MathContext mc) | ||
Returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings. |
| negate () | ||
Returns a BigDecimal whose value is (-this), and whose scale is this.scale(). |
| negate (MathContext mc) | ||
Returns a BigDecimal whose value is (-this), with rounding according to the context settings. |
| plus () | ||
Returns a BigDecimal whose value is (+this), and whose scale is this.scale(). This method, which simply returns this BigDecimal is included for symmetry with the unary minus method #negate(). |
| plus (MathContext mc) | ||
Returns a BigDecimal whose value is (+this), with rounding according to the context settings. The effect of this method is identical to that of the #round(MathContext) method. |
| pow (int n) | ||
Returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision. The parameter n must be in the range 0 through 999999999, inclusive. ZERO.pow(0) returns #ONE. Note that future releases may expand the allowable exponent range of this method. |
| pow (int n, MathContext mc) | ||
Returns a BigDecimal whose value is (thisn). The current implementation uses the core algorithm defined in ANSI standard X3.274-1996 with rounding according to the context settings. In general, the returned numerical value is within two ulps of the exact numerical value for the chos ... more > |
int | precision () | |
Returns the precision of this BigDecimal. (The precision is the number of digits in the unscaled value.) The precision of a zero value is 1. |
| remainder (BigDecimal divisor) | ||
Returns a BigDecimal whose value is (this % divisor). The remainder is given by this.subtract(this.divideToIntegralValue(divisor).multiply(divisor)). Note that this is not the modulo operation (the result can be negative). |
| remainder (BigDecimal divisor, MathContext mc) | ||
Returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings. The MathContext settings affect the implicit divide used to compute the remainder. The remainder computation itself is by definition exact. Therefore, the remainder may contain mor ... more > |
| round (MathContext mc) | ||
Returns a BigDecimal rounded according to the MathContext settings. If the precision setting is 0 then no rounding takes place. The effect of this method is identical to that of the #plus(MathContext) method. |
int | scale () | |
Returns the scale of this BigDecimal. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. For example, a scale of -3 means the unscaled ... more > |
| scaleByPowerOfTen (int n) | ||
Returns a BigDecimal whose numerical value is equal to (this * 10n). The scale of the result is (this.scale() - n). |
| setScale (int newScale, RoundingMode roundingMode) | ||
Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation, the unscaled value must ... more > |
| setScale (int newScale, int roundingMode) | ||
Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal's unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation, the unscaled value must ... more > |
| setScale (int newScale) | ||
Returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal'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 BigDecim ... more > |
short | shortValueExact () | |
Converts this BigDecimal to a short, checking for lost information. If this BigDecimal has a nonzero fractional part or is out of the possible range for a short result then an ArithmeticException is thrown. |
int | signum () | |
Returns the signum function of this BigDecimal. |
| stripTrailingZeros () | ||
Returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. For example, stripping the trailing zeros from the BigDecimal value 600.0, which has [BigInteger, scale] components equals to [6000, 1], yields 6E2 with [BigIntege ... more > |
| subtract (BigDecimal subtrahend) | ||
Returns a BigDecimal whose value is (this - subtrahend), and whose scale is max(this.scale(), subtrahend.scale()). |
| subtract (BigDecimal subtrahend, MathContext mc) | ||
Returns a BigDecimal whose value is (this - subtrahend), with rounding according to the context settings. If subtrahend is zero then this, rounded if necessary, is used as the result. If this is zero then the result is subtrahend.negate(mc). |
| toBigInteger () | ||
Converts this BigDecimal to a BigInteger. This conversion is analogous to a narrowing primitive conversion from double to long as defined in the Java Language Specification: any fractional part of this BigDecimal will be discarded. Note that this conversion can lose information abou ... more > |
| toBigIntegerExact () | ||
Converts this BigDecimal to a BigInteger, checking for lost information. An exception is thrown if this BigDecimal has a nonzero fractional part. |
| toEngineeringString () | ||
Returns a string representation of this BigDecimal, using engineering notation if an exponent is needed. Returns a string that represents the BigDecimal as described in the #toString() method, except that if exponential notation is used, the power of ten is adjusted to be a multipl ... more > |
| toPlainString () | ||
Returns a string representation of this BigDecimal without an exponent field. For values with a positive scale, the number of digits to the right of the decimal point is used to indicate scale. For values with a zero or negative scale, the resulting string is generated as if the valu ... more > |
| toString () | ||
Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed. A standard canonical string form of the BigDecimal is created as though by the following steps: first, the absolute value of the unscaled value of the BigDecimal is converted t ... more > |
| ulp () | ||
Returns the size of an ulp, a unit in the last place, of this BigDecimal. An ulp of a nonzero BigDecimal value is the positive distance between this value and the BigDecimal value next larger in magnitude with the same number of digits. An ulp of a zero value is numerically equal to ... more > |
| unscaledValue () | ||
Returns a BigInteger whose value is the unscaled value of this BigDecimal. (Computes (this * 10this.scale()).) |
static BigDecimal | valueOf (long unscaledVal, int scale) | |
Translates a long unscaled value and an int scale into a BigDecimal. This "static factory method" is provided in preference to a (long, int) constructor because it allows for reuse of frequently used BigDecimal values.. |
static BigDecimal | valueOf (long val) | |
Translates a long value into a BigDecimal with a scale of zero. This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigDecimal values. |
static BigDecimal | valueOf (double val) | |
Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double#toString(double) method. Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting fr ... more > |
Inherited methods
Community comments
Powered by JavaDocPlus