# convert integer to double

• 03-17-2011, 02:16 AM
himanwish
convert integer to double
Hi guys,

I'm trying to get the average of two integer values in double.

If I enter 7 and 8 then I get only 7 as the average not 7.5.

I tried
double average = Double.parseDouble( (firstNumber + secondNumber) /2 );
but I get a compile error.

below code is compiled fine but I cant get the average in double. Appreciate any ideas.

import java.util.Scanner;

public class Average {

public static void main(String [] args) {

Scanner console = new Scanner(System.in);

System.out.print("Enter the first number");
int firstNumber = console.nextInt();

System.out.print("Enter the second number");
int secondNumber = console.nextInt();

double average = (firstNumber + secondNumber)/2;

System.out.println("The average is " + average);
}

}
• 03-17-2011, 02:19 AM
sunde887
Use a cast or divide by a double.
• 03-17-2011, 02:37 AM
himanwish
Thank you very much sunde887. it works!!!
• 03-17-2011, 02:44 AM
Junky
Quote:

Originally Posted by sunde887
Use a cast

Just to clarify, you need to cast one or both of your ints to a double before the division. If you simply cast the result you will get 7.0 and not 7.5.
• 03-17-2011, 02:55 AM
sunde887
Quote:

Originally Posted by Junky
Just to clarify, you need to cast one or both of your ints to a double before the division. If you simply cast the result you will get 7.0 and not 7.5.

Thanks for clarifying, I tend to be overly vague at times when posting from my phone.