How to convert a double to an int
Short answer
The (int) cast drops the fractional part:
void main() {
double price = 9.99;
int whole = (int) price;
IO.println(whole);
}Output:
9With rounding
To round to the nearest integer, call Math.round() first. It returns a long, so an int needs one more cast:
void main() {
double price = 9.99;
int rounded = (int) Math.round(price);
IO.println(rounded);
}Output:
10Without losing data
Math.toIntExact() throws if the long does not fit into an int:
void main() {
IO.println(Math.toIntExact(Math.round(1e9)));
IO.println(Math.toIntExact(Math.round(1e10)));
}Output:
1000000000
Exception in thread "main" java.lang.ArithmeticException: integer overflowCommon mistake
Casting values that are too large, and NaN. Java does not throw — it silently uses the limit or zero:
void main() {
IO.println((int) 1e10);
IO.println((int) Double.NaN);
IO.println((int) -1e10);
}Output:
2147483647
0
-2147483648Functions used in this recipe
- Math.round() — Rounds a number to the nearest integer.
- ArithmeticException — Thrown on an invalid arithmetic operation, such as integer division by zero.