Richard Thomas - 2 months ago 5x
Java Question

# How to divide two ints and return a double in Java

I'm new to Android and I'm having trouble with a maths app I am creating.

The basic premise is to present the user with 2 numbers between 0 and 20 (questionTextView) then show the user a grid containing 3 incorrect answers and 1 correct answer. The user then clicks on the correct answer.

The issue I'm having is that the correct answer is not displaying to 2 decimal points.

E.g. Question: 4 / 7

Answer 4: 0 (Should be 0.57)

I don't understand why the correct answer is not displaying properly as I have cast both ints to doubles and included decimal formatting.

I've tried Math.round(), but I couldn't get this to work - perhaps due to the way I have generated the questions within a for loop????

Any assistance would be greatly appreciated.

Here is my code:

``````private static DecimalFormat df2 = new DecimalFormat("#.##");

public void generateQuestion(){

//Create 2 random numbers between 0 and 20.
Random rand = new Random();

int a = rand.nextInt(21);
int b = rand.nextInt(21);

if (a==b){
b = rand.nextInt(21);
}

questionTextView.setText(Integer.toString(a) + " / " + Integer.toString(b));

/*Create a random number between 0 and 3 to determine the grid square of

randomly generated.

/*Loop through each square and assign either the correct answer or
a randomly generated number. */
for (int i=0; i<4; i++){
} else {
inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;

inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;
}
}
}

//Assign an answer to each of the buttons.
`(((double)a/(double)b))` This will give you = 0.57 and then this `(int)` this will convert 0.57 to 0 here `(int)(((double)a/(double)b));` because integer can only hold `whole numbers` hence decimal values will be truncated.
``````double correctAnswer = (((double)a/(double)b));