Reputation: 61
i am trying to do some calculations in Java, but for some reason a simple calculation in 1 or 2 lines of code gives me the wrong answer, while on the other hand if i do it in 3 steps it works flawlessly.
i know that's it not that bad to do something in a couple more steps, but why use extra text if it can be shortened??
Could someone give me a pointer if my math is wrong??
this is the 1 line code
percent1 = (((totaloutput1Int - Total1Int) / totaloutput1Int) * 100);
also = (((2232 - 1590) / 2232) * 100)
and this is the multiple steps code which does work.
percent1step1 = (totaloutput1Int - Total1Int);
percent1step2 = ((percent1step1 / totaloutput1Int)* 100);
percent1Tv.setText(String.valueOf(percent1step2));
Upvotes: 3
Views: 1223
Reputation: 54791
So as this is tagged Android, I'm assuming you are using Android Studio. One of it's great features is in-lining (also available in most modern IDEs).
Take this:
float percent1step1 = (totaloutput1Int - Total1Int);
float percent1step2 = ((percent1step1 / totaloutput1Int)* 100);
If you rightclick percent1step1
and select "refactor->inline" android studio will so this:
float percent1step2 = ((((float)(totaloutput1Int - Total1Int)) / totaloutput1Int)* 100);
So it shows you how to achieve things inline, without multiple lines. In this case the result is convert the int
from the subtraction in to a float
.
Upvotes: 1
Reputation: 1737
Change totaloutput1Int
and Total1Int
from int
to double
and everything will work fine.
In the 1st method, int/int leads to rounding off of the value. Which leads to a different result.
Upvotes: 5
Reputation: 33856
You need to convert some of your variables to a double to get an accurate answer. int
/ int
is going to give you an int
Take a look at this question
Upvotes: 1