Java — Number doubleValue() Method
The Java Number doubleValue() method is used to convert the value of any number to its corresponding a double value.
A double is a primitive data type that is a 64-bit double precision floating-point value with a range greater than the float data type according to the IEEE 754 standards. It ranges from values 1.7976931348623157 x 10 308 to 4.9406564584124654 x 10 -324 (both positive and negative).
The default value and size of double is 0.0d and 8 bytes respectively.
Note − This conversion may involve rounding or truncation of the given number.
Syntax
Following is the syntax for Java Number doubleValue() method
Parameters
This method does not accept any parameters.
Return Value
This method returns the double value after conversion.
Example
The following example shows the usage of Java Number doubleValue() method. Here, we are instantiating an Integer object and initializing it. The method is then invoked on this object. The return value obtained will be the corresponding double value.
Let us compile and run the above program, this will produce the following result −
Example
Another way to implement the example above is seen as follows. An object is created after assigning an integer value to the Integer class reference variable. The method is then invoked on this object to obtain the double value.
Let us compile and run the above program, this will produce the following result −
Example
Like the previous example, a Long object is created here and the method is called on it to convert it into a double value.
The output for the program above is given as follows −
Example
The following example creates a Float object and invokes the method on this object. The method then converts the value assigned to this object into a double value.
On compiling and executing the given program, the output is displayed as follows −
Example
In here, the method invoked on a Byte object, converting the assigned byte value to a double value.
Once we compile and run the program, the output is printed as given below −
Class 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.
Floating-point Equality, Equivalence, and Comparison
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.equals 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.
- If 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.
- If 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 defines NaN arguments to be equal to each other and defines +0.0 to not be equal to -0.0 , restoring reflexivity. 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 .
Double vs doubleValue in Java
if a method returns a Double, why would we call the method «doubleValue» on it? it already returns a double and in calculations, appears to evaluate correctly.
4 Answers 4
Prior to Java 1.5 auto-boxing (and unboxing) didn’t exist in Java. So, you would need this to extract the underlying primitive from a Double.
You call ‘doubleValue’ on a Double object to convert from the boxed Object to the primitive data type. Since most of the time the Double is auto-unboxed to a double, you usually don’t need to do this, but if you want to be explicit in your conversion, you can call this method.
doubleValue returns a primitive double from the Double Object. Depending on the scenario, you would want to get the double out of a Double.
You’d call doubleValue if you need to obtain a double from a Double . The former is a primitive type, while the latter is a wrapper object type, which basically encapsulates a primitive value inside an immutable object. If possible (and I’m saying this without knowing exactly the purpose of your code), use double for all your calculations; only use Double if you need to store the values in a Collection or Map ; that’s because object types consume more memory and may be subject to casting operations.
It’s easy to mistake double with Double (same thing applies for the other primitive types vs. wrapper types), since the compiler will automatically convert from one to the other as needed in a process known as auto-boxing (and auto-unboxing), so a little care must be taken to use the correct type.
Русские Блоги
Java Начало 93 — Номер IntValue и DoubleValue Метод
проблема
В Java номер абстрактного класса — это суперкласс для Bigdecimal, Biginteger, Byte, Double, Float, Integer, длинные и короткие. Этот класс обеспечивает шесть способов, как показано на рисунке -1.
Возвращает указанное значение в виде байта.
Возвращает указанное значение в двойном.
Возвращает указанное значение в Float.
Возвращает указанное значение в форме INT.
Возвращает указанное значение в длинной форме
Возвращает указанное значение в короткой форме
В вышеупомянутых шести способах метод Floatvalue и метод DoubleValue могут включать округление; другие четыре метода могут включать округление или расход.
Этот случай требует метода IntValue и DoubleValue метода класса номера, то есть сначала определяют две переменные типа числа:
Требуется тип данных, к которому относятся d объекты и n объектов.
Затем объект D преобразуется в переменную типа INT и переменной двойной типы и выводится результат преобразования.
Наконец, объект n преобразуется в переменную типа int и переменной двойной типы и выводим результат преобразования.
Программа
Во-первых, создайте новый пакет и класс и создайте новый метод теста в классе.
Во-вторых, используйте код d.getClass (). Getname () и код n.getclass (). Getname () Получите тип данных, на который принадлежат объект d и объект n. Просто понимайте, что это может получить тип данных объекта, чтобы получить объект.
В-третьих, используя метод IntValue метода номера класса и метода DoubleValue, преобразуйте объекты D для переменных типа INT и переменные двойного типа и выводит результаты преобразования.
В-четвертых, используйте метод IntValue INTVALUE и метод DoubleValue, преобразуйте n объектов для переменных типа INT и переменные двойных типов и вывод преобразования.
Этот случай должен быть выполнен в соответствии со следующими шагами.
Шаг 1: Создайте пакет, класс и метод теста
Во-первых, класс по имени Testnumber недавно назван в пакете Day02, а затем новые методы испытаний в этом классе TestindubleValue, код выглядит следующим образом:
Шаг 2: Получите тип объекта, принадлежащего номеру класса
Используйте код D.getClass (). Getname () и код n.getclass (). Getname () Получите тип данных, к которым принадлежат d объекты d и n объектов. Просто понимайте, что это может получить тип данных объекта, чтобы получить объект. Код выглядит следующим образом:
Шаг 3: Беги
Run Step Ii TestValueAndubleValue Метод, результаты выходных данных консоли следующие:
Как видно из выхода, тип Doj Double Double, N Тип ремня является целым числом, поскольку 123,45. Прямое количество двойное. После того, как автоматическая упаковка преобразуется в двойной тип, двойной тип типа. Подклассы, типы подкласс Преобразование в тип родительского класса принадлежит автоматическому преобразованию типа, поэтому тип D является двойным, тот же тип N, является типом целого числа.
Шаг 4: Конвертируйте объекты d для переменных типа INT и переменные двойных типов, и выведите результат преобразования, код следующим образом:
Шаг 5: запустить
Пробег Метод TestIntValueAnddoubleValue, выходное содержание последнего вывода является:
Как видно из результата вывода, целочисленная часть объекта D взята после того, как объект D исходного типа двойного типа преобразуется в тип INT. Но никаких изменений после преобразования двойного типа.
Шаг 6: Преобразование n объектов для переменных типа INT и переменные двойных типов соответственно.
Используйте метод IntValue INTVALUE и метод DoubleValue, преобразуйте n объектов для переменных типа INT и переменные двойного типа и вывод результатов преобразования.
Шаг 7: Беги
Запустите метод TestIntValueAnddoubleValue снова, выходное содержание последнего вывода:
Как видно из выхода, объект n исходного целочисленного типа преобразуется в двойной тип, десятичное число сохраняется после десятичной точки. Тем не менее, нет никаких изменений после преобразования его в тип INT.