Returns a BigDecimal
whose value is the absolute value
of this BigDecimal
, with rounding according to the
context settings.
the context to use.
absolute value, rounded as necessary.
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.
value to be added to this BigDecimal
.
the context to use.
this + augend
, rounded as necessary.
Compares this BigDecimal
numerically 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. Such values are in the
same cohort.
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.
BigDecimal
to which this BigDecimal
is
to be compared.
-1, 0, or 1 as this BigDecimal
is numerically
less than, equal to, or greater than val
.
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.
value by which this BigDecimal
is to be divided.
scale of the BigDecimal
quotient to be returned.
rounding mode to apply.
this / divisor
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 quotient and remainder are
needed, this method is faster than using the
divideToIntegralValue
and remainder
methods
separately because the division need only be carried out once.
value by which this BigDecimal
is to be divided,
and the remainder computed.
the context to use.
a two element BigDecimal
array: the quotient
(the result of divideToIntegralValue
) is the
initial element and the remainder is the final element.
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() - divisor.scale())
. A
RangeError
is thrown if the integer part of
the exact quotient needs more than mc.precision
digits.
value by which this BigDecimal
is to be divided.
the context to use.
The integer part of this / divisor
.
Returns a BigDecimal
whose value is (this / divisor)
, with rounding according to the context settings.
value by which this BigDecimal
is to be
the context to use.
this / divisor
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. Therefore 2.0 is not equal to 2.00 when compared by this
method since the former has [BigInt
, scale
]
components equal to [20, 1] while the latter has components
equal to [200, 2].
One example that shows how 2.0 and 2.00 are not substitutable for each other under some arithmetic operations are the two expressions:
to which this BigDecimal
is
to be compared.
true if and only if the specified value is a BigDecimal whose value and scale are equal to this BigDecimal's.
Returns the maximum of this BigDecimal
and val
.
value with which the maximum is to be computed.
the BigDecimal
whose value is the greater of this
BigDecimal
and val
. If they are equal,
as defined by the compareTo
method, this
is returned.
Returns the minimum of this BigDecimal
and val
.
value with which the minimum is to be computed.
the BigDecimal
whose value is the lesser of this
BigDecimal
and val
. If they are equal,
as defined by the compareTo
method, this
is returned.
Returns a BigDecimal
which is equivalent to this one
with the decimal point moved n
places to the left. If
n
is non-negative, the call merely adds n
to
the scale. If n
is negative, the call is equivalent
to movePointRight(-n)
. The BigDecimal
returned by this call has value (this ×
10-n)
and scale max(this.scale()+n, 0)
.
number of places to move the decimal point to the left.
a BigDecimal
which is equivalent to this one with the
decimal point moved n
places to the left.
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 (this
× 10n)
and scale max(this.scale()-n, 0)
.
number of places to move the decimal point to the right.
a BigDecimal
which is equivalent to this one
with the decimal point moved n
places to the right.
Returns a BigDecimal
whose value is (this ×
multiplicand)
, with rounding according to the context settings.
value to be multiplied by this BigDecimal
.
the context to use.
this * multiplicand
, rounded as necessary.
Returns a BigDecimal
whose value is (-this)
,
with rounding according to the context settings.
the context to use.
-this
, rounded as necessary.
Converts this BigDecimal to number.
number for of this BigDecimal
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 method.
the context to use.
this
, rounded as necessary. A zero result will
have a scale of 0.
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 chosen precision.
The X3.274-1996 algorithm is:
An RangeError
exception is thrown if
abs(n)
> 999999999}mc.precision == 0
and n < 0
mc.precision > 0
and n
has more than
mc.precision
decimal digitsif n
is zero, a BigDecimal with value 1 is returned even if
this
is zero, otherwise
if n
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 in mc
except for a
precision increased to mc.precision + elength + 1
where elength
is the number of decimal digits in
n
.
if n
is negative, the result is calculated as if
n
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.
power to raise this BigDecimal
to.
the context to use.
thisn
using the ANSI standard X3.274-1996
algorithm
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 more than mc.getPrecision()
digits.
The remainder is given by
this.subtract(this.divideToIntegralValue(divisor, mc).multiply(divisor))
. Note that this is not the modulo
operation (the result can be negative).
value by which this BigDecimal
is to be divided.
the context to use.
this % divisor
, rounded as necessary.
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 method.
the context to use.
a BigDecimal
rounded according to the
MathContext
settings.
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
value is multiplied by 1000.
The scale will be kept in the integer range, if cannot error will be thrown.
the scale of this BigDecimal
.
Returns a BigDecimal whose numerical value is equal to
(this
* 10n). The scale of
the result is (this.scale() - n)
.
the exponent power of ten to scale by
a BigDecimal whose numerical value is equal to
(this
* 10n)
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 be
divided (rather than multiplied), and the value may be changed;
in this case, the specified rounding mode is applied to the
division.
scale of the BigDecimal
value to be returned.
The rounding mode to apply. By default it is set to UNNECESSARY
.
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.
Returns the signum function of this BigDecimal
.
-1, 0, or 1 as the value of this BigDecimal
is negative, zero, or positive.
Returns an approximation to the square root of this
with rounding according to the context settings.
The preferred scale of the returned result is equal to
this.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 is RoundingMode.HALF_UP, RoundingMode.HALF_DOWN,
or RoundingMode.HALF_EVEN, the
result is within one half an ulp of the exact decimal value.
the context to use.
the square root of this
.
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
[BigInt
, scale
] components equal to
[6000n, 1], yields 6E2
with [BigInt
, scale
]
components equal to [6n, -2].
a numerically equal BigDecimal
with any
trailing zeros removed.
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)
.
value to be subtracted from this BigDecimal
.
the context to use.
this - subtrahend
, rounded as necessary.
Converts this BigDecimal
to a BigInt
.
Any fractional part of this will be discarded. Note that this
conversion can lose information about the precision of the
BigDecimal
value.
To have an exception thrown if the conversion is inexact (in other words if a nonzero fractional part is discarded), use the toBigIntExact method.
this BigDecimal
converted to a BigInt
.
Converts this BigDecimal
to a BigInt
,
checking for lost information. An exception is thrown if this
BigDecimal
has a nonzero fractional part.
this BigDecimal
converted to a BigInt
.
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 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 of toString, the output of this
method is not guaranteed to recover the same [number,
scale] pair of this BigDecimal
if the output string is
converting back to a BigDecimal
using the string 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.
string representation of this BigDecimal
, using
engineering notation if an exponent is needed.
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 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 the
string constructor, only the
numerical value of this BigDecimal
will necessarily be
recovered; the representation of the new BigDecimal
may have a different scale. In particular, if this
BigDecimal
has a negative scale, the string resulting
from this method will have a scale of zero when processed by
the string constructor.
a string representation of this BigDecimal
without an exponent field.
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 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, an adjusted 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)
, where ulength
is the
length of the absolute value of the unscaled value in decimal
digits (its precision).
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 converted BigInt
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:
There is a one-to-one mapping between the distinguishable
BigDecimal
values and the result of this conversion.
That is, every distinguishable BigDecimal
value
(unscaled value and scale) has a unique string representation
as a result of using toString
. If that string
representation is converted back to a BigDecimal
using
the string constructor, then the original
value will be recovered.
The toEngineeringString method may be used for
presenting numbers with exponents in engineering notation, and the
setScale method may be used for
rounding a BigDecimal
so it has a known number of digits after
the decimal point.
string representation of this BigDecimal
.
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 1 with the scale of this
. The result is
stored with the same scale as this
so the result
for zero and nonzero values is equal to [1, this.scale()]
.
the size of an ulp of this
Returns a BigInt
whose value is the unscaled
value of this BigDecimal
. (Computes (this *
10this.scale())
.)
the unscaled value of this BigDecimal
.
Generated using TypeDoc
BigInt based BigDecimal implementation. This class is ported from java.math.BigDecimal. The following documentation is adapted from openjdk/jdk repository.
Immutable, arbitrary-precision signed decimal numbers. A
BigDecimal
consists of an arbitrary precision number unscaled value and a scale. 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. The value of the number represented by theBigDecimal
is therefore(unscaledValue × 10-scale)
.The
BigDecimal
class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. The toString method provides a canonical representation of aBigDecimal
.The
BigDecimal
class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, aRangeError
is thrown; otherwise, calculations can be carried out to a chosen precision and rounding mode by supplying an appropriate MathContext object to the operation. In either case, eight rounding modes are provided for the control of rounding.When a
MathContext
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 aMathContext
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 non-terminating decimal expansion and the operation is specified to return an exact result, a RangeError 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 same cohort. The natural order of
BigDecimal
considers members of the same cohort to be equal to each other. In contrast, the equals method requires both the numerical value and representation to be the same for equality to hold. The results of methods like scale and unscaledValue 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 the
MathContext
'sprecision
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.
For methods and constructors with a
MathContext
parameter, if the result is inexact but the rounding mode is UNNECESSARY, a RangeError 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.
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 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 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 the floor rounding mode,19/100 = 0.19 // number=19, scale=2
but
21/110 = 0.190 // number=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 specified algorithm can occasionally differ from the rounded mathematical result by more than one unit in the last place, one 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 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 and movePointRight) return aBigDecimal
created from the operand by moving the decimal point a specified distance in the specified direction.As a number, the set of values for the scale is large, but bounded. If the scale of a result would exceed the range of a safe number, either by overflow or underflow, the operation may throw a RangerError.
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 "aBigDecimal
whose value is that of theBigDecimal
i
added to that of theBigDecimal
j
." The pseudo-code expression(i == j)
is shorthand for "true
if and only if theBigDecimal
i
represents the same value as theBigDecimal
j
." Other pseudo-code expressions are interpreted similarly. Square brackets are used to represent the particularBigInt
and scale pair defining aBigDecimal
value; for example [19, 2] is theBigDecimal
numerically equal to 0.19 having a scale of 2.Relation to IEEE 754 Decimal Arithmetic
Starting with its 2008 revision, the IEEE 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 a rounding policy. The rounding policy is called a rounding 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 a preferred scale/preferred exponent is also shared by both systems.For differences, IEEE 754 includes several kinds of values not modeled by
BigDecimal
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
's scale 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 the unscaled 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 by
BigDecimal
operations indicated by rounding 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 as decimal64 or decimal128 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 aMathContext
does not constrain the scale ofBigDecimal
results. Operations that would generate a NaN or exact infinity, such as dividing by zero, throw a RangeError inBigDecimal
arithmetic.