Class BigDecimal

java.lang.Object
java.lang.Number
java.math.BigDecimal
All Implemented Interfaces:
Serializable,Comparable<BigDecimal>

public classBigDecimalextendsNumberimplementsComparable<BigDecimal>
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integerunscaled value and a 32-bit integerscale. If the scale is zero or positive, the scale is the number of digits to the right of the decimal point. If the scale is negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by theBigDecimal is therefore(unscaledValue × 10-scale).

TheBigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. ThetoString() method provides a canonical representation of aBigDecimal.

TheBigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, anArithmeticException is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriateMathContext object to the operation. In either case, eightrounding modes are provided for the control of rounding. Using the integer fields in this class (such asROUND_HALF_UP) to represent rounding mode is deprecated; the enumeration values of theRoundingModeenum, (such asRoundingMode.HALF_UP) should be used instead.

When aMathContext object is supplied with a precision setting of 0 (for example,MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take noMathContext object. 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. Any conflicts between these ANSI standards and theBigDecimal specification are resolved in favor ofBigDecimal.

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. The different representations of the same numerical value are called members of the samecohort. Thenatural order ofBigDecimal considers members of the same cohort to be equal to each other. In contrast, theequals method requires both the numerical value and representation to be the same for equality to hold. The results of methods likescale andunscaledValue() will differ for numerically equal values with different representations.

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 and square root) than the number of digits returned. First, the total number of digits to return is specified by theMathContext'sprecision setting; this determines the result'sprecision. 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.

For methods and constructors with aMathContext parameter, if the result is inexact but the rounding mode isUNNECESSARY, an ArithmeticException will be thrown.

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.

Preferred Scales for Results of Arithmetic Operations
OperationPreferred Scale of Result
Addmax(addend.scale(), augend.scale())
Subtractmax(minuend.scale(), subtrahend.scale())
Multiplymultiplier.scale() + multiplicand.scale()
Dividedividend.scale() - divisor.scale()
Square rootradicand.scale()/2
These scales are the ones used by the methods which return exact arithmetic results; except that an exact divide may have to use a larger scale since the exact result may have more digits. For example,1/32 is0.03125.

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 inprecision 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 theprecision digits actually returned. If the exact result can be represented with at mostprecision 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 thanprecision digits by removing trailing zeros and decreasing the scale. For example, rounding to three digits using thefloor 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 thepow method using thespecified algorithm can occasionally differ from the rounded mathematical result by more than one unit in the last place, oneulp.

Two types of operations are provided for manipulating the scale of aBigDecimal: scaling/rounding operations and decimal point motion operations. Scaling/rounding operations (setScale andround) return aBigDecimal 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 andmovePointRight) return aBigDecimal created from the operand by moving the decimal point a specified distance in the specified direction.

As a 32-bit integer, the set of values for the scale is large, but bounded. If the scale of a result would exceed the range of a 32-bit integer, either by overflow or underflow, the operation may throw anArithmeticException.

For the sake of brevity and clarity, pseudo-code is used throughout the descriptions ofBigDecimal methods. The pseudo-code expression(i + j) is shorthand for "aBigDecimal whose value is that of theBigDecimali added to that of theBigDecimalj." The pseudo-code expression(i == j) is shorthand for "true if and only if theBigDecimali represents the same value as theBigDecimalj." Other pseudo-code expressions are interpreted similarly. Square brackets are used to represent the particularBigInteger and scale pair defining aBigDecimal value; for example [19, 2] is theBigDecimal numerically equal to 0.19 having a scale of 2.

All methods and constructors for this class throwNullPointerException when passed anull object reference for any input parameter.

API Note:
Care should be exercised ifBigDecimal objects are used as keys in aSortedMap or elements in aSortedSet since BigDecimal'snatural ordering isinconsistent with equals. SeeComparable,SortedMap orSortedSet for more information.

Relation to IEEE 754 Decimal Arithmetic

Starting with its 2008 revision, theIEEE 754 Standard for Floating-point Arithmetic has covered decimal formats and operations. While there are broad similarities in the decimal arithmetic defined by IEEE 754 and by this class, there are notable differences as well. The fundamental similarity shared by BigDecimal and IEEE 754 decimal arithmetic is the conceptual operation of computing the mathematical infinitely precise real number value of an operation and then mapping that real number to a representable decimal floating-point value under arounding policy. The rounding policy is called arounding mode forBigDecimal and called a rounding-direction attribute in IEEE 754-2019. When the exact value is not representable, the rounding policy determines which of the two representable decimal values bracketing the exact value is selected as the computed result. The notion of apreferred scale/preferred exponent is also shared by both systems.

For differences, IEEE 754 includes several kinds of values not modeled byBigDecimal including negative zero, signed infinities, and NaN (not-a-number). IEEE 754 defines formats, which are parameterized by base (binary or decimal), number of digits of precision, and exponent range. A format determines the set of representable values. Most operations accept as input one or more values of a given format and produce a result in the same format. ABigDecimal'sscale is equivalent to negating an IEEE 754 value's exponent.BigDecimal values do not have a format in the same sense; all values have the same possible range of scale/exponent and theunscaled value has arbitrary precision. Instead, for theBigDecimal operations taking aMathContext parameter, if theMathContext has a nonzero precision, the set of possible representable values for the result is determined by the precision of theMathContext argument. For example inBigDecimal, if a nonzero three-digit number and a nonzero four-digit number are multiplied together in the context of aMathContext object having a precision of three, the result will have three digits (assuming no overflow or underflow, etc.).

The rounding policies implemented byBigDecimal operations indicated byrounding modes are a proper superset of the IEEE 754 rounding-direction attributes.

BigDecimal arithmetic will most resemble IEEE 754 decimal arithmetic if aMathContext corresponding to an IEEE 754 decimal format, such asdecimal64 ordecimal128 is used to round all starting values and intermediate operations. The numerical values computed can differ if the exponent range of the IEEE 754 format being approximated is exceeded since a MathContext does not constrain the scale ofBigDecimal results. Operations that would generate a NaN or exact infinity, such as dividing by zero, throw anArithmeticException inBigDecimal arithmetic.

Algorithmic Complexity

Operations onBigDecimal values have a range of algorithmic complexities; in general, those complexities are a function of both the size of the unscaled value as well as the size of the scale. For example, anexact multiply of twoBigDecimal values is subject to the samecomplexity constraints asBigInteger multiply of the unscaled values. In contrast, aBigDecimal value with a compact representation likenew BigDecimal(1E-1000000000) has atoPlainString() result with over one billion characters.

