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.
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:
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
, you will get an integer overflow or underflow.
If you need to handle large or floating-point numbers, you can use the BigDecimal
class or the double
type's