In Java and some other programming languages, there is something called integer arithmetic, which says that if you do (in your case):
int / int = int
In your code, you are doing
(int * int) / int <=> int / int = int
Solutions:
Method 1: Something you can do to get a float is to use a float
operand. In your case it can be the 100
:
float z = (x * 100.0f) / y;
Here, the operation is
(int * float) / int <=> float / int = float
Method 2: Another way to solve this is to cast an integer to a float:
float z = (x * 100) / (float)y; // int * int / float = float
float z = (float)x * 100 / y; // float * int / int = float
Method 3: As @webSpider mentioned in his answer, you can just declare the variables x
and y
as float
to avoid these problems.
Edit: To round your float
result, you can try this:
float z = Math.round(result * 100) / 100f;
where the number of zeros of 100
is the number of decimal places. Note that 100f
will be a float
because of the postfix f
.