Operations may also allocate and compute on intermediate results, potentially those allocations may be as large as in proportion to the running time of the algorithm.

Users ofBigDecimal concerned with bounding the running time or space of operations can screen outBigDecimal values with unscaled values or scales above a chosen magnitude.

Since:
1.1
External Specifications
See Also:
  • Field Details

    • ZERO

      public static final BigDecimal ZERO
      The value 0, with a scale of 0.
      Since:
      1.5
    • ONE

      public static final BigDecimal ONE
      The value 1, with a scale of 0.
      Since:
      1.5
    • TWO

      public static final BigDecimal TWO
      The value 2, with a scale of 0.
      Since:
      19
    • TEN

      public static final BigDecimal TEN
      The value 10, with a scale of 0.
      Since:
      1.5
    • ROUND_UP

      @Deprecated(since="9")public static final int ROUND_UP
      Deprecated.
      UseRoundingMode.UP instead.
      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.
      See Also:
    • ROUND_DOWN

      @Deprecated(since="9")public static final int ROUND_DOWN
      Deprecated.
      UseRoundingMode.DOWN instead.
      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.
      See Also:
    • ROUND_CEILING

      @Deprecated(since="9")public static final int ROUND_CEILING
      Deprecated.
      Rounding mode to round towards positive infinity. If theBigDecimal is positive, behaves as forROUND_UP; if negative, behaves as forROUND_DOWN. Note that this rounding mode never decreases the calculated value.
      See Also:
    • ROUND_FLOOR

      @Deprecated(since="9")public static final int ROUND_FLOOR
      Deprecated.
      UseRoundingMode.FLOOR instead.
      Rounding mode to round towards negative infinity. If theBigDecimal is positive, behave as forROUND_DOWN; if negative, behave as forROUND_UP. Note that this rounding mode never increases the calculated value.
      See Also:
    • ROUND_HALF_UP

      @Deprecated(since="9")public static final int ROUND_HALF_UP
      Deprecated.
      Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. Behaves as forROUND_UP if the discarded fraction is ≥ 0.5; otherwise, behaves as forROUND_DOWN. Note that this is the rounding mode that most of us were taught in grade school.
      See Also:
    • ROUND_HALF_DOWN

      @Deprecated(since="9")public static final int ROUND_HALF_DOWN
      Deprecated.
      Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. Behaves as forROUND_UP if the discarded fraction is > 0.5; otherwise, behaves as forROUND_DOWN.
      See Also:
    • ROUND_HALF_EVEN

      @Deprecated(since="9")public static final int ROUND_HALF_EVEN
      Deprecated.
      Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as forROUND_HALF_UP if the digit to the left of the discarded fraction is odd; behaves as forROUND_HALF_DOWN if it's even. Note that this is the rounding mode that minimizes cumulative error when applied repeatedly over a sequence of calculations.
      See Also:
    • ROUND_UNNECESSARY

      @Deprecated(since="9")public static final int ROUND_UNNECESSARY
      Deprecated.
      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, anArithmeticException is thrown.
      See Also:
  • Constructor Details

    • BigDecimal

      public BigDecimal(char[] in, int offset, int len)
      Translates a character array representation of aBigDecimal into aBigDecimal, accepting the same sequence of characters as theBigDecimal(String) constructor, while allowing a sub-array to be specified.
      Implementation Note:
      If the sequence of characters is already available within a character array, using this constructor is faster than converting thechar array to string and using theBigDecimal(String) constructor.
      Parameters:
      in -char array that is the source of characters.
      offset - first character in the array to inspect.
      len - number of characters to consider.
      Throws:
      NumberFormatException - ifin is not a valid representation of aBigDecimal or the defined subarray is not wholly withinin.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(char[] in, int offset, int len,MathContext mc)
      Translates a character array representation of aBigDecimal into aBigDecimal, accepting the same sequence of characters as theBigDecimal(String) constructor, while allowing a sub-array to be specified and with rounding according to the context settings.
      Implementation Note:
      If the sequence of characters is already available within a character array, using this constructor is faster than converting thechar array to string and using theBigDecimal(String) constructor.
      Parameters:
      in -char array that is the source of characters.
      offset - first character in the array to inspect.
      len - number of characters to consider.
      mc - the context to use.
      Throws:
      NumberFormatException - ifin is not a valid representation of aBigDecimal or the defined subarray is not wholly withinin.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(char[] in)
      Translates a character array representation of aBigDecimal into aBigDecimal, accepting the same sequence of characters as theBigDecimal(String) constructor.
      Implementation Note:
      If the sequence of characters is already available as a character array, using this constructor is faster than converting thechar array to string and using theBigDecimal(String) constructor.
      Parameters:
      in -char array that is the source of characters.
      Throws:
      NumberFormatException - ifin is not a valid representation of aBigDecimal.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(char[] in,MathContext mc)
      Translates a character array representation of aBigDecimal into aBigDecimal, accepting the same sequence of characters as theBigDecimal(String) constructor and with rounding according to the context settings.
      Implementation Note:
      If the sequence of characters is already available as a character array, using this constructor is faster than converting thechar array to string and using theBigDecimal(String) constructor.
      Parameters:
      in -char array that is the source of characters.
      mc - the context to use.
      Throws:
      NumberFormatException - ifin is not a valid representation of aBigDecimal.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(String val)
      Translates the string representation of aBigDecimal into aBigDecimal. 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, optionally followed by an exponent.

      The fraction consists of a decimal point followed by zero or more decimal digits. The string must contain at least one digit in either the integer or the fraction. The number formed by the sign, the integer and the fraction is referred to as thesignificand.

      The exponent consists of the character'e' ('\u0065') or'E' ('\u0045') followed by one or more decimal digits.

      More formally, the strings this constructor accepts are described by the following grammar:

      BigDecimalString:
      Signopt Significand Exponentopt
      Sign:
      +
      -
      Significand:
      IntegerPart.FractionPartopt
      .FractionPart
      IntegerPart
      IntegerPart:
      Digits
      FractionPart:
      Digits
      Exponent:
      ExponentIndicator SignedInteger
      ExponentIndicator:
      e
      E
      SignedInteger:
      Signopt Digits
      Digits:
      Digit
      Digits Digit
      Digit:
      any character for whichCharacter.isDigit(char) returnstrue, including 0, 1, 2 ...

      The scale of the returnedBigDecimal will be the number of digits in the fraction, or zero if the string contains no decimal point, subject to adjustment for any exponent; if the string contains an exponent, the exponent is subtracted from the scale. The value of the resulting scale must lie betweenInteger.MIN_VALUE andInteger.MAX_VALUE, inclusive.

      The character-to-digit mapping is provided byCharacter.digit(char, int) set to convert to radix 10. The String may not contain any extraneous characters (whitespace, for example).

      Examples:
      The value of the returnedBigDecimal is equal tosignificand × 10 exponent. For each string on the left, the resulting representation [BigInteger,scale] is shown on the right.

       "0"            [0,0] "0.00"         [0,2] "123"          [123,0] "-123"         [-123,0] "1.23E3"       [123,-1] "1.23E+3"      [123,-1] "12.3E+7"      [123,-6] "12.0"         [120,1] "12.3"         [123,1] "0.00123"      [123,5] "-1.23E-12"    [-123,14] "1234.5E-4"    [12345,5] "0E+7"         [0,-7] "-0"           [0,0]

      API Note:
      For values other thanfloat anddouble NaN and ±Infinity, this constructor is compatible with the values returned byFloat.toString(float) andDouble.toString(double). This is generally the preferred way to convert afloat ordouble into a BigDecimal, as it doesn't suffer from the unpredictability of theBigDecimal(double) constructor.
      Parameters:
      val - String representation ofBigDecimal.
      Throws:
      NumberFormatException - ifval is not a valid representation of aBigDecimal.
    • BigDecimal

      public BigDecimal(String val,MathContext mc)
      Translates the string representation of aBigDecimal into aBigDecimal, accepting the same strings as theBigDecimal(String) constructor, with rounding according to the context settings.
      Parameters:
      val - string representation of aBigDecimal.
      mc - the context to use.
      Throws:
      NumberFormatException - ifval is not a valid representation of a BigDecimal.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(double val)
      Translates adouble into aBigDecimal which is the exact decimal representation of thedouble's binary floating-point value. The scale of the returnedBigDecimal is the smallest value such that(10scale × val) is an integer.

      Notes:

      1. The results of this constructor can be somewhat unpredictable. One might assume that writingnew BigDecimal(0.1) in Java creates aBigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as adouble (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passedin to the constructor is not exactly equal to 0.1, appearances notwithstanding.
      2. TheString constructor, on the other hand, is perfectly predictable: writingnew BigDecimal("0.1") creates aBigDecimal which isexactly equal to 0.1, as one would expect. Therefore, it is generally recommended that theString constructor be used in preference to this one.
      3. When adouble must be used as a source for aBigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting thedouble to aString using theDouble.toString(double) method and then using theBigDecimal(String) constructor. To get that result, use thestaticvalueOf(double) method.

      Parameters:
      val -double value to be converted toBigDecimal.
      Throws:
      NumberFormatException - ifval is infinite or NaN.
    • BigDecimal

      public BigDecimal(double val,MathContext mc)
      Translates adouble into aBigDecimal, with rounding according to the context settings. The scale of theBigDecimal 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 recommended; see the notes under theBigDecimal(double) constructor.

      Parameters:
      val -double value to be converted toBigDecimal.
      mc - the context to use.
      Throws:
      NumberFormatException - ifval is infinite or NaN.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(BigInteger val)
      Translates aBigInteger into aBigDecimal. The scale of theBigDecimal is zero.
      Parameters:
      val -BigInteger value to be converted toBigDecimal.
    • BigDecimal

      public BigDecimal(BigInteger val,MathContext mc)
      Translates aBigInteger into aBigDecimal rounding according to the context settings. The scale of theBigDecimal is zero.
      Parameters:
      val -BigInteger value to be converted toBigDecimal.
      mc - the context to use.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(BigInteger unscaledVal, int scale)
      Translates aBigInteger unscaled value and anint scale into aBigDecimal. The value of theBigDecimal is(unscaledVal × 10-scale).
      Parameters:
      unscaledVal - unscaled value of theBigDecimal.
      scale - scale of theBigDecimal.
    • BigDecimal

      public BigDecimal(BigInteger unscaledVal, int scale,MathContext mc)
      Translates aBigInteger unscaled value and anint scale into aBigDecimal, with rounding according to the context settings. The value of theBigDecimal is(unscaledVal × 10-scale), rounded according to theprecision and rounding mode settings.
      Parameters:
      unscaledVal - unscaled value of theBigDecimal.
      scale - scale of theBigDecimal.
      mc - the context to use.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(int val)
      Translates anint into aBigDecimal. The scale of theBigDecimal is zero.
      Parameters:
      val -int value to be converted toBigDecimal.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(int val,MathContext mc)
      Translates anint into aBigDecimal, with rounding according to the context settings. The scale of theBigDecimal, before any rounding, is zero.
      Parameters:
      val -int value to be converted toBigDecimal.
      mc - the context to use.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(long val)
      Translates along into aBigDecimal. The scale of theBigDecimal is zero.
      Parameters:
      val -long value to be converted toBigDecimal.
      Since:
      1.5
    • BigDecimal

      public BigDecimal(long val,MathContext mc)
      Translates along into aBigDecimal, with rounding according to the context settings. The scale of theBigDecimal, before any rounding, is zero.
      Parameters:
      val -long value to be converted toBigDecimal.
      mc - the context to use.
      Since:
      1.5
  • Method Details

    • valueOf

      public static BigDecimal valueOf(long unscaledVal, int scale)
      Translates along unscaled value and anint scale into aBigDecimal.
      API Note:
      This static factory method is provided in preference to a (long,int) constructor because it allows for reuse of frequently usedBigDecimal values.
      Parameters:
      unscaledVal - unscaled value of theBigDecimal.
      scale - scale of theBigDecimal.
      Returns:
      aBigDecimal whose value is(unscaledVal × 10-scale).
    • valueOf

      public static BigDecimal valueOf(long val)
      Translates along value into aBigDecimal with a scale of zero.
      API Note:
      This static factory method is provided in preference to a (long) constructor because it allows for reuse of frequently usedBigDecimal values.
      Parameters:
      val - value of theBigDecimal.
      Returns:
      aBigDecimal whose value isval.
    • valueOf

      public static BigDecimal valueOf(double val)
      Translates adouble into aBigDecimal, using thedouble's canonical string representation provided by theDouble.toString(double) method.
      API Note:
      This is generally the preferred way to convert adouble (orfloat) into aBigDecimal, as the value returned is equal to that resulting from constructing aBigDecimal from the result of usingDouble.toString(double).
      Parameters:
      val -double to convert to aBigDecimal.
      Returns:
      aBigDecimal whose value is equal to or approximately equal to the value ofval.
      Throws:
      NumberFormatException - ifval is infinite or NaN.
      Since:
      1.5
    • add

      public BigDecimal add(BigDecimal augend)
      Returns aBigDecimal whose value is(this + augend), and whose scale ismax(this.scale(), augend.scale()).
      Parameters:
      augend - value to be added to thisBigDecimal.
      Returns:
      this + augend
    • add

      public BigDecimal add(BigDecimal augend,MathContext mc)
      Returns aBigDecimal 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.
      Parameters:
      augend - value to be added to thisBigDecimal.
      mc - the context to use.
      Returns:
      this + augend, rounded as necessary.
      Since:
      1.5
    • subtract

      public BigDecimal subtract(BigDecimal subtrahend)
      Returns aBigDecimal whose value is(this - subtrahend), and whose scale ismax(this.scale(), subtrahend.scale()).
      Parameters:
      subtrahend - value to be subtracted from thisBigDecimal.
      Returns:
      this - subtrahend
    • subtract

      public BigDecimal subtract(BigDecimal subtrahend,MathContext mc)
      Returns aBigDecimal whose value is(this - subtrahend), with rounding according to the context settings. Ifsubtrahend is zero then this, rounded if necessary, is used as the result. If this is zero then the result issubtrahend.negate(mc).
      Parameters:
      subtrahend - value to be subtracted from thisBigDecimal.
      mc - the context to use.
      Returns:
      this - subtrahend, rounded as necessary.
      Since:
      1.5
    • multiply

      public BigDecimal multiply(BigDecimal multiplicand)
      Returns aBigDecimal whose value is(this × multiplicand), and whose scale is(this.scale() + multiplicand.scale()).
      Parameters:
      multiplicand - value to be multiplied by thisBigDecimal.
      Returns:
      this * multiplicand
    • multiply

      public BigDecimal multiply(BigDecimal multiplicand,MathContext mc)
      Returns aBigDecimal whose value is(this × multiplicand), with rounding according to the context settings.
      Parameters:
      multiplicand - value to be multiplied by thisBigDecimal.
      mc - the context to use.
      Returns:
      this * multiplicand, rounded as necessary.
      Since:
      1.5
    • divide

      @Deprecated(since="9")public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
      Deprecated.
      The methoddivide(BigDecimal, int, RoundingMode) should be used in preference to this legacy method.
      Returns aBigDecimal 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.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      scale - scale of theBigDecimal quotient to be returned.
      roundingMode - rounding mode to apply.
      Returns:
      this / divisor
      Throws:
      ArithmeticException - ifdivisor is zero,roundingMode==ROUND_UNNECESSARY and the specified scale is insufficient to represent the result of the division exactly.
      IllegalArgumentException - ifroundingMode does not represent a valid rounding mode.
      See Also:
    • divide

      public BigDecimal divide(BigDecimal divisor, int scale,RoundingMode roundingMode)
      Returns aBigDecimal 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.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      scale - scale of theBigDecimal quotient to be returned.
      roundingMode - rounding mode to apply.
      Returns:
      this / divisor
      Throws:
      ArithmeticException - ifdivisor is zero,roundingMode==RoundingMode.UNNECESSARY and the specified scale is insufficient to represent the result of the division exactly.
      Since:
      1.5
    • divide

      @Deprecated(since="9")public BigDecimal divide(BigDecimal divisor, int roundingMode)
      Deprecated.
      The methoddivide(BigDecimal, RoundingMode) should be used in preference to this legacy method.
      Returns aBigDecimal whose value is(this / divisor), and whose scale isthis.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      roundingMode - rounding mode to apply.
      Returns:
      this / divisor
      Throws:
      ArithmeticException - ifdivisor==0, orroundingMode==ROUND_UNNECESSARY andthis.scale() is insufficient to represent the result of the division exactly.
      IllegalArgumentException - ifroundingMode does not represent a valid rounding mode.
      See Also:
    • divide

      public BigDecimal divide(BigDecimal divisor,RoundingMode roundingMode)
      Returns aBigDecimal whose value is(this / divisor), and whose scale isthis.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      roundingMode - rounding mode to apply.
      Returns:
      this / divisor
      Throws:
      ArithmeticException - ifdivisor==0, orroundingMode==RoundingMode.UNNECESSARY andthis.scale() is insufficient to represent the result of the division exactly.
      Since:
      1.5
    • divide

      public BigDecimal divide(BigDecimal divisor)
      Returns aBigDecimal 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) anArithmeticException is thrown.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      Returns:
      this / divisor
      Throws:
      ArithmeticException - if the exact quotient does not have a terminating decimal expansion, including dividing by zero
      Since:
      1.5
    • divide

      public BigDecimal divide(BigDecimal divisor,MathContext mc)
      Returns aBigDecimal whose value is(this / divisor), with rounding according to the context settings.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      mc - the context to use.
      Returns:
      this / divisor, rounded as necessary.
      Throws:
      ArithmeticException - if the result is inexact but the rounding mode isUNNECESSARY ormc.precision == 0 and the quotient has a non-terminating decimal expansion, including dividing by zero
      Since:
      1.5
    • divideToIntegralValue

      public BigDecimal divideToIntegralValue(BigDecimal divisor)
      Returns aBigDecimal whose value is the integer part of the quotient(this / divisor) rounded down. The preferred scale of the result is(this.scale() - divisor.scale()).
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      Returns:
      The integer part ofthis / divisor.
      Throws:
      ArithmeticException - ifdivisor==0
      Since:
      1.5
    • divideToIntegralValue

      public BigDecimal divideToIntegralValue(BigDecimal divisor,MathContext mc)
      Returns aBigDecimal 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() - divisor.scale()). AnArithmeticException is thrown if the integer part of the exact quotient needs more thanmc.precision digits.
      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      mc - the context to use.
      Returns:
      The integer part ofthis / divisor.
      Throws:
      ArithmeticException - ifdivisor==0
      ArithmeticException - ifmc.precision > 0 and the result requires a precision of more thanmc.precision digits.
      Since:
      1.5
    • remainder

      public BigDecimal remainder(BigDecimal divisor)
      Returns aBigDecimal whose value is(this % divisor).

      The remainder is given bythis.subtract(this.divideToIntegralValue(divisor).multiply(divisor)). Note that this isnot the modulo operation (the result can be negative).

      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      Returns:
      this % divisor.
      Throws:
      ArithmeticException - ifdivisor==0
      Since:
      1.5
    • remainder

      public BigDecimal remainder(BigDecimal divisor,MathContext mc)
      Returns aBigDecimal whose value is(this % divisor), with rounding according to the context settings. TheMathContext settings affect the implicit divide used to compute the remainder. The remainder computation itself is by definition exact. Therefore, the remainder may contain more thanmc.getPrecision() digits.

      The remainder is given bythis.subtract(this.divideToIntegralValue(divisor, mc).multiply(divisor)). Note that this is not the modulo operation (the result can be negative).

      Parameters:
      divisor - value by which thisBigDecimal is to be divided.
      mc - the context to use.
      Returns:
      this % divisor, rounded as necessary.
      Throws:
      ArithmeticException - ifdivisor==0
      ArithmeticException - if the result is inexact but the rounding mode isUNNECESSARY, ormc.precision > 0 and the result ofthis.divideToIntegralValue(divisor) would require a precision of more thanmc.precision digits.
      Since:
      1.5
      See Also:
    • divideAndRemainder

      public BigDecimal[] divideAndRemainder(BigDecimal divisor)
      Returns a two-elementBigDecimal array containing the result ofdivideToIntegralValue followed by the result ofremainder on the two operands.

      Note that if both the integer quotient and remainder are needed, this method is faster than using thedivideToIntegralValue andremainder methods separately because the division need only be carried out once.

      Parameters:
      divisor - value by which thisBigDecimal is to be divided, and the remainder computed.
      Returns:
      a two elementBigDecimal array: the quotient (the result ofdivideToIntegralValue) is the initial element and the remainder is the final element.
      Throws:
      ArithmeticException - ifdivisor==0
      Since:
      1.5
      See Also:
    • divideAndRemainder

      public BigDecimal[] divideAndRemainder(BigDecimal divisor,MathContext mc)
      Returns a two-elementBigDecimal array containing the result ofdivideToIntegralValue followed by the result ofremainder 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 faster than using thedivideToIntegralValue andremainder methods separately because the division need only be carried out once.

      Parameters:
      divisor - value by which thisBigDecimal is to be divided, and the remainder computed.
      mc - the context to use.
      Returns:
      a two elementBigDecimal array: the quotient (the result ofdivideToIntegralValue) is the initial element and the remainder is the final element.
      Throws:
      ArithmeticException - ifdivisor==0
      ArithmeticException - if the result is inexact but the rounding mode isUNNECESSARY, ormc.precision > 0 and the result ofthis.divideToIntegralValue(divisor) would require a precision of more thanmc.precision digits.
      Since:
      1.5
      See Also:
    • sqrt

      public BigDecimal sqrt(MathContext mc)
      Returns an approximation to the square root ofthis with rounding according to the context settings.

      The preferred scale of the returned result is equal tothis.scale()/2. The value of the returned result is always within one ulp of the exact decimal value for the precision in question. If the rounding mode isHALF_UP,HALF_DOWN, orHALF_EVEN, the result is within one half an ulp of the exact decimal value.

      Special case:

      • The square root of a number numerically equal to ZERO is numerically equal toZERO with a preferred scale according to the general rule above. In particular, forZERO,ZERO.sqrt(mc).equals(ZERO) is true with anyMathContext as an argument.

      Parameters:
      mc - the context to use.
      Returns:
      the square root ofthis.
      Throws:
      ArithmeticException - ifthis is less than zero.
      ArithmeticException - if an exact result is requested (mc.getPrecision()==0) and there is no finite decimal expansion of the exact result
      ArithmeticException - if(mc.getRoundingMode()==RoundingMode.UNNECESSARY) and the exact result cannot fit inmc.getPrecision() digits.
      Since:
      9
      See Also:
    • pow

      public BigDecimal pow(int n)
      Returns aBigDecimal whose value is(thisn), The power is computed exactly, to unlimited precision.

      The parametern must be in the range 0 through 999999999, inclusive.ZERO.pow(0) returnsONE. Note that future releases may expand the allowable exponent range of this method.

      Parameters:
      n - power to raise thisBigDecimal to.
      Returns:
      thisn
      Throws:
      ArithmeticException - ifn is out of range.
      Since:
      1.5
    • pow

      public BigDecimal pow(int n,MathContext mc)
      Returns aBigDecimal 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 chosen precision. Note that future releases may use a different algorithm with a decreased allowable error bound and increased allowable exponent range.

      The X3.274-1996 algorithm is:

      • AnArithmeticException exception is thrown if
        • abs(n) > 999999999
        • mc.precision == 0 andn < 0
        • mc.precision > 0 andn has more thanmc.precision decimal digits
      • ifn is zero,ONE is returned even ifthis is zero, otherwise
        • ifn is positive, the result is calculated via the repeated squaring technique into a single accumulator. The individual multiplications with the accumulator use the same math context settings as inmc except for a precision increased tomc.precision + elength + 1 whereelength is the number of decimal digits inn.
        • ifn is negative, the result is calculated as ifn were positive; this value is then divided into one using the working precision specified above.
        • The final value from either the positive or negative case is then rounded to the destination precision.

      Parameters:
      n - power to raise thisBigDecimal to.
      mc - the context to use.
      Returns:
      thisn using the ANSI standard X3.274-1996 algorithm
      Throws:
      ArithmeticException - if the result is inexact but the rounding mode isUNNECESSARY, orn is out of range.
      Since:
      1.5
    • abs

      public BigDecimal abs()
      Returns aBigDecimal whose value is the absolute value of thisBigDecimal, and whose scale isthis.scale().
      Returns:
      abs(this)
    • abs

      public BigDecimal abs(MathContext mc)
      Returns aBigDecimal whose value is the absolute value of thisBigDecimal, with rounding according to the context settings.
      Parameters:
      mc - the context to use.
      Returns:
      abs(this), rounded as necessary.
      Since:
      1.5
    • negate

      public BigDecimal negate()
      Returns aBigDecimal whose value is(-this), and whose scale isthis.scale().
      Returns:
      -this.
    • negate

      public BigDecimal negate(MathContext mc)
      Returns aBigDecimal whose value is(-this), with rounding according to the context settings.
      Parameters:
      mc - the context to use.
      Returns:
      -this, rounded as necessary.
      Since:
      1.5
    • plus

      public BigDecimal plus()
      Returns aBigDecimal whose value is(+this), and whose scale isthis.scale().

      This method, which simply returns thisBigDecimal is included for symmetry with the unary minus methodnegate().

      Returns:
      this.
      Since:
      1.5
      See Also:
    • plus

      public BigDecimal plus(MathContext mc)
      Returns aBigDecimal whose value is(+this), with rounding according to the context settings.

      The effect of this method is identical to that of theround(MathContext) method.

      Parameters:
      mc - the context to use.
      Returns:
      this, rounded as necessary. A zero result will have a scale of 0.
      Since:
      1.5
      See Also:
    • signum

      public int signum()
      Returns the signum function of thisBigDecimal.
      Returns:
      -1, 0, or 1 as the value of thisBigDecimal is negative, zero, or positive.
    • scale

      public int scale()
      Returns thescale of thisBigDecimal. 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 value is multiplied by 1000.
      Returns:
      the scale of thisBigDecimal.
    • precision

      public int precision()
      Returns theprecision of thisBigDecimal. (The precision is the number of digits in the unscaled value.)

      The precision of a zero value is 1.

      Returns:
      the precision of thisBigDecimal.
      Since:
      1.5
    • unscaledValue

      public BigInteger unscaledValue()
      Returns aBigInteger whose value is theunscaled value of thisBigDecimal. (Computes(this * 10this.scale()).)
      Returns:
      the unscaled value of thisBigDecimal.
      Since:
      1.2
    • round

      public BigDecimal round(MathContext mc)
      Returns aBigDecimal rounded according to theMathContext settings. If the precision setting is 0 then no rounding takes place.

      The effect of this method is identical to that of theplus(MathContext) method.

      Parameters:
      mc - the context to use.
      Returns:
      aBigDecimal rounded according to theMathContext settings.
      Since:
      1.5
      See Also:
    • setScale

      public BigDecimal setScale(int newScale,RoundingMode roundingMode)
      Returns aBigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing thisBigDecimal'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 be divided (rather than multiplied), and the value may be changed; in this case, the specified rounding mode is applied to the division.
      API Note:
      Since BigDecimal objects are immutable, calls of this method donot result in the original object being modified, contrary to the usual convention of having methods namedsetX mutate fieldX. Instead,setScale returns an object with the proper scale; the returned object may or may not be newly allocated.
      Parameters:
      newScale - scale of theBigDecimal value to be returned.
      roundingMode - The rounding mode to apply.
      Returns:
      aBigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing thisBigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
      Throws:
      ArithmeticException - ifroundingMode==UNNECESSARY and the specified scaling operation would require rounding.
      Since:
      1.5
      See Also:
    • setScale

      @Deprecated(since="9")public BigDecimal setScale(int newScale, int roundingMode)
      Deprecated.
      The methodsetScale(int, RoundingMode) should be used in preference to this legacy method.
      Returns aBigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing thisBigDecimal'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 be divided (rather than multiplied), and the value may be changed; in this case, the specified rounding mode is applied to the division.
      API Note:
      Since BigDecimal objects are immutable, calls of this method donot result in the original object being modified, contrary to the usual convention of having methods namedsetX mutate fieldX. Instead,setScale returns an object with the proper scale; the returned object may or may not be newly allocated.
      Parameters:
      newScale - scale of theBigDecimal value to be returned.
      roundingMode - The rounding mode to apply.
      Returns:
      aBigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing thisBigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
      Throws:
      ArithmeticException - ifroundingMode==ROUND_UNNECESSARY and the specified scaling operation would require rounding.
      IllegalArgumentException - ifroundingMode does not represent a valid rounding mode.
      See Also:
    • setScale

      public BigDecimal setScale(int newScale)
      Returns aBigDecimal whose scale is the specified value, and whose value is numerically equal to thisBigDecimal's. Throws anArithmeticException if this is not possible.

      This call is typically used to increase the scale, in which case it is guaranteed that there exists aBigDecimal of the specified scale and the correct value. The call can also be used to reduce the scale if the caller knows that theBigDecimal 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 changing its value.

      This method returns the same result as the two-argument versions ofsetScale, but saves the caller the trouble of specifying a rounding mode in cases where it is irrelevant.

      API Note:
      SinceBigDecimal objects are immutable, calls of this method donot result in the original object being modified, contrary to the usual convention of having methods namedsetX mutate fieldX. Instead,setScale returns an object with the proper scale; the returned object may or may not be newly allocated.
      Parameters:
      newScale - scale of theBigDecimal value to be returned.
      Returns:
      aBigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing thisBigDecimal's unscaled value by the appropriate power of ten to maintain its overall value.
      Throws:
      ArithmeticException - if the specified scaling operation would require rounding.
      See Also:
    • movePointLeft

      public BigDecimal movePointLeft(int n)
      Returns aBigDecimal which is equivalent to this one with the decimal point movedn places to the left. Ifn is non-negative, the call merely addsn to the scale. Ifn is negative, the call is equivalent tomovePointRight(-n). TheBigDecimal returned by this call has value(this × 10-n) and scalemax(this.scale()+n, 0).
      Parameters:
      n - number of places to move the decimal point to the left.
      Returns:
      aBigDecimal which is equivalent to this one with the decimal point movedn places to the left.
      Throws:
      ArithmeticException - if scale overflows.
    • movePointRight

      public BigDecimal movePointRight(int n)
      Returns aBigDecimal which is equivalent to this one with the decimal point movedn places to the right. Ifn is non-negative, the call merely subtractsn from the scale. Ifn is negative, the call is equivalent tomovePointLeft(-n). TheBigDecimal returned by this call has value(this × 10n) and scalemax(this.scale()-n, 0).
      Parameters:
      n - number of places to move the decimal point to the right.
      Returns:
      aBigDecimal which is equivalent to this one with the decimal point movedn places to the right.
      Throws:
      ArithmeticException - if scale overflows.
    • scaleByPowerOfTen

      public BigDecimal scaleByPowerOfTen(int n)
      Returns a BigDecimal whose numerical value is equal to (this * 10n). The scale of the result is(this.scale() - n).
      Parameters:
      n - the exponent power of ten to scale by
      Returns:
      a BigDecimal whose numerical value is equal to (this * 10n)
      Throws:
      ArithmeticException - if the scale would be outside the range of a 32-bit integer.
      Since:
      1.5
    • stripTrailingZeros

      public BigDecimal stripTrailingZeros()
      Returns aBigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. For example, stripping the trailing zeros from theBigDecimal value600.0, which has [BigInteger,scale] components equal to [6000, 1], yields6E2 with [BigInteger,scale] components equal to [6, -2]. If this BigDecimal is numerically equal to zero, thenBigDecimal.ZERO is returned.
      Returns:
      a numerically equalBigDecimal with any trailing zeros removed.
      Throws:
      ArithmeticException - if scale overflows.
      Since:
      1.5
    • compareTo

      public int compareTo(BigDecimal val)
      Compares thisBigDecimal numerically with the specifiedBigDecimal. TwoBigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. Such values are in the samecohort. 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.
      Specified by:
      compareTo in interface Comparable<BigDecimal>
      API Note:
      Note: this class has a natural ordering that is inconsistent with equals. The behavior of comparing the result of this method for equality to 0 is analogous to checking thenumerical equality ofdouble values.
      Parameters:
      val -BigDecimal to which thisBigDecimal is to be compared.
      Returns:
      -1, 0, or 1 as thisBigDecimal is numerically less than, equal to, or greater thanval.
    • equals

      public boolean equals(Object x)
      Compares thisBigDecimal with the specified Object for equality. UnlikecompareTo, this method considers twoBigDecimal objects equal only if they are equal in value and scale. Therefore 2.0 is not equal to 2.00 when compared by this method since the former has [BigInteger,scale] components equal to [20, 1] while the latter has components equal to [200, 2].
      Overrides:
      equals in class Object
      API Note:
      One example that shows how 2.0 and 2.00 arenot substitutable for each other under some arithmetic operations are the two expressions:
      new BigDecimal("2.0" ).divide(BigDecimal.valueOf(3), HALF_UP) which evaluates to 0.7 and
      new BigDecimal("2.00").divide(BigDecimal.valueOf(3), HALF_UP) which evaluates to 0.67. The behavior of this method is analogous to checking therepresentation equivalence ofdouble values.
      Parameters:
      x -Object to which thisBigDecimal is to be compared.
      Returns:
      true if and only if the specifiedObject is aBigDecimal whose value and scale are equal to thisBigDecimal's.
      See Also:
    • min

      public BigDecimal min(BigDecimal val)
      Returns the minimum of thisBigDecimal andval.
      Parameters:
      val - value with which the minimum is to be computed.
      Returns:
      theBigDecimal whose value is the lesser of thisBigDecimal andval. If they are equal, as defined by thecompareTo method,this is returned.
      See Also:
    • max

      public BigDecimal max(BigDecimal val)
      Returns the maximum of thisBigDecimal andval.
      Parameters:
      val - value with which the maximum is to be computed.
      Returns:
      theBigDecimal whose value is the greater of thisBigDecimal andval. If they are equal, as defined by thecompareTo method,this is returned.
      See Also:
    • hashCode

      public int hashCode()
      Returns the hash code for thisBigDecimal. The hash code is computed as a function of theunscaled value and thescale of thisBigDecimal.
      Overrides:
      hashCode in class Object
      API Note:
      TwoBigDecimal objects that are numerically equal but differ in scale (like 2.0 and 2.00) will generallynot have the same hash code.
      Returns:
      hash code for thisBigDecimal.
      See Also:
    • toString

      public String toString()
      Returns the string representation of thisBigDecimal, using scientific notation if an exponent is needed.

      A standard canonical string form of theBigDecimal is created as though by the following steps: first, the absolute value of the unscaled value of theBigDecimal is converted to a string in base ten using the characters'0' through'9' with no leading zeros (except if its value is zero, in which case a single'0' character is used).

      Next, anadjusted exponent is calculated; this is the negated scale, plus the number of characters in the converted unscaled value, less one. That is,-scale+(ulength-1), whereulength is the length of the absolute value of the unscaled value in decimal digits (itsprecision).

      If the scale is greater than or equal to zero and the adjusted exponent is greater than or equal to-6, the number will be converted to a character form without using exponential notation. In this case, if the scale is zero then no decimal point is added and if the scale is positive a decimal point will be inserted with the scale specifying the number of characters to the right of the decimal point.'0' characters are added to the left of the converted unscaled value as necessary. If no character precedes the decimal point after this insertion then a conventional'0' character is prefixed.

      Otherwise (that is, if the scale is negative, or the adjusted exponent is less than-6), the number will be converted to a character form using exponential notation. In this case, if the convertedBigInteger has more than one digit a decimal point is inserted after the first digit. An exponent in character form is then suffixed to the converted unscaled value (perhaps with inserted decimal point); this comprises the letter'E' followed immediately by the adjusted exponent converted to a character form. The latter is in base ten, using the characters'0' through'9' with no leading zeros, and is always prefixed by a sign character'-' ('\u002D') if the adjusted exponent is negative,'+' ('\u002B') otherwise).

      Finally, the entire string is prefixed by a minus sign character'-' ('\u002D') if the unscaled value is less than zero. No sign character is prefixed if the unscaled value is zero or positive.

      Examples:

      For each representation [unscaled value,scale] on the left, the resulting string is shown on the right.

       [123,0]      "123" [-123,0]     "-123" [123,-1]     "1.23E+3" [123,-3]     "1.23E+5" [123,1]      "12.3" [123,5]      "0.00123" [123,10]     "1.23E-8" [-123,12]    "-1.23E-10"
      Notes:
      1. There is a one-to-one mapping between the distinguishableBigDecimal values and the result of this conversion. That is, every distinguishableBigDecimal value (unscaled value and scale) has a unique string representation as a result of usingtoString. If that string representation is converted back to aBigDecimal using theBigDecimal(String) constructor, then the original value will be recovered.
      2. The string produced for a given number is always the same; it is not affected by locale. This means that it can be used as a canonical string representation for exchanging decimal data, or as a key for a Hashtable, etc. Locale-sensitive number formatting and parsing is handled by theNumberFormat class and its subclasses.
      3. ThetoEngineeringString() method may be used for presenting numbers with exponents in engineering notation, and thesetScale method may be used for rounding aBigDecimal so it has a known number of digits after the decimal point.
      4. The digit-to-character mapping provided byCharacter.forDigit is used.

      Overrides:
      toString in class Object
      Returns:
      string representation of thisBigDecimal.
      See Also:
    • toEngineeringString

      public String toEngineeringString()
      Returns a string representation of thisBigDecimal, using engineering notation if an exponent is needed.

      Returns a string that represents theBigDecimal as described in thetoString() method, except that if exponential notation is used, the power of ten is adjusted to be a multiple of three (engineering notation) such that the integer part of nonzero values will be in the range 1 through 999. If exponential notation is used for zero values, a decimal point and one or two fractional zero digits are used so that the scale of the zero value is preserved. Note that unlike the output oftoString(), the output of this method isnot guaranteed to recover the same [integer, scale] pair of thisBigDecimal if the output string is converting back to aBigDecimal using thestring constructor. The result of this method meets the weaker constraint of always producing a numerically equal result from applying the string constructor to the method's output.

      Returns:
      string representation of thisBigDecimal, using engineering notation if an exponent is needed.
      Since:
      1.5
    • toPlainString

      public String toPlainString()
      Returns a string representation of thisBigDecimal 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 value were converted to a numerically equal value with zero scale and as if all the trailing zeros of the zero scale value were present in the result. The entire string is prefixed by a minus sign character '-' ('\u002D') if the unscaled value is less than zero. No sign character is prefixed if the unscaled value is zero or positive. Note that if the result of this method is passed to thestring constructor, only the numerical value of thisBigDecimal will necessarily be recovered; the representation of the newBigDecimal may have a different scale. In particular, if thisBigDecimal has a negative scale, the string resulting from this method will have a scale of zero when processed by the string constructor. (This method behaves analogously to thetoString method in 1.4 and earlier releases.)
      Returns:
      a string representation of thisBigDecimal without an exponent field.
      Since:
      1.5
      See Also:
    • toBigInteger

      public BigInteger toBigInteger()
      Converts thisBigDecimal to aBigInteger. This conversion is analogous to thenarrowing primitive conversion fromdouble tolong as defined inThe Java Language Specification: any fractional part of thisBigDecimal will be discarded. Note that this conversion can lose information about the precision of theBigDecimal value.

      To have an exception thrown if the conversion is inexact (in other words if a nonzero fractional part is discarded), use thetoBigIntegerExact() method.

      Returns:
      thisBigDecimal converted to aBigInteger.
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • toBigIntegerExact

      public BigInteger toBigIntegerExact()
      Converts thisBigDecimal to aBigInteger, checking for lost information. An exception is thrown if thisBigDecimal has a nonzero fractional part.
      Returns:
      thisBigDecimal converted to aBigInteger.
      Throws:
      ArithmeticException - ifthis has a nonzero fractional part.
      Since:
      1.5
    • longValue

      public long longValue()
      Converts thisBigDecimal to along. This conversion is analogous to thenarrowing primitive conversion fromdouble toshort as defined inThe Java Language Specification: any fractional part of thisBigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in along, only the low-order 64 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of thisBigDecimal value as well as return a result with the opposite sign.
      Specified by:
      longValue in class Number
      Returns:
      thisBigDecimal converted to along.
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • longValueExact

      public long longValueExact()
      Converts thisBigDecimal to along, checking for lost information. If thisBigDecimal has a nonzero fractional part or is out of the possible range for along result then anArithmeticException is thrown.
      Returns:
      thisBigDecimal converted to along.
      Throws:
      ArithmeticException - ifthis has a nonzero fractional part, or will not fit in along.
      Since:
      1.5
    • intValue

      public int intValue()
      Converts thisBigDecimal to anint. This conversion is analogous to thenarrowing primitive conversion fromdouble toshort as defined inThe Java Language Specification: any fractional part of thisBigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in anint, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude and precision of thisBigDecimal value as well as return a result with the opposite sign.
      Specified by:
      intValue in class Number
      Returns:
      thisBigDecimal converted to anint.
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • intValueExact

      public int intValueExact()
      Converts thisBigDecimal to anint, checking for lost information. If thisBigDecimal has a nonzero fractional part or is out of the possible range for anint result then anArithmeticException is thrown.
      Returns:
      thisBigDecimal converted to anint.
      Throws:
      ArithmeticException - ifthis has a nonzero fractional part, or will not fit in anint.
      Since:
      1.5
    • shortValueExact

      public short shortValueExact()
      Converts thisBigDecimal to ashort, checking for lost information. If thisBigDecimal has a nonzero fractional part or is out of the possible range for ashort result then anArithmeticException is thrown.
      Returns:
      thisBigDecimal converted to ashort.
      Throws:
      ArithmeticException - ifthis has a nonzero fractional part, or will not fit in ashort.
      Since:
      1.5
    • byteValueExact

      public byte byteValueExact()
      Converts thisBigDecimal to abyte, checking for lost information. If thisBigDecimal has a nonzero fractional part or is out of the possible range for abyte result then anArithmeticException is thrown.
      Returns:
      thisBigDecimal converted to abyte.
      Throws:
      ArithmeticException - ifthis has a nonzero fractional part, or will not fit in abyte.
      Since:
      1.5
    • floatValue

      public float floatValue()
      Converts thisBigDecimal to afloat. This conversion is similar to thenarrowing primitive conversion fromdouble tofloat as defined inThe Java Language Specification: if thisBigDecimal has too great a magnitude to represent as afloat, it will be converted toFloat.NEGATIVE_INFINITY orFloat.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of theBigDecimal value.
      Specified by:
      floatValue in class Number
      Returns:
      thisBigDecimal converted to afloat.
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • doubleValue

      public double doubleValue()
      Converts thisBigDecimal to adouble. This conversion is similar to thenarrowing primitive conversion fromdouble tofloat as defined inThe Java Language Specification: if thisBigDecimal has too great a magnitude represent as adouble, it will be converted toDouble.NEGATIVE_INFINITY orDouble.POSITIVE_INFINITY as appropriate. Note that even when the return value is finite, this conversion can lose information about the precision of theBigDecimal value.
      Specified by:
      doubleValue in class Number
      Returns:
      thisBigDecimal converted to adouble.
      SeeJava Language Specification:
      5.1.3 Narrowing Primitive Conversion
    • ulp

      public BigDecimal ulp()
      Returns the size of an ulp, a unit in the last place, of thisBigDecimal. An ulp of a nonzeroBigDecimal value is the positive distance between this value and theBigDecimal value next larger in magnitude with the same number of digits. An ulp of a zero value is numerically equal to 1 with the scale ofthis. The result is stored with the same scale asthis so the result for zero and nonzero values is equal to[1, this.scale()].
      Returns:
      the size of an ulp ofthis
      Since:
      1.5