null
null

Reputation: 2140

Casting Double object to int

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

Answers (3)

VMoza
VMoza

Reputation: 157

In your case you use

Double.intValue()

as a method to convert the Double Object to Integer.

Upvotes: 0

Moni
Moni

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

Louis Wasserman
Louis Wasserman

Reputation: 198014

Double.intValue()

is the provided method that does that conversion.

Upvotes: 7

Related Questions