[java] I need to convert an int variable to double

My friend is trying to make some kind of calculation as a task for class, and he's having some trouble... I hope you can help him.

The problem is that he gets an input from the user as int (it has to be, it's a part of the task). He is trying to convert it to double in the code below, but this doesn't work. The results are int anyway.

double firstSolution = ((b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
double secondSolution = ((b2 * a11 - b1 * a21) / (a11 * a22 - a12 * a21));

If you need more explanation, I'll ask him for it. Thanks in advance!

This question is related to java

The answer is


Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.


I think you should casting variable or use Integer class by call out method doubleValue().


Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));