5 Replies Latest reply on Mar 20, 2007 6:09 AM by 807599

# Being able to use a double and an int in a equation

Did a little searching for the answer before asking both in the api and here on the forums, as well as my old programs but just can't seem to find the answer. I need to be able to use an int and a double in a equation where the answer should be an int. Here is an example of exactly what I'm trying to do:

int number=1;
int number2=3;
double number3=1.5

I want an int as the answer but I need the double for the equation so please tell me what I'm forgetting. Thanks.
• ###### 1. Re: Being able to use a double and an int in a equation
You can cast number3 into an int
``answer = number * number2 * (int)number3;``
But in either case, you're going to lose some data.
Losing data, I mean 1.5 will become 1.

Were you expecting 4.5 as the outcome?
If so, then just change answer to a double type.

Message was edited by:
lethalwire
• ###### 2. Re: Being able to use a double and an int in a equation
I guess what I want is the answer rounded to an int. For example the math equation gives you something like 1+3*1.5=5.5, however I want it to round it to 6.
• ###### 3. Re: Being able to use a double and an int in a equation
This is the method you'll need then:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#round(double)

It rounds a double type into an a long.
You'll then cast that into an int.

Example:
``answer = num1 * num2 * (int)Math.round(num3);``
The variable "answer" now contains the number 6.
• ###### 4. Re: Being able to use a double and an int in a equation
Safer bet is to round the result.
``answer = (int)Math.round(num1 * num2 * num3);``
• ###### 5. Re: Being able to use a double and an int in a equation
Thanks Flounder that's exactly what I needed. I actually had tried the Math.round but didn't figure out the (int) part which of course didn't make it work.