How to convert Double to int directly?

Java

Java Problem Overview


May be this is silly question. I want to get rid of the fractional part of the Double number. But I cant do that. It shows the error that incompatible types. What to do?

Double to int conversion in one line....please help thanks

Java Solutions


Solution 1 - Java

If you really should use Double instead of double you even can get the int Value of Double by calling:

Double d = new Double(1.23);
int i = d.intValue();

Else its already described by Peter Lawreys answer.

Solution 2 - Java

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

Solution 3 - Java

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

Solution 4 - Java

try casting the value

double d = 1.2345;
long l = (long) d;

Solution 5 - Java

int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSelvinView Question on Stackoverflow
Solution 1 - JavacrusamView Answer on Stackoverflow
Solution 2 - JavagipinaniView Answer on Stackoverflow
Solution 3 - JavaDaneosView Answer on Stackoverflow
Solution 4 - JavaPeter LawreyView Answer on Stackoverflow
Solution 5 - JavaUsmanView Answer on Stackoverflow