In Java, you can convert a double to an int by using explicit type casting. Here’s an example of how to do it:
Example:
public class Main {
public static void main(String[] args) {
double myDouble = 11.75;
// Converting double to int using type casting
int myInt = (int) myDouble;
System.out.println("Double value: " + myDouble);
System.out.println("Converted int value: " + myInt);
}
}
Output:
- Double value: 11.75
- Converted int value: 11
Explanation:
1. Casting: The (int) before the myDouble variable forces the conversion of the double to an int.
2. Behavior: This conversion truncates the decimal part, so it doesn’t round the number but simply removes everything after the decimal point. For example, 11.75 becomes 11.
2. Using Math.round()
If you need rounding instead of truncation, you can use Math.round():
Example:
public class Main {
public static void main(String[] args) {
double myDouble = 11.75;
// Rounding the double to the nearest integer
int myInt = (int) Math.round(myDouble);
System.out.println("Double value: " + myDouble);
System.out.println("Rounded int value: " + myInt);
}
}
Output:
- Double value: 11.75
- Rounded int value: 12
Note: In this case, Math.round() rounds the value to the nearest whole number before converting it to an int.