87

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

4
  • 2
    How about reading the documentation of the Double class? I am sure there is some method that will do the conversion. Commented Mar 23, 2011 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. Commented Mar 23, 2011 at 11:05
  • 1
    @Ingo i did googling and tried my best after that only I came to SO. Thanks for helping hands :) Commented Mar 23, 2011 at 11:19
  • 1
    docs.oracle.com/javase/7/docs/api/java/lang/… Commented Apr 18, 2014 at 16:00

5 Answers 5

186

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.

Sign up to request clarification or add additional context in comments.

5 Comments

sorry guys. I tried google and found double to int only. So then I came to disturb our Friends here :) That works. many thanks
This is a really bad idea in loops. It's much better to work with primitives.
why I did this and it gives me an error double cannot be dereferenced?
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.
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) 

1 Comment

Also worth noting that 2.999999999999997 becomes 2, which is undesired in most cases.
24
double myDb = 12.3; int myInt = (int) myDb; 

Result is: myInt = 12

1 Comment

Daneos the question was about converting Double to int. Not double to int.
11

try casting the value

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

1 Comment

no it was not double it is a Double number. Thats why it shows the error i think.
2
int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue(); 

1 Comment

Math.ceil OR Math.floor is optional.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.