85

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

Selvin
  • 12,333
  • 17
  • 59
  • 80
  • 2
    How about reading the documentation of the Double class? I am sure there is some method that will do the conversion. – Ingo Mar 23 '11 at 11:04
  • 1
    You are talking about an error because of incompatible types. Then it's usually a good idea to show the code snippet you have tried. That helps giving better answers. – jmg Mar 23 '11 at 11:05
  • 1
    @Ingo i did googling and tried my best after that only I came to SO. Thanks for helping hands :) – Selvin Mar 23 '11 at 11:19
  • 1
    http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#intValue() – Selvin Apr 18 '14 at 16:00

5 Answers5

184

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.

Rishabh Srivastava
  • 3,683
  • 2
  • 30
  • 58
crusam
  • 6,140
  • 6
  • 40
  • 68
  • sorry guys. I tried google and found double to int only. So then I came to disturb our Friends here :) That works. many thanks – Selvin Mar 23 '11 at 11:17
  • This is a *really* bad idea in loops. It's much better to work with primitives. – ingyhere Apr 04 '14 at 02:39
  • http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#intValue() – Selvin Apr 18 '14 at 15:59
  • why I did this and it gives me an error `double cannot be dereferenced`? – Tony Chen Oct 13 '16 at 01:26
  • most likely you use a primitive type double and not Double, but you may want to ask that in your own question to provide more context. – crusam Oct 13 '16 at 06:42
27

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)
gipinani
  • 14,038
  • 12
  • 56
  • 85
24
double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

Daneos
  • 249
  • 2
  • 3
11

try casting the value

double d = 1.2345;
long l = (long) d;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2
int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();
S1LENT WARRIOR
  • 11,704
  • 4
  • 46
  • 60
Usman
  • 1,116
  • 11
  • 13