Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginners Java Question (int, float)

Tags:

java

int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema

So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?

like image 586
bitmoe Avatar asked Sep 15 '10 01:09

bitmoe


3 Answers

When you divide two ints (eg, 2 / 3), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0.

You need to force Java to perform a double division by casting either operand to a double.

For example:

fractionCinema = (cinema / (double)total) * 100;
like image 111
SLaks Avatar answered Oct 26 '22 18:10

SLaks


Try this instead:

int  cinema, total;
int  fractionCinema;

fractionCinema = cinema*100 / total;   //percent cinema

For example, if cinema/(double)total is 0.5, then fractionCinema would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.

Addendum

As pointed out by @user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:

fractionCinema = (cinema*100 + 50) / total;    //percent cinema
like image 24
David R Tribble Avatar answered Oct 26 '22 19:10

David R Tribble


When you divide two ints, Java will do integer division, and the fractional part will be truncated.

You can either explicitly cast one of the arguments to a double via cinema/(double) total or implicitly using an operation such as cinema*1.0/total

like image 27
NullUserException Avatar answered Oct 26 '22 18:10

NullUserException