383

Any way to cast java.lang.Double to java.lang.Integer?

It throws an exception

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"

0

19 Answers 19

592

You need to explicitly get the int value using method intValue() like this:

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5

Or

double d = 5.25;
int i = (int) d;
0
493

A Double is not an Integer, so the cast won't work. Note the difference between the Double class and the double primitive. Also note that a Double is a Number, so it has the method intValue, which you can use to get the value as a primitive int.

7
  • 2
    Ok not to cast. I need to get Integer object from Double, not 13.22222 but 13, for example.
    – 4lex1v
    Commented Feb 1, 2012 at 19:57
  • 198
    just call intValue() then.
    – hvgotcodes
    Commented Feb 1, 2012 at 19:58
  • 7
    Don't forget to handle nulls.
    – pimlottc
    Commented Mar 27, 2014 at 20:01
  • 15
    Note that this merely returns the integer part of the Double, so for 13.666667 or even 13.9, you'll get 13, not 14. If you want the nearest integer, refer to my answer: stackoverflow.com/a/24816336/1450294 Commented Jul 18, 2014 at 2:18
  • 2
    if you look at the implementation of intValue(), it just casts the double to an int. Commented Sep 30, 2015 at 9:38
61

I think it's impossible to understand the other answers without covering the pitfalls and reasoning behind it.

You cannot directly cast an Integer to a Double object. Also Double and Integer are immutable objects, so you cannot modify them in any way.

Each numeric class has a primitive alternative (Double vs double, Integer vs int, ...). Note that these primitives start with a lowercase character (e.g. int). That tells us that they aren't classes/objects. Which also means that they don't have methods. By contrast, the classes (e.g. Integer) act like boxes/wrappers around these primitives, which makes it possible to use them like objects.

Strategy:

To convert a Double to an Integer you would need to follow this strategy:

  1. Convert the Double object to a primitive double. (= "unboxing")
  2. Convert the primitive double to a primitive int. (= "casting")
  3. Convert the primitive int back to an Integer object. (= "boxing")

In code:

// starting point
Double myDouble = Double.valueOf(10.0);

// step 1: unboxing
double dbl = myDouble.doubleValue();

// step 2: casting
int intgr = (int) dbl;

// step 3: boxing
Integer val = Integer.valueOf(intgr);

Actually there is a shortcut. You can unbox immediately from a Double straight to a primitive int. That way, you can skip step 2 entirely.

Double myDouble = Double.valueOf(10.0);
Integer val = Integer.valueOf(myDouble.intValue()); // the simple way

Pitfalls:

However, there are a lot of things that are not covered in the code above. The code-above is not null-safe.

Double myDouble = null;
Integer val = Integer.valueOf(myDouble.intValue()); // will throw a NullPointerException

// a null-safe solution:
Integer val = (myDouble == null)? null : Integer.valueOf(myDouble.intValue());

Now it works fine for most values. However integers have a very small range (min/max value) compared to a Double. On top of that, doubles can also hold "special values", that integers cannot:

  • 1/0 = +infinity
  • -1/0 = -infinity
  • 0/0 = undefined (NaN)

So, depending on the application, you may want to add some filtering to avoid nasty Exceptions.

Then, the next shortcoming is the rounding strategy. By default Java will always round down. Rounding down makes perfect sense in all programming languages. Basically Java is just throwing away some of the bytes. In financial applications you will surely want to use half-up rounding (e.g.: round(0.5) = 1 and round(0.4) = 0).

// null-safe and with better rounding
long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = Integer.valueOf(rounded);

Auto-(un)boxing

You could be tempted to use auto-(un)boxing in this, but I wouldn't. If you're already stuck now, then the next examples will not be that obvious neither. If you don't understand the inner workings of auto-(un)boxing then please don't use it.

Integer val1 = 10; // works
Integer val2 = 10.0; // doesn't work

Double val3 = 10; // doesn't work
Double val4 = 10.0; // works

Double val5 = null; 
double val6 = val5; // doesn't work (throws a NullPointerException)

I guess the following shouldn't be a surprise. But if it is, then you may want to read some article about casting in Java.

double val7 = (double) 10; // works
Double val8 = (Double) Integer.valueOf(10); // doesn't work
Integer val9 = (Integer) 9; // pure nonsense

Prefer valueOf:

Also, don't be tempted to use new Integer() constructor (as some other answers propose). The valueOf() methods are better because they use caching. It's a good habit to use these methods, because from time to time they will save you some memory.

