Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing two integers in Java gives me 0 or 100?

Tags:

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

like image 299
arberb Avatar asked Dec 29 '11 15:12

arberb


People also ask

What happens when you divide two integers in Java?

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.

When two integers are divided we get?

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.

How do you float a division in Java?

float v=s/t performs division then transforms result into a float. float v=(float)s/t casts to float then performs division.


2 Answers

What you could do is force it to divide a and b as doubles thus:

int x = (int) (((double) a / (double) b) * 100); 
like image 195
ridecar2 Avatar answered Nov 07 '22 12:11

ridecar2


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; 
like image 42
Simon Urbanek Avatar answered Nov 07 '22 10:11

Simon Urbanek