CKTIS / Java
Number.doubleValue() — convert to double
Get a `Number` object's value as a primitive `double`. Whether the result is exact depends on the object's actual subtype and whether the value can be represented as a `double`.
Version: Java SE 21
Syntax
public abstract double doubleValue();
// n is a non-null Number reference:
double value = n.doubleValue();Number.doubleValue() is an abstract, no-argument instance method declared in java.lang.Number. Calling n.doubleValue() returns a primitive double, not a Double object. Even when n is declared as Number, Java uses the implementation for the object's actual class.
Every Integer value converts exactly, but some Long values must be rounded. A BigDecimal conversion can lose precision even when the result is finite, and it can return infinity with the appropriate sign if the magnitude is too large. If a calculation must be exact, don't switch to double when it cannot represent the value exactly.
If n is null, the call throws NullPointerException. This method converts the value of an existing numeric object; it does not parse text. To read a number from a String, use Double.parseDouble(String).
Examples
public class NumberDoubleValueDemo {
public static void main(String[] args) {
Number small = Integer.valueOf(42);
double value = small.doubleValue();
System.out.println(value);
System.out.println(value * 2);
long original = 9_007_199_254_740_993L;
Number large = Long.valueOf(original);
double rounded = large.doubleValue();
System.out.println(original);
System.out.println((long) rounded);
}
}Result
42.0 84.0 9007199254740993 9007199254740992
The first two lines show the exact `42.0` before multiplication by `2` and the result `84.0`. The last two compare the original `long` with the result of converting to `double` and back to `long`. The `(long)` cast lets you print the rounded value as an integer here; it does not restore lost precision.
Related lessons
- Java · Lesson 9 · Advanced · Version: 2
- Java · Lesson 58 · Basic · Version: 2
- Java · Lesson 59 · Basic · Version: 2
Sources
- Java SE 21 API — Number.doubleValue()
- Java SE 21 API — Integer.doubleValue()
- Java SE 21 API — Long.doubleValue()
- Java SE 21 API — BigDecimal.doubleValue()
- Java SE 21 API — Double.parseDouble(String)
- Java Language Specification, Java SE 21 — §5.1.2 Widening Primitive Conversion
- Java Language Specification, Java SE 21 — §5.1.3 Narrowing Primitive Conversion
- Java Language Specification, Java SE 21 — §15.12.4.4 Locate Method to Invoke