Java gives wrong answer to calculation
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, on the other hand if I do it in 3 steps it works flawlessly.
I know it's not too bad to take a couple more steps, but why use additional text when it can be shortened?
Can anyone give me a pointer if my math is wrong?
this is 1 line of code
percent1 = (((totaloutput1Int - Total1Int) / totaloutput1Int) * 100);
also = (((2232 - 1590) / 2232) * 100)
and this is a multi-step code that works.
percent1step1 = (totaloutput1Int - Total1Int); percent1step2 = ((percent1step1 / totaloutput1Int)* 100); percent1Tv.setText(String.valueOf(percent1step2));
source to share
You need to convert some of your variables to double to get an accurate answer. int
/ int
going to give you int
Take a look at this question
source to share
Since this is labeled Android, I am assuming you are using Android Studio. One of its great features is the lining (also available in most modern IDEs).
Take this:
float percent1step1 = (totaloutput1Int - Total1Int);
float percent1step2 = ((percent1step1 / totaloutput1Int)* 100);
If you right click percent1step1
and select "refactor-> inline" android studio do like this:
float percent1step2 = ((((float)(totaloutput1Int - Total1Int)) / totaloutput1Int)* 100);
Thus, it shows you how to succeed internally, without a few lines. In this case, the result is converted int
from subtraction to float
.
source to share