Constructor: |
public BigDecimal(char[] in) {
this(in, 0, in.length);
}
Translates a character array representation of a
{@code BigDecimal} into a {@code BigDecimal}, accepting the
same sequence of characters as the #BigDecimal(String)
constructor.
Note that if the sequence of characters is already available
as a character array, using this constructor is faster than
converting the {@code char} array to string and using the
{@code BigDecimal(String)} constructor . Parameters:
in - {@code char} array that is the source of characters.
Throws:
NumberFormatException - if {@code in} is not a valid
representation of a {@code BigDecimal}.
- since:
1.5 -
|
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
Translates the string representation of a {@code BigDecimal}
into a {@code BigDecimal}. The string representation consists
of an optional sign, {@code '+'} ( '\u002B') or
{@code '-'} ('\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 the
significand.
The exponent consists of the character {@code 'e'}
('\u0065') or {@code 'E'} ('\u0045')
followed by one or more decimal digits. The value of the
exponent must lie between -Integer#MAX_VALUE (Integer#MIN_VALUE +1) and Integer#MAX_VALUE , inclusive.
More formally, the strings this constructor accepts are
described by the following grammar:
- BigDecimalString:
- Signopt Significand Exponentopt
- Sign:
- {@code +}
- {@code -}
- Significand:
- IntegerPart {@code .} FractionPartopt
- {@code .} FractionPart
- IntegerPart
- IntegerPart:
- Digits
- FractionPart:
- Digits
- Exponent:
- ExponentIndicator SignedInteger
- ExponentIndicator:
- {@code e}
- {@code E}
- SignedInteger:
- Signopt Digits
- Digits:
- Digit
- Digits Digit
- Digit:
- any character for which Character#isDigit
returns {@code true}, including 0, 1, 2 ...
The scale of the returned {@code BigDecimal} 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 between {@code Integer.MIN_VALUE} and
{@code Integer.MAX_VALUE}, inclusive.
The character-to-digit mapping is provided by java.lang.Character#digit set to convert to radix 10. The
String may not contain any extraneous characters (whitespace,
for example).
Examples:
The value of the returned {@code BigDecimal} is equal to
significand × 10 exponent.
For each string on the left, the resulting representation
[{@code BigInteger}, {@code 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]
Note: For values other than {@code float} and
{@code double} NaN and ±Infinity, this constructor is
compatible with the values returned by Float#toString
and Double#toString . This is generally the preferred
way to convert a {@code float} or {@code double} into a
BigDecimal, as it doesn't suffer from the unpredictability of
the #BigDecimal(double) constructor. Parameters:
val - String representation of {@code BigDecimal}.
Throws:
NumberFormatException - if {@code val} is not a valid
representation of a {@code BigDecimal}.
|
public BigDecimal(double val) {
if (Double.isInfinite(val) || Double.isNaN(val))
throw new NumberFormatException("Infinite or NaN");
// Translate the double into sign, exponent and significand, according
// to the formulae in JLS, Section 20.10.22.
long valBits = Double.doubleToLongBits(val);
int sign = ((valBits > > 63)==0 ? 1 : -1);
int exponent = (int) ((valBits > > 52) & 0x7ffL);
long significand = (exponent==0 ? (valBits & ((1L< < 52) - 1)) < < 1
: (valBits & ((1L< < 52) - 1)) | (1L< < 52));
exponent -= 1075;
// At this point, val == sign * significand * 2**exponent.
/*
* Special case zero to supress nonterminating normalization
* and bogus scale calculation.
*/
if (significand == 0) {
intVal = BigInteger.ZERO;
intCompact = 0;
precision = 1;
return;
}
// Normalize
while((significand & 1) == 0) { // i.e., significand is even
significand > >= 1;
exponent++;
}
// Calculate intVal and scale
long s = sign * significand;
BigInteger b;
if (exponent < 0) {
b = BigInteger.valueOf(5).pow(-exponent).multiply(s);
scale = -exponent;
} else if (exponent > 0) {
b = BigInteger.valueOf(2).pow(exponent).multiply(s);
} else {
b = BigInteger.valueOf(s);
}
intCompact = compactValFor(b);
intVal = (intCompact != INFLATED) ? null : b;
}
Translates a {@code double} into a {@code BigDecimal} which
is the exact decimal representation of the {@code double}'s
binary floating-point value. The scale of the returned
{@code BigDecimal} is the smallest value such that
(10scale × val) is an integer.
Notes:
-
The results of this constructor can be somewhat unpredictable.
One might assume that writing {@code new BigDecimal(0.1)} in
Java creates a {@code BigDecimal} 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 a
{@code double} (or, for that matter, as a binary fraction of
any finite length). Thus, the value that is being passed
in to the constructor is not exactly equal to 0.1,
appearances notwithstanding.
-
The {@code String} constructor, on the other hand, is
perfectly predictable: writing {@code new BigDecimal("0.1")}
creates a {@code BigDecimal} which is exactly equal to
0.1, as one would expect. Therefore, it is generally
recommended that the {@linkplain #BigDecimal(String)
String constructor} be used in preference to this one.
-
When a {@code double} must be used as a source for a
{@code BigDecimal}, note that this constructor provides an
exact conversion; it does not give the same result as
converting the {@code double} to a {@code String} using the
Double#toString(double) method and then using the
#BigDecimal(String) constructor. To get that result,
use the {@code static} #valueOf(double) method.
Parameters:
val - {@code double} value to be converted to
{@code BigDecimal}.
Throws:
NumberFormatException - if {@code val} is infinite or NaN.
|
public BigDecimal(BigInteger val) {
intCompact = compactValFor(val);
intVal = (intCompact != INFLATED) ? null : val;
}
Translates a {@code BigInteger} into a {@code BigDecimal}.
The scale of the {@code BigDecimal} is zero. Parameters:
val - {@code BigInteger} value to be converted to
{@code BigDecimal}.
|
public BigDecimal(int val) {
intCompact = val;
}
Translates an {@code int} into a {@code BigDecimal}. The
scale of the {@code BigDecimal} is zero. Parameters:
val - {@code int} value to be converted to
{@code BigDecimal}.
- since:
1.5 -
|
public BigDecimal(long val) {
this.intCompact = val;
this.intVal = (val == INFLATED) ? BigInteger.valueOf(val) : null;
}
Translates a {@code long} into a {@code BigDecimal}. The
scale of the {@code BigDecimal} is zero. Parameters:
val - {@code long} value to be converted to {@code BigDecimal}.
- since:
1.5 -
|
public BigDecimal(char[] in,
MathContext mc) {
this(in, 0, in.length, mc);
}
Translates a character array representation of a
{@code BigDecimal} into a {@code BigDecimal}, accepting the
same sequence of characters as the #BigDecimal(String)
constructor and with rounding according to the context
settings.
Note that if the sequence of characters is already available
as a character array, using this constructor is faster than
converting the {@code char} array to string and using the
{@code BigDecimal(String)} constructor . Parameters:
in - {@code char} array that is the source of characters.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
NumberFormatException - if {@code in} is not a valid
representation of a {@code BigDecimal}.
- since:
1.5 -
|
public BigDecimal(String val,
MathContext mc) {
this(val.toCharArray(), 0, val.length());
if (mc.precision > 0)
roundThis(mc);
}
Translates the string representation of a {@code BigDecimal}
into a {@code BigDecimal}, accepting the same strings as the
#BigDecimal(String) constructor, with rounding
according to the context settings. Parameters:
val - string representation of a {@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
NumberFormatException - if {@code val} is not a valid
representation of a BigDecimal.
- since:
1.5 -
|
public BigDecimal(double val,
MathContext mc) {
this(val);
if (mc.precision > 0)
roundThis(mc);
}
Translates a {@code double} into a {@code BigDecimal}, with
rounding according to the context settings. The scale of the
{@code BigDecimal} is the smallest value such that
(10scale × val) is an integer.
The results of this constructor can be somewhat unpredictable
and its use is generally not recommended; see the notes under
the #BigDecimal(double) constructor. Parameters:
val - {@code double} value to be converted to
{@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
RoundingMode is UNNECESSARY.
NumberFormatException - if {@code val} is infinite or NaN.
- since:
1.5 -
|
public BigDecimal(BigInteger val,
MathContext mc) {
this(val);
if (mc.precision > 0)
roundThis(mc);
}
Translates a {@code BigInteger} into a {@code BigDecimal}
rounding according to the context settings. The scale of the
{@code BigDecimal} is zero. Parameters:
val - {@code BigInteger} value to be converted to
{@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
- since:
1.5 -
|
public BigDecimal(BigInteger unscaledVal,
int scale) {
// Negative scales are now allowed
this(unscaledVal);
this.scale = scale;
}
Translates a {@code BigInteger} unscaled value and an
{@code int} scale into a {@code BigDecimal}. The value of
the {@code BigDecimal} is
(unscaledVal × 10-scale). Parameters:
unscaledVal - unscaled value of the {@code BigDecimal}.
scale - scale of the {@code BigDecimal}.
|
public BigDecimal(int val,
MathContext mc) {
intCompact = val;
if (mc.precision > 0)
roundThis(mc);
}
Translates an {@code int} into a {@code BigDecimal}, with
rounding according to the context settings. The scale of the
{@code BigDecimal}, before any rounding, is zero. Parameters:
val - {@code int} value to be converted to {@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
- since:
1.5 -
|
public BigDecimal(long val,
MathContext mc) {
this(val);
if (mc.precision > 0)
roundThis(mc);
}
Translates a {@code long} into a {@code BigDecimal}, with
rounding according to the context settings. The scale of the
{@code BigDecimal}, before any rounding, is zero. Parameters:
val - {@code long} value to be converted to {@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
- since:
1.5 -
|
public BigDecimal(char[] in,
int offset,
int len) {
// protect against huge length.
if (offset+len > in.length || offset < 0)
throw new NumberFormatException();
// This is the primary string to BigDecimal constructor; all
// incoming strings end up here; it uses explicit (inline)
// parsing for speed and generates at most one intermediate
// (temporary) object (a char[] array) for non-compact case.
// Use locals for all fields values until completion
int prec = 0; // record precision value
int scl = 0; // record scale value
long rs = 0; // the compact value in long
BigInteger rb = null; // the inflated value in BigInteger
// use array bounds checking to handle too-long, len == 0,
// bad offset, etc.
try {
// handle the sign
boolean isneg = false; // assume positive
if (in[offset] == '-') {
isneg = true; // leading minus means negative
offset++;
len--;
} else if (in[offset] == '+') { // leading + allowed
offset++;
len--;
}
// should now be at numeric part of the significand
boolean dot = false; // true when there is a '.'
int cfirst = offset; // record start of integer
long exp = 0; // exponent
char c; // current character
boolean isCompact = (len < = MAX_COMPACT_DIGITS);
// integer significand array & idx is the index to it. The array
// is ONLY used when we can't use a compact representation.
char coeff[] = isCompact ? null : new char[len];
int idx = 0;
for (; len > 0; offset++, len--) {
c = in[offset];
// have digit
if ((c >= '0' && c < = '9') || Character.isDigit(c)) {
// First compact case, we need not to preserve the character
// and we can just compute the value in place.
if (isCompact) {
int digit = Character.digit(c, 10);
if (digit == 0) {
if (prec == 0)
prec = 1;
else if (rs != 0) {
rs *= 10;
++prec;
} // else digit is a redundant leading zero
} else {
if (prec != 1 || rs != 0)
++prec; // prec unchanged if preceded by 0s
rs = rs * 10 + digit;
}
} else { // the unscaled value is likely a BigInteger object.
if (c == '0' || Character.digit(c, 10) == 0) {
if (prec == 0) {
coeff[idx] = c;
prec = 1;
} else if (idx != 0) {
coeff[idx++] = c;
++prec;
} // else c must be a redundant leading zero
} else {
if (prec != 1 || idx != 0)
++prec; // prec unchanged if preceded by 0s
coeff[idx++] = c;
}
}
if (dot)
++scl;
continue;
}
// have dot
if (c == '.') {
// have dot
if (dot) // two dots
throw new NumberFormatException();
dot = true;
continue;
}
// exponent expected
if ((c != 'e') && (c != 'E'))
throw new NumberFormatException();
offset++;
c = in[offset];
len--;
boolean negexp = (c == '-');
// optional sign
if (negexp || c == '+') {
offset++;
c = in[offset];
len--;
}
if (len < = 0) // no exponent digits
throw new NumberFormatException();
// skip leading zeros in the exponent
while (len > 10 && Character.digit(c, 10) == 0) {
offset++;
c = in[offset];
len--;
}
if (len > 10) // too many nonzero exponent digits
throw new NumberFormatException();
// c now holds first digit of exponent
for (;; len--) {
int v;
if (c >= '0' && c < = '9') {
v = c - '0';
} else {
v = Character.digit(c, 10);
if (v < 0) // not a digit
throw new NumberFormatException();
}
exp = exp * 10 + v;
if (len == 1)
break; // that was final character
offset++;
c = in[offset];
}
if (negexp) // apply sign
exp = -exp;
// Next test is required for backwards compatibility
if ((int)exp != exp) // overflow
throw new NumberFormatException();
break; // [saves a test]
}
// here when no characters left
if (prec == 0) // no digits found
throw new NumberFormatException();
// Adjust scale if exp is not zero.
if (exp != 0) { // had significant exponent
// Can't call checkScale which relies on proper fields value
long adjustedScale = scl - exp;
if (adjustedScale > Integer.MAX_VALUE ||
adjustedScale < Integer.MIN_VALUE)
throw new NumberFormatException("Scale out of range.");
scl = (int)adjustedScale;
}
// Remove leading zeros from precision (digits count)
if (isCompact) {
rs = isneg ? -rs : rs;
} else {
char quick[];
if (!isneg) {
quick = (coeff.length != prec) ?
Arrays.copyOf(coeff, prec) : coeff;
} else {
quick = new char[prec + 1];
quick[0] = '-';
System.arraycopy(coeff, 0, quick, 1, prec);
}
rb = new BigInteger(quick);
rs = compactValFor(rb);
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new NumberFormatException();
} catch (NegativeArraySizeException e) {
throw new NumberFormatException();
}
this.scale = scl;
this.precision = prec;
this.intCompact = rs;
this.intVal = (rs != INFLATED) ? null : rb;
}
Translates a character array representation of a
{@code BigDecimal} into a {@code BigDecimal}, accepting the
same sequence of characters as the #BigDecimal(String)
constructor, while allowing a sub-array to be specified.
Note that if the sequence of characters is already available
within a character array, using this constructor is faster than
converting the {@code char} array to string and using the
{@code BigDecimal(String)} constructor . Parameters:
in - {@code char} array that is the source of characters.
offset - first character in the array to inspect.
len - number of characters to consider.
Throws:
NumberFormatException - if {@code in} is not a valid
representation of a {@code BigDecimal} or the defined subarray
is not wholly within {@code in}.
- since:
1.5 -
|
public BigDecimal(BigInteger unscaledVal,
int scale,
MathContext mc) {
this(unscaledVal);
this.scale = scale;
if (mc.precision > 0)
roundThis(mc);
}
Translates a {@code BigInteger} unscaled value and an
{@code int} scale into a {@code BigDecimal}, with rounding
according to the context settings. The value of the
{@code BigDecimal} is (unscaledVal ×
10-scale), rounded according to the
{@code precision} and rounding mode settings. Parameters:
unscaledVal - unscaled value of the {@code BigDecimal}.
scale - scale of the {@code BigDecimal}.
mc - the context to use.
Throws:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
- since:
1.5 -
|
BigDecimal(BigInteger intVal,
long val,
int scale,
int prec) {
this.scale = scale;
this.precision = prec;
this.intCompact = val;
this.intVal = intVal;
}
Trusted package private constructor.
Trusted simply means if val is INFLATED, intVal could not be null and
if intVal is null, val could not be INFLATED. |
public BigDecimal(char[] in,
int offset,
int len,
MathContext mc) {
this(in, offset, len);
if (mc.precision > 0)
roundThis(mc);
}
Translates a character array representation of a
{@code BigDecimal} into a {@code BigDecimal}, accepting the
same sequence of characters as the #BigDecimal(String)
constructor, while allowing a sub-array to be specified and
with rounding according to the context settings.
Note that if the sequence of characters is already available
within a character array, using this constructor is faster than
converting the {@code char} array to string and using the
{@code BigDecimal(String)} constructor . Parameters:
in - {@code 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:
ArithmeticException - if the result is inexact but the
rounding mode is {@code UNNECESSARY}.
NumberFormatException - if {@code in} is not a valid
representation of a {@code BigDecimal} or the defined subarray
is not wholly within {@code in}.
- since:
1.5 -
|
Method from java.math.BigDecimal Detail: |
public BigDecimal abs() {
return (signum() < 0 ? negate() : this);
}
Returns a {@code BigDecimal} whose value is the absolute value
of this {@code BigDecimal}, and whose scale is
{@code this.scale()}. |
public BigDecimal abs(MathContext mc) {
return (signum() < 0 ? negate(mc) : plus(mc));
}
Returns a {@code BigDecimal} whose value is the absolute value
of this {@code BigDecimal}, with rounding according to the
context settings. |
public BigDecimal add(BigDecimal augend) {
long xs = this.intCompact;
long ys = augend.intCompact;
BigInteger fst = (xs != INFLATED) ? null : this.intVal;
BigInteger snd = (ys != INFLATED) ? null : augend.intVal;
int rscale = this.scale;
long sdiff = (long)rscale - augend.scale;
if (sdiff != 0) {
if (sdiff < 0) {
int raise = checkScale(-sdiff);
rscale = augend.scale;
if (xs == INFLATED ||
(xs = longMultiplyPowerTen(xs, raise)) == INFLATED)
fst = bigMultiplyPowerTen(raise);
} else {
int raise = augend.checkScale(sdiff);
if (ys == INFLATED ||
(ys = longMultiplyPowerTen(ys, raise)) == INFLATED)
snd = augend.bigMultiplyPowerTen(raise);
}
}
if (xs != INFLATED && ys != INFLATED) {
long sum = xs + ys;
// See "Hacker's Delight" section 2-12 for explanation of
// the overflow test.
if ( (((sum ^ xs) & (sum ^ ys))) >= 0L) // not overflowed
return BigDecimal.valueOf(sum, rscale);
}
if (fst == null)
fst = BigInteger.valueOf(xs);
if (snd == null)
snd = BigInteger.valueOf(ys);
BigInteger sum = fst.add(snd);
return (fst.signum == snd.signum) ?
new BigDecimal(sum, INFLATED, rscale, 0) :
new BigDecimal(sum, rscale);
}
Returns a {@code BigDecimal} whose value is {@code (this +
augend)}, and whose scale is {@code max(this.scale(),
augend.scale())}. |
public BigDecimal add(BigDecimal augend,
MathContext mc) {
if (mc.precision == 0)
return add(augend);
BigDecimal lhs = this;
// Could optimize if values are compact
this.inflate();
augend.inflate();
// If either number is zero then the other number, rounded and
// scaled if necessary, is used as the result.
{
boolean lhsIsZero = lhs.signum() == 0;
boolean augendIsZero = augend.signum() == 0;
if (lhsIsZero || augendIsZero) {
int preferredScale = Math.max(lhs.scale(), augend.scale());
BigDecimal result;
// Could use a factory for zero instead of a new object
if (lhsIsZero && augendIsZero)
return new BigDecimal(BigInteger.ZERO, 0, preferredScale, 0);
result = lhsIsZero ? doRound(augend, mc) : doRound(lhs, mc);
if (result.scale() == preferredScale)
return result;
else if (result.scale() > preferredScale) {
BigDecimal scaledResult =
new BigDecimal(result.intVal, result.intCompact,
result.scale, 0);
scaledResult.stripZerosToMatchScale(preferredScale);
return scaledResult;
} else { // result.scale < preferredScale
int precisionDiff = mc.precision - result.precision();
int scaleDiff = preferredScale - result.scale();
if (precisionDiff >= scaleDiff)
return result.setScale(preferredScale); // can achieve target scale
else
return result.setScale(result.scale() + precisionDiff);
}
}
}
long padding = (long)lhs.scale - augend.scale;
if (padding != 0) { // scales differ; alignment needed
BigDecimal arg[] = preAlign(lhs, augend, padding, mc);
matchScale(arg);
lhs = arg[0];
augend = arg[1];
}
BigDecimal d = new BigDecimal(lhs.inflate().add(augend.inflate()),
lhs.scale);
return doRound(d, mc);
}
Returns a {@code BigDecimal} whose value is {@code (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. |
public byte byteValueExact() {
long num;
num = this.longValueExact(); // will check decimal part
if ((byte)num != num)
throw new java.lang.ArithmeticException("Overflow");
return (byte)num;
}
Converts this {@code BigDecimal} to a {@code byte}, checking
for lost information. If this {@code BigDecimal} has a
nonzero fractional part or is out of the possible range for a
{@code byte} result then an {@code ArithmeticException} is
thrown. |
public int compareTo(BigDecimal val) {
// Quick path for equal scale and non-inflated case.
if (scale == val.scale) {
long xs = intCompact;
long ys = val.intCompact;
if (xs != INFLATED && ys != INFLATED)
return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
}
int xsign = this.signum();
int ysign = val.signum();
if (xsign != ysign)
return (xsign > ysign) ? 1 : -1;
if (xsign == 0)
return 0;
int cmp = compareMagnitude(val);
return (xsign > 0) ? cmp : -cmp;
}
Compares this {@code BigDecimal} with the specified
{@code BigDecimal}. Two {@code BigDecimal} objects that are
equal in value but have a different scale (like 2.0 and 2.00)
are considered equal by this method. This method is provided
in preference to individual methods for each of the six boolean
comparison operators ({@literal <}, ==,
{@literal >}, {@literal >=}, !=, {@literal <=}). The
suggested idiom for performing these comparisons is:
{@code (x.compareTo(y)} <op> {@code 0)}, where
<op> is one of the six comparison operators. |
public BigDecimal divide(BigDecimal divisor) {
/*
* Handle zero cases first.
*/
if (divisor.signum() == 0) { // x/0
if (this.signum() == 0) // 0/0
throw new ArithmeticException("Division undefined"); // NaN
throw new ArithmeticException("Division by zero");
}
// Calculate preferred scale
int preferredScale = saturateLong((long)this.scale - divisor.scale);
if (this.signum() == 0) // 0/y
return (preferredScale >= 0 &&
preferredScale < ZERO_SCALED_BY.length) ?
ZERO_SCALED_BY[preferredScale] :
BigDecimal.valueOf(0, preferredScale);
else {
this.inflate();
divisor.inflate();
/*
* If the quotient this/divisor has a terminating decimal
* expansion, the expansion can have no more than
* (a.precision() + ceil(10*b.precision)/3) digits.
* Therefore, create a MathContext object with this
* precision and do a divide with the UNNECESSARY rounding
* mode.
*/
MathContext mc = new MathContext( (int)Math.min(this.precision() +
(long)Math.ceil(10.0*divisor.precision()/3.0),
Integer.MAX_VALUE),
RoundingMode.UNNECESSARY);
BigDecimal quotient;
try {
quotient = this.divide(divisor, mc);
} catch (ArithmeticException e) {
throw new ArithmeticException("Non-terminating decimal expansion; " +
"no exact representable decimal result.");
}
int quotientScale = quotient.scale();
// divide(BigDecimal, mc) tries to adjust the quotient to
// the desired one by removing trailing zeros; since the
// exact divide method does not have an explicit digit
// limit, we can add zeros too.
if (preferredScale > quotientScale)
return quotient.setScale(preferredScale, ROUND_UNNECESSARY);
return quotient;
}
}
Returns a {@code BigDecimal} whose value is {@code (this /
divisor)}, and whose preferred scale is {@code (this.scale() -
divisor.scale())}; if the exact quotient cannot be
represented (because it has a non-terminating decimal
expansion) an {@code ArithmeticException} is thrown. |
public BigDecimal divide(BigDecimal divisor,
int roundingMode) {
return this.divide(divisor, scale, roundingMode);
}
Returns a {@code BigDecimal} whose value is {@code (this /
divisor)}, and whose scale is {@code this.scale()}. If
rounding must be performed to generate a result with the given
scale, the specified rounding mode is applied.
The new #divide(BigDecimal, RoundingMode) method
should be used in preference to this legacy method. |
public BigDecimal divide(BigDecimal divisor,
RoundingMode roundingMode) {
return this.divide(divisor, scale, roundingMode.oldMode);
}
Returns a {@code BigDecimal} whose value is {@code (this /
divisor)}, and whose scale is {@code this.scale()}. If
rounding must be performed to generate a result with the given
scale, the specified rounding mode is applied. |
public BigDecimal divide(BigDecimal divisor,
MathContext mc) {
int mcp = mc.precision;
if (mcp == 0)
return divide(divisor);
BigDecimal dividend = this;
long preferredScale = (long)dividend.scale - divisor.scale;
// Now calculate the answer. We use the existing
// divide-and-round method, but as this rounds to scale we have
// to normalize the values here to achieve the desired result.
// For x/y we first handle y=0 and x=0, and then normalize x and
// y to give x' and y' with the following constraints:
// (a) 0.1 < = x' < 1
// (b) x' < = y' < 10*x'
// Dividing x'/y' with the required scale set to mc.precision then
// will give a result in the range 0.1 to 1 rounded to exactly
// the right number of digits (except in the case of a result of
// 1.000... which can arise when x=y, or when rounding overflows
// The 1.000... case will reduce properly to 1.
if (divisor.signum() == 0) { // x/0
if (dividend.signum() == 0) // 0/0
throw new ArithmeticException("Division undefined"); // NaN
throw new ArithmeticException("Division by zero");
}
if (dividend.signum() == 0) // 0/y
return new BigDecimal(BigInteger.ZERO, 0,
saturateLong(preferredScale), 1);
// Normalize dividend & divisor so that both fall into [0.1, 0.999...]
int xscale = dividend.precision();
int yscale = divisor.precision();
dividend = new BigDecimal(dividend.intVal, dividend.intCompact,
xscale, xscale);
divisor = new BigDecimal(divisor.intVal, divisor.intCompact,
yscale, yscale);
if (dividend.compareMagnitude(divisor) > 0) // satisfy constraint (b)
yscale = divisor.scale -= 1; // [that is, divisor *= 10]
// In order to find out whether the divide generates the exact result,
// we avoid calling the above divide method. 'quotient' holds the
// return BigDecimal object whose scale will be set to 'scl'.
BigDecimal quotient;
int scl = checkScale(preferredScale + yscale - xscale + mcp);
if (checkScale((long)mcp + yscale) > xscale)
dividend = dividend.setScale(mcp + yscale, ROUND_UNNECESSARY);
else
divisor = divisor.setScale(checkScale((long)xscale - mcp),
ROUND_UNNECESSARY);
quotient = divideAndRound(dividend.intCompact, dividend.intVal,
divisor.intCompact, divisor.intVal,
scl, mc.roundingMode.oldMode,
checkScale(preferredScale));
// doRound, here, only affects 1000000000 case.
quotient = doRound(quotient, mc);
return quotient;
}
Returns a {@code BigDecimal} whose value is {@code (this /
divisor)}, with rounding according to the context settings. |
public BigDecimal divide(BigDecimal divisor,
int scale,
int roundingMode) {
/*
* IMPLEMENTATION NOTE: This method *must* return a new object
* since divideAndRound uses divide to generate a value whose
* scale is then modified.
*/
if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
throw new IllegalArgumentException("Invalid rounding mode");
/*
* Rescale dividend or divisor (whichever can be "upscaled" to
* produce correctly scaled quotient).
* Take care to detect out-of-range scales
*/
BigDecimal dividend = this;
if (checkScale((long)scale + divisor.scale) > this.scale)
dividend = this.setScale(scale + divisor.scale, ROUND_UNNECESSARY);
else
divisor = divisor.setScale(checkScale((long)this.scale - scale),
ROUND_UNNECESSARY);
return divideAndRound(dividend.intCompact, dividend.intVal,
divisor.intCompact, divisor.intVal,
scale, roundingMode, scale);
}
Returns a {@code BigDecimal} whose value is {@code (this /
divisor)}, and whose scale is as specified. If rounding must
be performed to generate a result with the specified scale, the
specified rounding mode is applied.
The new #divide(BigDecimal, int, RoundingMode) method
should be used in preference to this legacy method. |
public BigDecimal divide(BigDecimal divisor,
int scale,
RoundingMode roundingMode) {
return divide(divisor, scale, roundingMode.oldMode);
}
Returns a {@code BigDecimal} whose value is {@code (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. |
public BigDecimal[] divideAndRemainder(BigDecimal divisor) {
// we use the identity x = i * y + r to determine r
BigDecimal[] result = new BigDecimal[2];
result[0] = this.divideToIntegralValue(divisor);
result[1] = this.subtract(result[0].multiply(divisor));
return result;
}
Returns a two-element {@code BigDecimal} array containing the
result of {@code divideToIntegralValue} followed by the result of
{@code remainder} on the two operands.
Note that if both the integer quotient and remainder are
needed, this method is faster than using the
{@code divideToIntegralValue} and {@code remainder} methods
separately because the division need only be carried out once. |
public BigDecimal[] divideAndRemainder(BigDecimal divisor,
MathContext mc) {
if (mc.precision == 0)
return divideAndRemainder(divisor);
BigDecimal[] result = new BigDecimal[2];
BigDecimal lhs = this;
result[0] = lhs.divideToIntegralValue(divisor, mc);
result[1] = lhs.subtract(result[0].multiply(divisor));
return result;
}
Returns a two-element {@code BigDecimal} array containing the
result of {@code divideToIntegralValue} followed by the result of
{@code remainder} on the two operands calculated with rounding
according to the context settings.
Note that if both the integer quotient and remainder are
needed, this method is faster than using the
{@code divideToIntegralValue} and {@code remainder} methods
separately because the division need only be carried out once. |
public BigDecimal divideToIntegralValue(BigDecimal divisor) {
// Calculate preferred scale
int preferredScale = saturateLong((long)this.scale - divisor.scale);
if (this.compareMagnitude(divisor) < 0) {
// much faster when this < < divisor
return BigDecimal.valueOf(0, preferredScale);
}
if(this.signum() == 0 && divisor.signum() != 0)
return this.setScale(preferredScale, ROUND_UNNECESSARY);
// Perform a divide with enough digits to round to a correct
// integer value; then remove any fractional digits
int maxDigits = (int)Math.min(this.precision() +
(long)Math.ceil(10.0*divisor.precision()/3.0) +
Math.abs((long)this.scale() - divisor.scale()) + 2,
Integer.MAX_VALUE);
BigDecimal quotient = this.divide(divisor, new MathContext(maxDigits,
RoundingMode.DOWN));
if (quotient.scale > 0) {
quotient = quotient.setScale(0, RoundingMode.DOWN);
quotient.stripZerosToMatchScale(preferredScale);
}
if (quotient.scale < preferredScale) {
// pad with zeros if necessary
quotient = quotient.setScale(preferredScale, ROUND_UNNECESSARY);
}
return quotient;
}
Returns a {@code BigDecimal} whose value is the integer part
of the quotient {@code (this / divisor)} rounded down. The
preferred scale of the result is {@code (this.scale() -
divisor.scale())}. |
public BigDecimal divideToIntegralValue(BigDecimal divisor,
MathContext mc) {
if (mc.precision == 0 || // exact result
(this.compareMagnitude(divisor) < 0) ) // zero result
return divideToIntegralValue(divisor);
// Calculate preferred scale
int preferredScale = saturateLong((long)this.scale - divisor.scale);
/*
* Perform a normal divide to mc.precision digits. If the
* remainder has absolute value less than the divisor, the
* integer portion of the quotient fits into mc.precision
* digits. Next, remove any fractional digits from the
* quotient and adjust the scale to the preferred value.
*/
BigDecimal result = this.
divide(divisor, new MathContext(mc.precision, RoundingMode.DOWN));
if (result.scale() < 0) {
/*
* Result is an integer. See if quotient represents the
* full integer portion of the exact quotient; if it does,
* the computed remainder will be less than the divisor.
*/
BigDecimal product = result.multiply(divisor);
// If the quotient is the full integer value,
// |dividend-product| < |divisor|.
if (this.subtract(product).compareMagnitude(divisor) >= 0) {
throw new ArithmeticException("Division impossible");
}
} else if (result.scale() > 0) {
/*
* Integer portion of quotient will fit into precision
* digits; recompute quotient to scale 0 to avoid double
* rounding and then try to adjust, if necessary.
*/
result = result.setScale(0, RoundingMode.DOWN);
}
// else result.scale() == 0;
int precisionDiff;
if ((preferredScale > result.scale()) &&
(precisionDiff = mc.precision - result.precision()) > 0) {
return result.setScale(result.scale() +
Math.min(precisionDiff, preferredScale - result.scale) );
} else {
result.stripZerosToMatchScale(preferredScale);
return result;
}
}
Returns a {@code BigDecimal} whose value is the integer part
of {@code (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
{@code (this.scale() - divisor.scale())}. An
{@code ArithmeticException} is thrown if the integer part of
the exact quotient needs more than {@code mc.precision}
digits. |
public double doubleValue() {
if (scale == 0 && intCompact != INFLATED)
return (double)intCompact;
// Somewhat inefficient, but guaranteed to work.
return Double.parseDouble(this.toString());
}
Converts this {@code BigDecimal} to a {@code double}.
This conversion is similar to the
narrowing primitive conversion from {@code double} to
{@code float} as defined in section 5.1.3 of
The Java™ Language Specification:
if this {@code BigDecimal} has too great a
magnitude represent as a {@code double}, it will be
converted to Double#NEGATIVE_INFINITY or Double#POSITIVE_INFINITY as appropriate. Note that even when
the return value is finite, this conversion can lose
information about the precision of the {@code BigDecimal}
value. |
public boolean equals(Object x) {
if (!(x instanceof BigDecimal))
return false;
BigDecimal xDec = (BigDecimal) x;
if (x == this)
return true;
if (scale != xDec.scale)
return false;
long s = this.intCompact;
long xs = xDec.intCompact;
if (s != INFLATED) {
if (xs == INFLATED)
xs = compactValFor(xDec.intVal);
return xs == s;
} else if (xs != INFLATED)
return xs == compactValFor(this.intVal);
return this.inflate().equals(xDec.inflate());
}
Compares this {@code BigDecimal} with the specified
{@code Object} for equality. Unlike compareTo , this method considers two
{@code BigDecimal} objects equal only if they are equal in
value and scale (thus 2.0 is not equal to 2.00 when compared by
this method). |
public float floatValue() {
if (scale == 0 && intCompact != INFLATED)
return (float)intCompact;
// Somewhat inefficient, but guaranteed to work.
return Float.parseFloat(this.toString());
}
Converts this {@code BigDecimal} to a {@code float}.
This conversion is similar to the
narrowing primitive conversion from {@code double} to
{@code float} as defined in section 5.1.3 of
The Java™ Language Specification:
if this {@code BigDecimal} has too great a
magnitude to represent as a {@code float}, it will be
converted to Float#NEGATIVE_INFINITY or Float#POSITIVE_INFINITY as appropriate. Note that even when
the return value is finite, this conversion can lose
information about the precision of the {@code BigDecimal}
value. |
public int hashCode() {
if (intCompact != INFLATED) {
long val2 = (intCompact < 0)? -intCompact : intCompact;
int temp = (int)( ((int)(val2 > > > 32)) * 31 +
(val2 & LONG_MASK));
return 31*((intCompact < 0) ?-temp:temp) + scale;
} else
return 31*intVal.hashCode() + scale;
}
Returns the hash code for this {@code BigDecimal}. Note that
two {@code BigDecimal} objects that are numerically equal but
differ in scale (like 2.0 and 2.00) will generally not
have the same hash code. |
public int intValue() {
return (intCompact != INFLATED && scale == 0) ?
(int)intCompact :
toBigInteger().intValue();
}
Converts this {@code BigDecimal} to an {@code int}.
This conversion is analogous to the
narrowing primitive conversion from {@code double} to
{@code short} as defined in section 5.1.3 of
The Java™ Language Specification:
any fractional part of this
{@code BigDecimal} will be discarded, and if the resulting
"{@code BigInteger}" is too big to fit in an
{@code int}, only the low-order 32 bits are returned.
Note that this conversion can lose information about the
overall magnitude and precision of this {@code BigDecimal}
value as well as return a result with the opposite sign. |
public int intValueExact() {
long num;
num = this.longValueExact(); // will check decimal part
if ((int)num != num)
throw new java.lang.ArithmeticException("Overflow");
return (int)num;
}
Converts this {@code BigDecimal} to an {@code int}, checking
for lost information. If this {@code BigDecimal} has a
nonzero fractional part or is out of the possible range for an
{@code int} result then an {@code ArithmeticException} is
thrown. |
public long longValue() {
return (intCompact != INFLATED && scale == 0) ?
intCompact:
toBigInteger().longValue();
}
Converts this {@code BigDecimal} to a {@code long}.
This conversion is analogous to the
narrowing primitive conversion from {@code double} to
{@code short} as defined in section 5.1.3 of
The Java™ Language Specification:
any fractional part of this
{@code BigDecimal} will be discarded, and if the resulting
"{@code BigInteger}" is too big to fit in a
{@code long}, only the low-order 64 bits are returned.
Note that this conversion can lose information about the
overall magnitude and precision of this {@code BigDecimal} value as well
as return a result with the opposite sign. |
public long longValueExact() {
if (intCompact != INFLATED && scale == 0)
return intCompact;
// If more than 19 digits in integer part it cannot possibly fit
if ((precision() - scale) > 19) // [OK for negative scale too]
throw new java.lang.ArithmeticException("Overflow");
// Fastpath zero and < 1.0 numbers (the latter can be very slow
// to round if very small)
if (this.signum() == 0)
return 0;
if ((this.precision() - this.scale) < = 0)
throw new ArithmeticException("Rounding necessary");
// round to an integer, with Exception if decimal part non-0
BigDecimal num = this.setScale(0, ROUND_UNNECESSARY);
if (num.precision() >= 19) // need to check carefully
LongOverflow.check(num);
return num.inflate().longValue();
}
Converts this {@code BigDecimal} to a {@code long}, checking
for lost information. If this {@code BigDecimal} has a
nonzero fractional part or is out of the possible range for a
{@code long} result then an {@code ArithmeticException} is
thrown. |
public BigDecimal max(BigDecimal val) {
return (compareTo(val) >= 0 ? this : val);
}
Returns the maximum of this {@code BigDecimal} and {@code val}. |
public BigDecimal min(BigDecimal val) {
return (compareTo(val) < = 0 ? this : val);
}
Returns the minimum of this {@code BigDecimal} and
{@code val}. |
public BigDecimal movePointLeft(int n) {
// Cannot use movePointRight(-n) in case of n==Integer.MIN_VALUE
int newScale = checkScale((long)scale + n);
BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
}
Returns a {@code BigDecimal} which is equivalent to this one
with the decimal point moved {@code n} places to the left. If
{@code n} is non-negative, the call merely adds {@code n} to
the scale. If {@code n} is negative, the call is equivalent
to {@code movePointRight(-n)}. The {@code BigDecimal}
returned by this call has value (this ×
10-n) and scale {@code max(this.scale()+n,
0)}. |
public BigDecimal movePointRight(int n) {
// Cannot use movePointLeft(-n) in case of n==Integer.MIN_VALUE
int newScale = checkScale((long)scale - n);
BigDecimal num = new BigDecimal(intVal, intCompact, newScale, 0);
return num.scale < 0 ? num.setScale(0, ROUND_UNNECESSARY) : num;
}
Returns a {@code BigDecimal} which is equivalent to this one
with the decimal point moved {@code n} places to the right.
If {@code n} is non-negative, the call merely subtracts
{@code n} from the scale. If {@code n} is negative, the call
is equivalent to {@code movePointLeft(-n)}. The
{@code BigDecimal} returned by this call has value (this
× 10n) and scale {@code max(this.scale()-n,
0)}. |
public BigDecimal multiply(BigDecimal multiplicand) {
long x = this.intCompact;
long y = multiplicand.intCompact;
int productScale = checkScale((long)scale + multiplicand.scale);
// Might be able to do a more clever check incorporating the
// inflated check into the overflow computation.
if (x != INFLATED && y != INFLATED) {
/*
* If the product is not an overflowed value, continue
* to use the compact representation. if either of x or y
* is INFLATED, the product should also be regarded as
* an overflow. Before using the overflow test suggested in
* "Hacker's Delight" section 2-12, we perform quick checks
* using the precision information to see whether the overflow
* would occur since division is expensive on most CPUs.
*/
long product = x * y;
long prec = this.precision() + multiplicand.precision();
if (prec < 19 || (prec < 21 && (y == 0 || product / y == x)))
return BigDecimal.valueOf(product, productScale);
return new BigDecimal(BigInteger.valueOf(x).multiply(y), INFLATED,
productScale, 0);
}
BigInteger rb;
if (x == INFLATED && y == INFLATED)
rb = this.intVal.multiply(multiplicand.intVal);
else if (x != INFLATED)
rb = multiplicand.intVal.multiply(x);
else
rb = this.intVal.multiply(y);
return new BigDecimal(rb, INFLATED, productScale, 0);
}
Returns a {@code BigDecimal} whose value is (this ×
multiplicand), and whose scale is {@code (this.scale() +
multiplicand.scale())}. |
public BigDecimal multiply(BigDecimal multiplicand,
MathContext mc) {
if (mc.precision == 0)
return multiply(multiplicand);
return doRound(this.multiply(multiplicand), mc);
}
Returns a {@code BigDecimal} whose value is (this ×
multiplicand), with rounding according to the context settings. |
public BigDecimal negate() {
BigDecimal result;
if (intCompact != INFLATED)
result = BigDecimal.valueOf(-intCompact, scale);
else {
result = new BigDecimal(intVal.negate(), scale);
result.precision = precision;
}
return result;
}
Returns a {@code BigDecimal} whose value is {@code (-this)},
and whose scale is {@code this.scale()}. |
public BigDecimal negate(MathContext mc) {
return negate().plus(mc);
}
Returns a {@code BigDecimal} whose value is {@code (-this)},
with rounding according to the context settings. |
public BigDecimal plus() {
return this;
}
Returns a {@code BigDecimal} whose value is {@code (+this)}, and whose
scale is {@code this.scale()}.
This method, which simply returns this {@code BigDecimal}
is included for symmetry with the unary minus method #negate() . |
public BigDecimal plus(MathContext mc) {
if (mc.precision == 0) // no rounding please
return this;
return doRound(this, mc);
}
|
public BigDecimal pow(int n) {
if (n < 0 || n > 999999999)
throw new ArithmeticException("Invalid operation");
// No need to calculate pow(n) if result will over/underflow.
// Don't attempt to support "supernormal" numbers.
int newScale = checkScale((long)scale * n);
this.inflate();
return new BigDecimal(intVal.pow(n), newScale);
}
Returns a {@code BigDecimal} whose value is
(thisn), The power is computed exactly, to
unlimited precision.
The parameter {@code n} must be in the range 0 through
999999999, inclusive. {@code ZERO.pow(0)} returns #ONE .
Note that future releases may expand the allowable exponent
range of this method. |
public BigDecimal pow(int n,
MathContext mc) {
if (mc.precision == 0)
return pow(n);
if (n < -999999999 || n > 999999999)
throw new ArithmeticException("Invalid operation");
if (n == 0)
return ONE; // x**0 == 1 in X3.274
this.inflate();
BigDecimal lhs = this;
MathContext workmc = mc; // working settings
int mag = Math.abs(n); // magnitude of n
if (mc.precision > 0) {
int elength = longDigitLength(mag); // length of n in digits
if (elength > mc.precision) // X3.274 rule
throw new ArithmeticException("Invalid operation");
workmc = new MathContext(mc.precision + elength + 1,
mc.roundingMode);
}
// ready to carry out power calculation...
BigDecimal acc = ONE; // accumulator
boolean seenbit = false; // set once we've seen a 1-bit
for (int i=1;;i++) { // for each bit [top bit ignored]
mag += mag; // shift left 1 bit
if (mag < 0) { // top bit is set
seenbit = true; // OK, we're off
acc = acc.multiply(lhs, workmc); // acc=acc*x
}
if (i == 31)
break; // that was the last bit
if (seenbit)
acc=acc.multiply(acc, workmc); // acc=acc*acc [square]
// else (!seenbit) no point in squaring ONE
}
// if negative n, calculate the reciprocal using working precision
if (n< 0) // [hence mc.precision >0]
acc=ONE.divide(acc, workmc);
// round to final precision and strip zeros
return doRound(acc, mc);
}
|
public int precision() {
int result = precision;
if (result == 0) {
long s = intCompact;
if (s != INFLATED)
result = longDigitLength(s);
else
result = bigDigitLength(inflate());
precision = result;
}
return result;
}
|
public BigDecimal remainder(BigDecimal divisor) {
BigDecimal divrem[] = this.divideAndRemainder(divisor);
return divrem[1];
}
Returns a {@code BigDecimal} whose value is {@code (this % divisor)}.
The remainder is given by
{@code this.subtract(this.divideToIntegralValue(divisor).multiply(divisor))}.
Note that this is not the modulo operation (the result can be
negative). |
public BigDecimal remainder(BigDecimal divisor,
MathContext mc) {
BigDecimal divrem[] = this.divideAndRemainder(divisor, mc);
return divrem[1];
}
Returns a {@code BigDecimal} whose value is {@code (this %
divisor)}, with rounding according to the context settings.
The {@code 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 {@code mc.getPrecision()} digits.
The remainder is given by
{@code this.subtract(this.divideToIntegralValue(divisor,
mc).multiply(divisor))}. Note that this is not the modulo
operation (the result can be negative). |
public BigDecimal round(MathContext mc) {
return plus(mc);
}
|
public int scale() {
return scale;
}
Returns the scale of this {@code 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 {@code -3} means the unscaled
value is multiplied by 1000. |
public BigDecimal scaleByPowerOfTen(int n) {
return new BigDecimal(intVal, intCompact,
checkScale((long)scale - n), precision);
}
Returns a BigDecimal whose numerical value is equal to
({@code this} * 10n). The scale of
the result is {@code (this.scale() - n)}. |
public BigDecimal setScale(int newScale) {
return setScale(newScale, ROUND_UNNECESSARY);
}
Returns a {@code BigDecimal} whose scale is the specified
value, and whose value is numerically equal to this
{@code BigDecimal}'s. Throws an {@code ArithmeticException}
if this is not possible.
This call is typically used to increase the scale, in which
case it is guaranteed that there exists a {@code BigDecimal}
of the specified scale and the correct value. The call can
also be used to reduce the scale if the caller knows that the
{@code BigDecimal} 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 of {@code setScale}, but saves the caller the trouble
of specifying a rounding mode in cases where it is irrelevant.
Note that since {@code BigDecimal} objects are immutable,
calls of this method do not result in the original
object being modified, contrary to the usual convention of
having methods named setX mutate field
{@code X}. Instead, {@code setScale} returns an
object with the proper scale; the returned object may or may
not be newly allocated. |
public BigDecimal setScale(int newScale,
RoundingMode roundingMode) {
return setScale(newScale, roundingMode.oldMode);
}
Returns a {@code BigDecimal} whose scale is the specified
value, and whose unscaled value is determined by multiplying or
dividing this {@code 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.
Note that since BigDecimal objects are immutable, calls of
this method do not result in the original object being
modified, contrary to the usual convention of having methods
named setX mutate field {@code X}.
Instead, {@code setScale} returns an object with the proper
scale; the returned object may or may not be newly allocated. |
public BigDecimal setScale(int newScale,
int roundingMode) {
if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY)
throw new IllegalArgumentException("Invalid rounding mode");
int oldScale = this.scale;
if (newScale == oldScale) // easy case
return this;
if (this.signum() == 0) // zero can have any scale
return BigDecimal.valueOf(0, newScale);
long rs = this.intCompact;
if (newScale > oldScale) {
int raise = checkScale((long)newScale - oldScale);
BigInteger rb = null;
if (rs == INFLATED ||
(rs = longMultiplyPowerTen(rs, raise)) == INFLATED)
rb = bigMultiplyPowerTen(raise);
return new BigDecimal(rb, rs, newScale,
(precision > 0) ? precision + raise : 0);
} else {
// newScale < oldScale -- drop some digits
// Can't predict the precision due to the effect of rounding.
int drop = checkScale((long)oldScale - newScale);
if (drop < LONG_TEN_POWERS_TABLE.length)
return divideAndRound(rs, this.intVal,
LONG_TEN_POWERS_TABLE[drop], null,
newScale, roundingMode, newScale);
else
return divideAndRound(rs, this.intVal,
INFLATED, bigTenToThe(drop),
newScale, roundingMode, newScale);
}
}
Returns a {@code BigDecimal} whose scale is the specified
value, and whose unscaled value is determined by multiplying or
dividing this {@code 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.
Note that since BigDecimal objects are immutable, calls of
this method do not result in the original object being
modified, contrary to the usual convention of having methods
named setX mutate field {@code X}.
Instead, {@code setScale} returns an object with the proper
scale; the returned object may or may not be newly allocated.
The new #setScale(int, RoundingMode) method should
be used in preference to this legacy method. |
public short shortValueExact() {
long num;
num = this.longValueExact(); // will check decimal part
if ((short)num != num)
throw new java.lang.ArithmeticException("Overflow");
return (short)num;
}
Converts this {@code BigDecimal} to a {@code short}, checking
for lost information. If this {@code BigDecimal} has a
nonzero fractional part or is out of the possible range for a
{@code short} result then an {@code ArithmeticException} is
thrown. |
public int signum() {
return (intCompact != INFLATED)?
Long.signum(intCompact):
intVal.signum();
}
Returns the signum function of this {@code BigDecimal}. |
public BigDecimal stripTrailingZeros() {
this.inflate();
BigDecimal result = new BigDecimal(intVal, scale);
result.stripZerosToMatchScale(Long.MIN_VALUE);
return result;
}
Returns a {@code 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 {@code BigDecimal} value {@code 600.0}, which has
[{@code BigInteger}, {@code scale}] components equals to
[6000, 1], yields {@code 6E2} with [{@code BigInteger},
{@code scale}] components equals to [6, -2] |
public BigDecimal subtract(BigDecimal subtrahend) {
return add(subtrahend.negate());
}
Returns a {@code BigDecimal} whose value is {@code (this -
subtrahend)}, and whose scale is {@code max(this.scale(),
subtrahend.scale())}. |
public BigDecimal subtract(BigDecimal subtrahend,
MathContext mc) {
BigDecimal nsubtrahend = subtrahend.negate();
if (mc.precision == 0)
return add(nsubtrahend);
// share the special rounding code in add()
return add(nsubtrahend, mc);
}
Returns a {@code BigDecimal} whose value is {@code (this - subtrahend)},
with rounding according to the context settings.
If {@code subtrahend} is zero then this, rounded if necessary, is used as the
result. If this is zero then the result is {@code subtrahend.negate(mc)}. |
public BigInteger toBigInteger() {
// force to an integer, quietly
return this.setScale(0, ROUND_DOWN).inflate();
}
Converts this {@code BigDecimal} to a {@code BigInteger}.
This conversion is analogous to the
narrowing primitive conversion from {@code double} to
{@code long} as defined in section 5.1.3 of
The Java™ Language Specification:
any fractional part of this
{@code BigDecimal} will be discarded. Note that this
conversion can lose information about the precision of the
{@code BigDecimal} value.
To have an exception thrown if the conversion is inexact (in
other words if a nonzero fractional part is discarded), use the
#toBigIntegerExact() method. |
public BigInteger toBigIntegerExact() {
// round to an integer, with Exception if decimal part non-0
return this.setScale(0, ROUND_UNNECESSARY).inflate();
}
Converts this {@code BigDecimal} to a {@code BigInteger},
checking for lost information. An exception is thrown if this
{@code BigDecimal} has a nonzero fractional part. |
public String toEngineeringString() {
return layoutChars(false);
}
Returns a string representation of this {@code BigDecimal},
using engineering notation if an exponent is needed.
Returns a string that represents the {@code 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 [integer,
scale] pair of this {@code BigDecimal} if the output string is
converting back to a {@code BigDecimal} using the {@linkplain
#BigDecimal(String) 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. |
public String toPlainString() {
BigDecimal bd = this;
if (bd.scale < 0)
bd = bd.setScale(0);
bd.inflate();
if (bd.scale == 0) // No decimal point
return bd.intVal.toString();
return bd.getValueString(bd.signum(), bd.intVal.abs().toString(), bd.scale);
}
Returns a string representation of this {@code 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
{@linkplain #BigDecimal(String) string constructor}, only the
numerical value of this {@code BigDecimal} will necessarily be
recovered; the representation of the new {@code BigDecimal}
may have a different scale. In particular, if this
{@code BigDecimal} 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 the {@code toString}
method in 1.4 and earlier releases.) |
public String toString() {
String sc = stringCache;
if (sc == null)
stringCache = sc = layoutChars(true);
return sc;
}
Returns the string representation of this {@code BigDecimal},
using scientific notation if an exponent is needed.
A standard canonical string form of the {@code BigDecimal}
is created as though by the following steps: first, the
absolute value of the unscaled value of the {@code BigDecimal}
is converted to a string in base ten using the characters
{@code '0'} through {@code '9'} with no leading zeros (except
if its value is zero, in which case a single {@code '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,
{@code -scale+(ulength-1)}, where {@code 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 {@code -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.
{@code '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
{@code '0'} character is prefixed.
Otherwise (that is, if the scale is negative, or the
adjusted exponent is less than {@code -6}), the number will be
converted to a character form using exponential notation. In
this case, if the converted {@code BigInteger} 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 {@code 'E'} followed immediately by the
adjusted exponent converted to a character form. The latter is
in base ten, using the characters {@code '0'} through
{@code '9'} with no leading zeros, and is always prefixed by a
sign character {@code '-'} ('\u002D') if the
adjusted exponent is negative, {@code '+'}
('\u002B') otherwise).
Finally, the entire string is prefixed by a minus sign
character {@code '-'} ('\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
{@code BigDecimal} values and the result of this conversion.
That is, every distinguishable {@code BigDecimal} value
(unscaled value and scale) has a unique string representation
as a result of using {@code toString}. If that string
representation is converted back to a {@code BigDecimal} using
the #BigDecimal(String) constructor, then the original
value will be recovered.
- 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 the java.text.NumberFormat class and its subclasses.
- The #toEngineeringString method may be used for
presenting numbers with exponents in engineering notation, and the
setScale method may be used for
rounding a {@code BigDecimal} so it has a known number of digits after
the decimal point.
- The digit-to-character mapping provided by
{@code Character.forDigit} is used.
|
public BigDecimal ulp() {
return BigDecimal.valueOf(1, this.scale());
}
Returns the size of an ulp, a unit in the last place, of this
{@code BigDecimal}. An ulp of a nonzero {@code BigDecimal}
value is the positive distance between this value and the
{@code 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 {@code this}. The result is
stored with the same scale as {@code this} so the result
for zero and nonzero values is equal to {@code [1,
this.scale()]}. |
public BigInteger unscaledValue() {
return this.inflate();
}
Returns a {@code BigInteger} whose value is the unscaled
value of this {@code BigDecimal}. (Computes (this *
10this.scale()).) |
public static BigDecimal valueOf(long val) {
if (val >= 0 && val < zeroThroughTen.length)
return zeroThroughTen[(int)val];
else if (val != INFLATED)
return new BigDecimal(null, val, 0, 0);
return new BigDecimal(BigInteger.valueOf(val), val, 0, 0);
}
Translates a {@code long} value into a {@code BigDecimal}
with a scale of zero. This {@literal "static factory method"}
is provided in preference to a ({@code long}) constructor
because it allows for reuse of frequently used
{@code BigDecimal} values. |
public static BigDecimal valueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannot fastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
return new BigDecimal(Double.toString(val));
}
Translates a {@code double} into a {@code BigDecimal}, using
the {@code double}'s canonical string representation provided
by the Double#toString(double) method.
Note: This is generally the preferred way to convert
a {@code double} (or {@code float}) into a
{@code BigDecimal}, as the value returned is equal to that
resulting from constructing a {@code BigDecimal} from the
result of using Double#toString(double) . |
public static BigDecimal valueOf(long unscaledVal,
int scale) {
if (scale == 0)
return valueOf(unscaledVal);
else if (unscaledVal == 0) {
if (scale > 0 && scale < ZERO_SCALED_BY.length)
return ZERO_SCALED_BY[scale];
else
return new BigDecimal(BigInteger.ZERO, 0, scale, 1);
}
return new BigDecimal(unscaledVal == INFLATED ?
BigInteger.valueOf(unscaledVal) : null,
unscaledVal, scale, 0);
}
Translates a {@code long} unscaled value and an
{@code int} scale into a {@code BigDecimal}. This
{@literal "static factory method"} is provided in preference to
a ({@code long}, {@code int}) constructor because it
allows for reuse of frequently used {@code BigDecimal} values.. |