Reputation: 2140
How can I convert from a Double object to an int? The following code works but seems slightly unconventional (with casting twice):
Double d = new Double(4.0);
int i = (int)(double)d;
When I try int i = (int)d
, I get an error from Eclipse (Cannot cast from Double to int
), which makes sense. Nevertheless, is there a simpler way of converting a Double object to an int?
Upvotes: 1
Views: 3709
Reputation: 157
In your case you use
Double.intValue()
as a method to convert the Double Object to Integer.
Upvotes: 0
Reputation: 433
If you cast double to int you will loss decimal value.. so 4.99 double become 4 int. If still want to convert than try-
int i = d.intValue();
Upvotes: 0
Reputation: 198014
Double.intValue()
is the provided method that does that conversion.
Upvotes: 7