In Java, you can convert a double
to an int
using type casting. Here’s how you can do it:
1. Using Type Casting (Explicit Casting)
When you convert a double
to an int
, the decimal part is truncated (not rounded). This means that the fractional part of the number is discarded.
Example:
public class Main {
public static void main(String[] args) {
double doubleValue = 45.67;
// Convert double to int
int intValue = (int) doubleValue;
System.out.println("Double Value: " + doubleValue); // 45.67
System.out.println("Integer Value: " + intValue); // 45
}
}
Explanation:
(int) doubleValue
: This is called explicit casting. It converts thedouble
value into anint
by truncating the decimal part (removes.67
in this case).
Output:
Double Value: 45.67
Integer Value: 45
2. Using Math.round()
for Rounding
If you want to round the double
to the nearest int
(instead of truncating), you can use the Math.round()
method. However, Math.round()
returns a long
, so you will need to cast it to int
after rounding.
Example:
public class Main {
public static void main(String[] args) {
double doubleValue = 45.67;
// Round double and convert to int
int intValue = (int) Math.round(doubleValue);
System.out.println("Double Value: " + doubleValue); // 45.67
System.out.println("Rounded Integer Value: " + intValue); // 46
}
}
Explanation:
Math.round(doubleValue)
: This method rounds thedouble
value to the nearestlong
.(int) Math.round(doubleValue)
: Cast the roundedlong
value toint
.
Output:
Double Value: 45.67
Rounded Integer Value: 46
3. Using Double.intValue()
(for Double
object)
If you’re working with Double
objects, you can use the intValue()
method to convert a Double
object to int
.
Example:
public class Main {
public static void main(String[] args) {
Double doubleValue = 45.67;
// Convert Double to int
int intValue = doubleValue.intValue();
System.out.println("Double Value: " + doubleValue); // 45.67
System.out.println("Integer Value: " + intValue); // 45
}
}
Output:
Double Value: 45.67
Integer Value: 45
Summary
- Type casting:
(int) doubleValue
truncates the decimal. - Math.round():
Math.round(doubleValue)
rounds the value before converting it toint
. Double.intValue()
: Used when working withDouble
objects, to convert the value.