To convert a double
value to an int
value in Java, you can use the intValue()
method of the Double
class. Here’s an example:
double doubleValue = 3.14159; int intValue = (int) doubleValue; // cast double to int
Alternatively, you can use the Math.round()
method to round the double
value to the nearest int
value and then cast it to an int
. Here’s an example:
double doubleValue = 3.14159; int intValue = (int) Math.round(doubleValue); // round double to int and cast
Note that when casting a double
value to an int
value, the decimal part of the double
value will be truncated.
Java double to int Example: Typecasting
Here’s an example of converting a double
value to an int
value in Java using typecasting:
double myDouble = 3.14159; int myInt = (int) myDouble; System.out.println("Double value: " + myDouble); System.out.println("Int value: " + myInt);
In this example, we first declare a double
variable myDouble
with the value 3.14159
. Then we use typecasting to convert the double
value to an int
value and store it in the myInt
variable.
The (int)
in (int) myDouble
is the typecast operator. It tells the compiler to treat the double
value as an int
value. The decimal part of the double
value is truncated, and the resulting int
value is stored in myInt
.
The output of the above code would be:
Double value: 3.14159 Int value: 3
As you can see, the double
value 3.14159
is truncated to 3
when it is converted to an int
value using typecasting.
Java Double to int Example: intValue() method
Here’s an example of converting a Double
object to an int
value in Java using the intValue()
method:
Double myDouble = 3.14159; int myInt = myDouble.intValue(); System.out.println("Double value: " + myDouble); System.out.println("Int value: " + myInt);
In this example, we first declare a Double
object myDouble
with the value 3.14159
. Then we use the intValue()
method to convert the Double
object to an int
value and store it in the myInt
variable.
The intValue()
method of the Double
class returns the value of the Double
object as an int
. The decimal part of the Double
value is truncated, and the resulting int
value is returned.
The output of the above code would be:
Double value: 3.14159 Int value: 3
As you can see, the Double
value 3.14159
is truncated to 3
when it is converted to an int
value using the intValue()
method.