W3docs

Cast Double to Integer in Java

In Java, you can cast a double value to an int using the (int) operator. This will truncate the decimal part of the double and return the integer value.

In Java, you can cast a double value to an int using the (int) operator. This will truncate the decimal part of the double and return the integer value.

For example:

double d = 3.14;
int i = (int) d; // i will be 3

You can also use the Math.floor() method to round the double down to the nearest integer:

double d = 3.14;
int i = (int) Math.floor(d); // i will be 3

You can also use the Math.round() method to round the double to the nearest integer. Note that Math.round(double) returns a long, so a cast to int is required if you need an int variable:

double d = 3.14;
int i = (int) Math.round(d); // i will be 3

Note that if the double value is too large or too small to be represented as an int, casting will result in overflow or underflow. You can use Math.toIntExact() to safely convert and throw an exception if the value exceeds the int range:

double d = 3.14;
int i = Math.toIntExact(Math.round(d)); // throws ArithmeticException if out of int range

If you need to handle large numbers or precise decimal arithmetic, you can use the BigDecimal class:

double d = 3.14;
BigDecimal bd = BigDecimal.valueOf(d);
int i = bd.intValue(); // i will be 3