In this tutorial, you will learn how to convert a double
value to an int
in Java. We’ll explore explicit casting, how to handle the decimal part, and provide examples to demonstrate the conversion process.
Java – Convert double to int
Converting double to int in Java – In Java, converting a double
to an int
requires explicit casting because double
is a floating-point type while int
is an integer type. This conversion will truncate the decimal part of the double
value, returning only the whole number part.
Explicit Conversion from double to int
To convert a double
to an int
in Java, you need to use an explicit cast. This conversion will drop the decimal part, keeping only the integer portion of the number.
Example of Explicit Conversion
public class DoubleToIntExample {
public static void main(String[] args) {
double doubleVal = 9.99;
int intVal = (int) doubleVal; // Explicit conversion from double to int
System.out.println("Double value: " + doubleVal);
System.out.println("Int value after conversion: " + intVal);
}
}
Output
Double value: 9.99
Int value after conversion: 9
In this example, the double
value 9.99
is explicitly cast to an int
, resulting in 9
as the decimal portion is truncated.
Rounding Before Conversion
If you want to round the double
value to the nearest integer before converting it to an int
, you can use Math.round()
. This method rounds the double
value to the nearest whole number and returns a long
, which can then be cast to an int
.
Example of Rounding Before Conversion
public class DoubleToIntExample {
public static void main(String[] args) {
double doubleVal = 9.99;
int intVal = (int) Math.round(doubleVal); // Rounding and converting to int
System.out.println("Double value: " + doubleVal);
System.out.println("Int value after rounding: " + intVal);
}
}
Output
Double value: 9.99
Int value after rounding: 10
In this example, Math.round()
rounds 9.99
up to 10
before converting it to an int
.
Conclusion
Converting a double
to an int
in Java requires explicit casting, which truncates the decimal part. If rounding is desired, use Math.round()
to achieve the nearest whole number before converting. Be cautious, as any decimal part will be removed in the conversion.