Double class is the wrapper class for values of the primitive
type double. An object of type Double contains a
single field whose type is double.
In addition, this class provides several methods for converting a
double to a String and a
String to a double, as well as other
constants and methods useful when dealing with a
double.
This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
+0.0 and -0.0), signed infinities
(positive infinity and
negative infinity), and
NaN (not-a-number).
An equivalence relation on a set of values is a boolean
relation on pairs of values that is reflexive, symmetric, and
transitive. For more discussion of equivalence relations and object
equality, see the Object.
specification. An equivalence relation partitions the values it
operates over into sets called equivalence classes. All the
members of the equivalence class are equal to each other under the
relation. An equivalence class may contain only a single member. At
least for some purposes, all the members of an equivalence class
are substitutable for each other. In particular, in a numeric
expression equivalent values can be substituted for one
another without changing the result of the expression, meaning
changing the equivalence class of the result of the expression.
Notably, the built-in == operation on floating-point
values is not an equivalence relation. Despite not
defining an equivalence relation, the semantics of the IEEE 754
== operator were deliberately designed to meet other needs
of numerical computation. There are two exceptions where the
properties of an equivalence relation are not satisfied by == on floating-point values:
v1 and v2 are both NaN, then v1
== v2 has the value false. Therefore, for two NaN
arguments the reflexive property of an equivalence
relation is not satisfied by the == operator.
v1 represents +0.0 while v2
represents -0.0, or vice versa, then v1 == v2 has
the value true even though +0.0 and -0.0
are distinguishable under various floating-point operations. For
example, 1.0/+0.0 evaluates to positive infinity while
1.0/-0.0 evaluates to negative infinity and
positive infinity and negative infinity are neither equal to each
other nor equivalent to each other. Thus, while a signed zero input
most commonly determines the sign of a zero result, because of
dividing by zero, +0.0 and -0.0 may not be
substituted for each other in general. The sign of a zero input
also has a non-substitutable effect on the result of some math
library methods.
For ordered comparisons using the built-in comparison operators
(<, <=, etc.), NaN values have another anomalous
situation: a NaN is neither less than, nor greater than, nor equal
to any value, including itself. This means the trichotomy of
comparison does not hold.
To provide the appropriate semantics for equals and
compareTo methods, those methods cannot simply be wrappers
around == or ordered comparison operations. Instead, equals uses representation
equivalence, defining NaN arguments to be equal to each other,
restoring reflexivity, and defining +0.0 to not be
equal to -0.0. For comparisons, compareTo defines a total order where -0.0 is less than
+0.0 and where a NaN is equal to itself and considered
greater than positive infinity.
The operational semantics of equals and compareTo are expressed in terms of bit-wise converting the floating-point values to integral values.
The natural ordering implemented by compareTo is consistent with equals. That
is, two objects are reported as equal by equals if and only
if compareTo on those objects returns zero.
The adjusted behaviors defined for equals and compareTo allow instances of wrapper classes to work properly with
conventional data structures. For example, defining NaN
values to be equals to one another allows NaN to be used as
an element of a HashSet or as the key of
a HashMap. Similarly, defining compareTo as a total ordering, including +0.0, -0.0, and NaN, allows instances of wrapper classes to be used as
elements of a SortedSet or as keys of a
SortedMap.
Comparing numerical equality to various useful equivalence relations that can be defined over floating-point values:
==
operator): (Not an equivalence relation)+0.0 and -0.0 are equal since they both
map to the same real value, 0. A NaN does not map to any real
number and is not equal to any value, including itself.
double values a and b is implemented by the expression
Double.doubleToRawLongBits(a) == Double.doubleToRawLongBits(b)+0.0 and -0.0 are
distinguished from each other and every bit pattern encoding a NaN
is distinguished from every other bit pattern encoding a NaN.
+0.0 and -0.0 are distinguished from each other.
Double.doubleToLongBits(a) == Double.doubleToLongBits(b)
Double.valueOf(a).equals(Double.valueOf(b))
Double.compare(a, b) == 0
a and b, if
neither of a and b is zero or NaN, then the three
relations numerical equality, bit-wise equivalence, and
representation equivalence of a and b have the same
true/false value. In other words, for binary
floating-point values, the three relations only differ if at least
one argument is zero or NaN.
Values of the float type have 24
bits of precision and values of the double type have
53 bits of precision. Therefore, since 0.1
is a repeating fraction in base 2 with a four-bit repeat, 0.1f != 0.1d. In more detail, including hexadecimal
floating-point literals:
0.1f (0x1.99999a0000000p-4f) is
0.100000001490116119384765625.
0.1d (0x1.999999999999ap-4d) is
0.1000000000000000055511151231257827021181583404541015625.
float and double values,
respectively, to the numerical value of 0.1. These results are
consistent with a float value having the equivalent of 6 to
9 digits of decimal precision and a double value having the
equivalent of 15 to 17 digits of decimal precision. (The
equivalent precision varies according to the different relative
densities of binary and decimal values at different points along the
real number line.)
This representation hazard of decimal fractions is one reason to
use caution when storing monetary values as float or double. Alternatives include:
BigDecimal to store decimal
fractional values exactly
For each finite floating-point value and a given floating-point
type, there is a contiguous region of the real number line which
maps to that value. Under the default round to nearest rounding
policy (JLS 15.4), this contiguous region for a value is
typically one ulp (unit in the last place)
wide and centered around the exactly representable value. (At
exponent boundaries, the region is asymmetrical and larger on the
side with the larger exponent.) For example, for 0.1f, the
region can be computed as follows:
// Numeric values listed are exact values
oneTenthApproxAsFloat = 0.100000001490116119384765625;
ulpOfoneTenthApproxAsFloat = Math.ulp(0.1f) = 7.450580596923828125E-9;
// Numeric range that is converted to the float closest to 0.1, _excludes_ endpoints
(oneTenthApproxAsFloat - ½ulpOfoneTenthApproxAsFloat, oneTenthApproxAsFloat + ½ulpOfoneTenthApproxAsFloat) =
(0.0999999977648258209228515625, 0.1000000052154064178466796875)
In particular, a correctly rounded decimal to binary conversion
of any string representing a number in this range, say by Float#parseFloat(String), will be converted to the same value:
Float.parseFloat("0.0999999977648258209228515625000001"); // rounds up to oneTenthApproxAsFloat Float.parseFloat("0.099999998"); // rounds up to oneTenthApproxAsFloat Float.parseFloat("0.1"); // rounds up to oneTenthApproxAsFloat Float.parseFloat("0.100000001490116119384765625"); // exact conversion Float.parseFloat("0.100000005215406417846679687"); // rounds down to oneTenthApproxAsFloat Float.parseFloat("0.100000005215406417846679687499999"); // rounds down to oneTenthApproxAsFloat
Similarly, an analogous range can be constructed for the double type based on the exact value of double
approximation to 0.1d and the numerical value of Math.ulp(0.1d) and likewise for other particular numerical values
in the float and double types.
As seen in the above conversions, compared to the exact numerical value the operation would have without rounding, the same floating-point value as a result can be:
0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f; // Numerical value of computed sum: 1.00000011920928955078125, // the next floating-point value larger than 1.0f, equal to Math.nextUp(1.0f).
0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d; // Numerical value of computed sum: 0.99999999999999988897769753748434595763683319091796875, // the next floating-point value smaller than 1.0d, equal to Math.nextDown(1.0d).
double d = 0.0; while (d != 1.0) { // Surprising infinite loop d += 0.1; // Sum never _exactly_ equals 1.0 }
double d = 0.0; for (int i = 0; i < 10; i++) { d += 0.1; } // Value of d is equal to Math.nextDown(1.0).
<, <=, >, >=):
double d = 0.0; while (d <= 1.0) { d += 0.1; } // Value of d approximately 1.0999999999999999
<, <=, >, and >=
| Modifier and Type | Field and Description |
|---|---|
| public static final int | BYTES
The number of bytes used to represent a |
| public static final int | MAX_EXPONENT
Maximum exponent a finite |
| public static final double | MAX_VALUE
A constant holding the largest positive finite value of type
|
| public static final int | MIN_EXPONENT
Minimum exponent a normalized |
| public static final double | MIN_NORMAL
A constant holding the smallest positive normal value of type
|
| public static final double | MIN_VALUE
A constant holding the smallest positive nonzero value of type
|
| public static final double | NaN
A constant holding a Not-a-Number (NaN) value of type |
| public static final double | NEGATIVE_INFINITY
A constant holding the negative infinity of type
|
| public static final double | POSITIVE_INFINITY
A constant holding the positive infinity of type
|
| public static final int | PRECISION
The number of bits in the significand of a |
| private static final long | serialVersionUID
use serialVersionUID from JDK 1.0.2 for interoperability
|
| public static final int | SIZE
The number of bits used to represent a |
| public static final Class | TYPE
The |
| private final double | value
The value of the Double. |
| Access | Constructor and Description |
|---|---|
| public | Double(double
the value to be represented by the value)Double.
Deprecated
since 9. It is rarely appropriate to use this constructor.
Constructs a newly allocated |
| public |
| Modifier and Type | Method and Description |
|---|---|
| public byte | Returns: thedouble value represented by this object
converted to type byteOverrides java. Returns the value of this |
| public static int | Returns: the value0 if d1 is
numerically equal to d2; a value less than
0 if d1 is numerically less than
d2; and a value greater than 0
if d1 is numerically greater than
d2.the first d1, double double to comparethe second d2)double to compareCompares the two specified |
| public int | Returns: the value0 if anotherDouble is
numerically equal to this Double; a value
less than 0 if this Double
is numerically less than anotherDouble;
and a value greater than 0 if this
Double is numerically greater than
anotherDouble.the anotherDouble)Double to be compared.Implements java. Compares two |
| public Optional | describeConstable()
Implements java. Returns an |
| public static long | Returns: the bits that represent the floating-point number.a value)double precision floating-point number.Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout. |
| public static native long | Returns: the bits that represent the floating-point number.a value)double precision floating-point number.Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout, preserving Not-a-Number (NaN) values. |
| public double | Returns: thedouble value represented by this objectImplements abstract java. Returns the |
| public boolean | equals(Object obj)
Overrides java. Compares this object against the specified object. |
| public float | Returns: thedouble value represented by this object
converted to type floatImplements abstract java. Returns the value of this |
| public int | Returns: ahash code value for this object.Overrides java. Returns a hash code for this |
| public static int | Returns: a hash code value for adouble value.the value to hash value)Returns a hash code for a |
| public int | Returns: thedouble value represented by this object
converted to type intImplements abstract java. Returns the value of this |
| public static boolean | Returns: true if the argument is a finite
floating-point value, false otherwise.the d)double value to be testedReturns |
| public static boolean | Returns: true if the value of the argument is positive
infinity or negative infinity; false otherwise.the value to be tested. v)Returns |
| public boolean | Returns: true if the value represented by this object is
positive infinity or negative infinity;
false otherwise.Returns |
| public static boolean | Returns: true if the value of the argument is NaN;
false otherwise.the value to be tested. v)Returns |
| public boolean | Returns: true if the value represented by this object is
NaN; false otherwise.Returns |
| public static native double | Returns: thedouble floating-point value with the same
bit pattern.any bits)long integer.Returns the |
| public long | Returns: thedouble value represented by this object
converted to type longImplements abstract java. Returns the value of this |
| public static double | |
| public static double | |
| public static double | Returns: thedouble value represented by the string
argument.the string to be parsed. s)Returns a new |
| public Double | Returns: the Double instanceignored lookupImplements java. Resolves this instance as a |
| public short | Returns: thedouble value represented by this object
converted to type shortOverrides java. Returns the value of this |
| public static double | Returns: the sum ofa and bthe first operand a, double the second operand b)Adds two |
| public static String | Returns: a hex string representation of the argument.the d)double to be converted.Returns a hexadecimal string representation of the
|
| public static String | Returns: a string representation of the argument.the d)double to be converted.Returns a string representation of the |
| public String | Returns: aString representation of this object.Overrides java. Returns a string representation of this |
| public static Double | |
| public static Double | Returns: aDouble instance representing d.a double value. d)Returns a |
| BYTES | back to summary |
|---|---|
| public static final int BYTES The number of bytes used to represent a
| |
| MAX_EXPONENT | back to summary |
|---|---|
| public static final int MAX_EXPONENT Maximum exponent a finite
| |
| MAX_VALUE | back to summary |
|---|---|
| public static final double MAX_VALUE A constant holding the largest positive finite value of type
| |
| MIN_EXPONENT | back to summary |
|---|---|
| public static final int MIN_EXPONENT Minimum exponent a normalized
| |
| MIN_NORMAL | back to summary |
|---|---|
| public static final double MIN_NORMAL A constant holding the smallest positive normal value of type
| |
| MIN_VALUE | back to summary |
|---|---|
| public static final double MIN_VALUE A constant holding the smallest positive nonzero value of type
| |
| NaN | back to summary |
|---|---|
| public static final double NaN A constant holding a Not-a-Number (NaN) value of type | |
| NEGATIVE_INFINITY | back to summary |
|---|---|
| public static final double NEGATIVE_INFINITY A constant holding the negative infinity of type
| |
| POSITIVE_INFINITY | back to summary |
|---|---|
| public static final double POSITIVE_INFINITY A constant holding the positive infinity of type
| |
| PRECISION | back to summary |
|---|---|
| public static final int PRECISION The number of bits in the significand of a
| |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID Hides java. use serialVersionUID from JDK 1.0.2 for interoperability | |
| SIZE | back to summary |
|---|---|
| public static final int SIZE The number of bits used to represent a
| |
| TYPE | back to summary |
|---|---|
| public static final Class<Double> TYPE The
| |
| value | back to summary |
|---|---|
| private final double value The value of the Double. | |
| Double | back to summary |
|---|---|
| public Double(double value)
Deprecated since 9. It is rarely appropriate to use this constructor. The static factory
Constructs a newly allocated
| |
| Double | back to summary |
|---|---|
| public Double(String s) throws NumberFormatException
Deprecated since 9. It is rarely appropriate to use this constructor.
Use Constructs a newly allocated
| |
| byteValue | back to summary |
|---|---|
| public byte byteValue() Overrides java. Returns the value of this
| |
| compare | back to summary |
|---|---|
| public static int compare(double d1, double d2) Compares the two specified Double.valueOf(d1).compareTo(Double.valueOf(d2)) API Note One idiom to implement representation equivalence on Double.compare(a, b) == 0
| |
| compareTo | back to summary |
|---|---|
| public int compareTo(Double anotherDouble) Implements java. Compares two
Double
objects imposed by this method is consistent with
equals; see this
discussion for details of floating-point comparison and
ordering.
API Note The inclusion of a total order idiom in the Java SE API predates the inclusion of that functionality in the IEEE 754 standard. The ordering of the totalOrder predicate chosen by IEEE 754 differs from the total order chosen by this method. While this method treats all NaN representations as being in the same equivalence class, the IEEE 754 total order defines an ordering based on the bit patterns of the NaN among the different NaN representations. The IEEE 754 order regards "negative" NaN representations, that is NaN representations whose sign bit is set, to be less than any finite or infinite value and less than any "positive" NaN. In addition, the IEEE order regards all positive NaN values as greater than positive infinity. See the IEEE 754 standard for full details of its total ordering.
| |
| describeConstable | back to summary |
|---|---|
| public Optional Implements java. Returns an | |
| doubleToLongBits | back to summary |
|---|---|
| public static long doubleToLongBits(double value) Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout. Bit 63 (the bit that is selected by the mask
If the argument is positive infinity, the result is
If the argument is negative infinity, the result is
If the argument is NaN, the result is
In all cases, the result is a
| |
| doubleToRawLongBits | back to summary |
|---|---|
| public static native long doubleToRawLongBits(double value) Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout, preserving Not-a-Number (NaN) values. Bit 63 (the bit that is selected by the mask
If the argument is positive infinity, the result is
If the argument is negative infinity, the result is
If the argument is NaN, the result is the In all cases, the result is a
| |
| doubleValue | back to summary |
|---|---|
| public double doubleValue() Implements abstract java. Returns the
| |
| equals | back to summary |
|---|---|
| public boolean equals(Object obj) Overrides java. Compares this object against the specified object. The result
is API Note This method is defined in terms of
| |
| floatValue | back to summary |
|---|---|
| public float floatValue() Implements abstract java. Returns the value of this API Note This method corresponds to the convertFormat operation defined in IEEE 754.
| |
| hashCode | back to summary |
|---|---|
| public int hashCode() Overrides java. Returns a hash code for this
where v is defined by:
| |
| hashCode | back to summary |
|---|---|
| public static int hashCode(double value) Returns a hash code for a
| |
| intValue | back to summary |
|---|---|
| public int intValue() Implements abstract java. Returns the value of this API Note This method corresponds to the convertToIntegerTowardZero operation defined in IEEE 754.
| |
| isFinite | back to summary |
|---|---|
| public static boolean isFinite(double d) Returns API Note This method corresponds to the isFinite operation defined in IEEE 754.
| |
| isInfinite | back to summary |
|---|---|
| public static boolean isInfinite(double v) Returns API Note This method corresponds to the isInfinite operation defined in IEEE 754.
| |
| isInfinite | back to summary |
|---|---|
| public boolean isInfinite() Returns
| |
| isNaN | back to summary |
|---|---|
| public static boolean isNaN(double v) Returns API Note This method corresponds to the isNaN operation defined in IEEE 754.
| |
| isNaN | back to summary |
|---|---|
| public boolean isNaN() Returns
| |
| longBitsToDouble | back to summary |
|---|---|
| public static native double longBitsToDouble(long bits) Returns the If the argument is If the argument is If the argument is any value in the range
In all other cases, let s, e, and m be three values that can be computed from the argument: int s = ((bits >> 63) == 0) ? 1 : -1; int e = (int)((bits >> 52) & 0x7ffL); long m = (e == 0) ? (bits & 0xfffffffffffffL) << 1 : (bits & 0xfffffffffffffL) | 0x10000000000000L; Note that this method may not be able to return a
| |
| longValue | back to summary |
|---|---|
| public long longValue() Implements abstract java. Returns the value of this API Note This method corresponds to the convertToIntegerTowardZero operation defined in IEEE 754.
| |
| max | back to summary |
|---|---|
| public static double max(double a, double b) Returns the greater of two API Note This method corresponds to the maximum operation defined in IEEE 754.
| |
| min | back to summary |
|---|---|
| public static double min(double a, double b) Returns the smaller of two API Note This method corresponds to the minimum operation defined in IEEE 754.
| |
| parseDouble | back to summary |
|---|---|
| public static double parseDouble(String s) throws NumberFormatException Returns a new
| |
| resolveConstantDesc | back to summary |
|---|---|
| public Double resolveConstantDesc(MethodHandles. Implements java. Resolves this instance as a
| |
| shortValue | back to summary |
|---|---|
| public short shortValue() Overrides java. Returns the value of this
| |
| sum | back to summary |
|---|---|
| public static double sum(double a, double b) Adds two API Note This method corresponds to the addition operation defined in IEEE 754.
| |
| toHexString | back to summary | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| public static String toHexString(double d) Returns a hexadecimal string representation of the
API Note This method corresponds to the convertToHexCharacter operation defined in IEEE 754.
| |||||||||||||||||||||||
| toString | back to summary |
|---|---|
| public static String toString(double d) Returns a string representation of the
A decimal is a number of the form s×10i for some (unique) integers s > 0 and i such that s is not a multiple of 10. These integers are the significand and the exponent, respectively, of the decimal. The length of the decimal is the (unique) positive integer n meeting 10n-1 ≤ s < 10n. The decimal dm for a finite positive m is defined as follows:
The (uniquely) selected decimal dm
is then formatted.
Let s, i and n be the significand, exponent and
length of dm, respectively.
Further, let e = n + i - 1 and let
s1…sn
be the usual decimal expansion of s.
Note that s1 ≠ 0
and sn ≠ 0.
Below, the decimal point
To create localized string representations of a floating-point
value, use subclasses of API Note This method corresponds to the general functionality of the
convertToDecimalCharacter operation defined in IEEE 754;
however, that operation is defined in terms of specifying the
number of significand digits used in the conversion.
Code to do such a conversion in the Java platform includes
converting the double d = 0.1; int digits = 25; BigDecimal bd = new BigDecimal(d); String result = bd.round(new MathContext(digits, RoundingMode.HALF_UP)); // 0.1000000000000000055511151
| |
| toString | back to summary |
|---|---|
| public String toString() Overrides java. Returns a string representation of this
| |
| valueOf | back to summary |
|---|---|
| public static Double valueOf(String s) throws NumberFormatException Returns a If Leading and trailing whitespace characters in where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are as defined in the lexical structure sections of The Java Language Specification, except that underscores are not accepted between digits. If s does not have the form of
a FloatValue, then a NumberFormatException
is thrown. Otherwise, s is regarded as
representing an exact decimal value in the usual
"computerized scientific notation" or as an exact
hexadecimal value; this exact numerical value is then
conceptually converted to an "infinitely precise"
binary value that is then rounded to type double
by the usual round-to-nearest rule of IEEE 754 floating-point
arithmetic, which includes preserving the sign of a zero
value.
Note that the round-to-nearest rule also implies overflow and
underflow behaviour; if the exact value of s is large
enough in magnitude (greater than or equal to (MAX_VALUE + ulp(MAX_VALUE)/2),
rounding to double will result in an infinity and if the
exact value of s is small enough in magnitude (less
than or equal to MIN_VALUE/2), rounding to float will
result in a zero.
Finally, after rounding a Double object representing
this double value is returned.
Note that trailing format specifiers, specifiers that
determine the type of a floating-point literal
( To avoid calling this method on an invalid string and having
a final String Digits = "(\\p{Digit}+)"; final String HexDigits = "(\\p{XDigit}+)"; // an exponent is 'e' or 'E' followed by an optionally // signed decimal integer. final String Exp = "[eE][+-]?"+Digits; final String fpRegex = ("[\\x00-\\x20]*"+ // Optional leading "whitespace" "[+-]?(" + // Optional sign character "NaN|" + // "NaN" string "Infinity|" + // "Infinity" string // A decimal floating-point string representing a finite positive // number without a leading sign has at most five basic pieces: // Digits . Digits ExponentPart FloatTypeSuffix // // Since this method allows integer-only strings as input // in addition to strings of floating-point literals, the // two sub-patterns below are simplifications of the grammar // productions from section 3.10.2 of // The Java Language Specification. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+ // . Digits ExponentPart_opt FloatTypeSuffix_opt "(\\.("+Digits+")("+Exp+")?)|"+ // Hexadecimal strings "((" + // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "(\\.)?)|" + // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" + ")[pP][+-]?" + Digits + "))" + "[fFdD]?))" + "[\\x00-\\x20]*");// Optional trailing "whitespace" if (Pattern.matches(fpRegex, myString)) Double.valueOf(myString); // Will not throw NumberFormatException else { // Perform suitable alternative action } API Note To interpret localized string representations of a
floating-point value, or string representations that have
non-ASCII digits, use NumberFormat.getInstance(l).parse(s).doubleValue(); l is the desired locale, or
java. if locale insensitive.
API Note This method corresponds to the convertFromDecimalCharacter and convertFromHexCharacter operations defined in IEEE 754.
| |
| valueOf | back to summary |
|---|---|
| public static Double valueOf(double d) Returns a
| |