long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = new Integer(rounded); // waste of memory
1
  • 1
    this in my opinion is the best answer
    – Thor
    Commented Jul 4, 2018 at 6:24
41

I see three possibilities. The first two cut off the digits, the last one rounds to the nearest Integer.

double d = 9.5;
int i = (int)d;
//i = 9

Double D = 9.5;
int i = Integer.valueOf(D.intValue());
//i = 9

double d = 9.5;
Long L = Math.round(d);
int i = Integer.valueOf(L.intValue());
//i = 10
1
  • 23
    There's no need for the Integer.valueOf if you are going to store the result in a primitieve int. Your code forces Java to perform an unnecessary box and unbox.
    – bvdb
    Commented Jan 24, 2015 at 9:26
25

Indeed, the simplest way is to use intValue(). However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:

Integer integer = Integer.valueOf((int) Math.round(myDouble)));

And don't forget the null case:

Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));

Math.round() handles odd duck cases, like infinity and NaN, with relative grace.

3
  • 2
    Why do you need Integer.valueOf if you cast Math.round result to int?
    – Eran H.
    Commented Nov 17, 2015 at 17:05
  • @EranH.: As of Java 1.5, you probably don't—autoboxing means the code likely ends up doing the same thing either way. But I think this code is clearer for people who haven't quite grasped objects and primitives yet. Commented Nov 19, 2015 at 3:43
  • Whomever down-voted this answer: You'll help the community a lot more if you explain why, and it might even help you find out why it didn't work for you. Down-voting without explanation, OTOH, is unhelpful for everyone, and it comes across as cowardly. Commented Mar 12, 2018 at 23:50
23

Like this:

Double foo = 123.456;
Integer bar = foo.intValue();
0
14
double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13
1
  • 2
    The question was specifically about the wrapper classes. This answer is about primitives. Commented Sep 25, 2014 at 19:56
8

Simply do it this way...

Double d = 13.5578;
int i = d.intValue();
System.out.println(i);
7
Double d = 100.00;
Integer i = d.intValue();

One should also add that it works with autoboxing.

Otherwise, you get an int (primitive) and then can get an Integer from there:

Integer i = new Integer(d.intValue());
1
  • 2
    Don't use new Integer(int), instead use Integer.valueOf(int) , which has a cache for small integers, such as this one.
    – bvdb
    Commented Oct 27, 2014 at 11:52
6

Call intValue() on your Double object.

1
  • 2
    Seems like a repeat of the earlier answers.
    – Pang
    Commented Jun 5, 2017 at 1:58
4

You can do that by using "Narrowing or Explicit type conversion", double → long → int. I hope it will work.

double d = 100.04;
long l = (long)d; // Explicit type casting required
int i = (int)l;    // Explicit type casting required

PS: It will give 0 as double has all the decimal values and nothing on the left side. In case of 0.58, it will narrow it down to 0. But for others it will do the magic.

4

Try this one

double doubleValue = 6.5;Double doubleObj = new Double(doubleValue);int intResult = doubleObj.intValue();
3

Double and Integer are wrapper classes for Java primitives for double and int respectively. You can cast between those, but you will lose the floating point. That is, 5.4 casted to an int will be 5. If you cast it back, it will be 5.0.

1

Alternatively, one can first cast to primitive double, then cast to int, letting it be autoboxed to Integer.

Double d = 20.3;
Integer i = (int) (double) d; //20
//To obtain primitive:
int i2 = (int) (double) d;
0

Simply use the intValue method of Double

Double initialValue = 7.12;
int finalValue = initialValue.intValue();
1
  • 2
    Seems like a repeat of the other answers.
    – Pang
    Commented Jun 5, 2017 at 1:44
0

Use the doubleNumber.intValue(); method.

1
  • 2
    Seems like a repeat of the other answers.
    – Pang
    Commented Jun 5, 2017 at 1:44
0

First thing you should use Double not double.

Example

int intResult = newDoubleObj.intValue();

-1

Memory efficient, as it will share the already created instance of Double.

Double.valueOf(Math.floor(54644546464/60*60*24*365)).intValue()
1
  • is there any reason for the Math.floor(...) ? intValue() always floors anyway.
    – bvdb
    Commented May 3, 2019 at 14:24
-3

It's worked for me. Try this:

double od = Double.parseDouble("1.15");
int oi = (int) od;

Not the answer you're looking for? Browse other questions tagged or ask your own question.