In Java, you can convert a double
to an int
using type casting or by using the Math.round()
method depending on how you want the rounding to behave. Here are a few examples:
1. Type Casting (Truncating Decimal)
This method simply drops the decimal part and keeps the integer part.
double myDouble = 9.99;
int myInt = (int) myDouble; // myInt will be 9
2. Using Math.round()
(Rounding to the Nearest Integer)
If you want to round the double
value to the nearest integer, you can use Math.round()
. This method returns a long
, so you’ll need to cast it to an int
.
double myDouble = 9.99;
int myInt = (int) Math.round(myDouble); // myInt will be 10
3. Using Math.floor()
or Math.ceil()
(Rounding Down or Up)
If you want to round down (always to the lower integer) or up (always to the higher integer), you can use Math.floor()
or Math.ceil()
respectively, followed by casting to int
.
double myDouble = 9.99;
int myIntFloor = (int) Math.floor(myDouble); // myIntFloor will be 9 (rounds down)
int myIntCeil = (int) Math.ceil(myDouble); // myIntCeil will be 10 (rounds up)
Summary
- Type casting is the most straightforward and drops the decimal part.
Math.round()
rounds to the nearest integer.Math.floor()
andMath.ceil()
give you control over rounding down or up respectively.