-1

How do I convert/cast a Double object to an int?

Double d = new Double(12.34);
int i = 12 //is what I'm looking for

If I had a double I would just use:

double z = 12.34;
int i = (int)z;

Note: I want it to truncate the Double (so 12.9 becomes 12) because I know that d actually was an integer that was converted to a Double. I.e. I want to call (int) on a Double.

Sheldon
  • 1,215
  • 1
  • 15
  • 29
  • I could not find a question that asked what I was looking for (i.e. Object to primitive) and want to provide the answer here so that it comes up in searches. The closest I found was: http://stackoverflow.com/questions/9102318/cast-double-to-integer-in-java – Sheldon Jan 06 '17 at 15:06
  • If you are unhappy with truncation (due to possible precision loss errors), then why don't you try `round()`? – Anton Samsonov Jan 06 '17 at 15:53
  • @AntonSamsonov I want the truncation. I am looking to call the (int) cast, but on a Double not a double. – Sheldon Jan 11 '17 at 12:06

2 Answers2

5

To perform this operation you need to call the intValue method on the Double object:

int i = d.intValue();

This method performs a cast, into an int value, on the double value wrapped within the Double object, d.

Note that it does not check for null before attempting this.

Sheldon
  • 1,215
  • 1
  • 15
  • 29
  • _This method performs a cast on the double value in Double_ if `d` is a `double`, then this will not be wrapped, this will not compile. Here this works because `d` is a `Double`. The explanation are wrong. A primitive value doesn't provide methods – AxelH Jan 11 '17 at 12:13
  • Correct, the question is how to perform a cast to int on a `Double` object. I've edited the explanation, does this make it clearer? – Sheldon Jan 11 '17 at 12:49
  • _This method performs a cast into an `int` value on the `double` value wrapped within the Double object, d._ would seems more logic. Because I keep reading that you are casting the `Double` in a `double` because this is not really clear – AxelH Jan 11 '17 at 12:58
  • @AxelH I agree, I've edited the answer as per your suggestion. – Sheldon Jan 11 '17 at 13:03
1

If you want to use a cast you can use

Double d = 12.34;
int i = (int) (double) d;

You can't cast from Double to int in one step.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130