I'm trying to divide two integers and multiply by 100 but it keeps giving only 0 or 100. Can someone help me?
int x= (a/b)*100;
if a was 500 and b was 1000 it would give me 0. The only time it will give me 100 is if a>=b. How can I fix this?
Thanks
When dividing two integers, Java uses integer division. In integer division, the result is also an integer. The result is truncated (the fractional part is thrown away) and not rounded to the closest integer.
Division of integers involves the grouping of items. It includes both positive numbers and negative numbers. Just like multiplication, the division of integers also involves the same cases. When you divide integers with two positive signs, Positive ÷ Positive = Positive → 16 ÷ 8 = 2.
float v=s/t performs division then transforms result into a float. float v=(float)s/t casts to float then performs division.
What you could do is force it to divide a
and b
as doubles thus:
int x = (int) (((double) a / (double) b) * 100);
Integer division has no fractions, so 500 / 1000 = 0.5 (that is no integer!) which gets truncated to integer 0. You probably want
int x = a * 100 / b;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With