3

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));
CommonsWare
  • 954,112
  • 185
  • 2,315
  • 2,367
  • What (different) results are you getting from the first and second calculations? Also, what types are `percent1` and `percent2`? – Mureinik Jul 18 '15 at 16:37
  • i used all Integers and for percent1step1 and percent1step2 i tried floats, the first calculation is just giving me 2232 and the second one is giving me 28.76344 – user3032484 Jul 18 '15 at 16:41

3 Answers3

5

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.

Samrat Dutta
  • 1,707
  • 10
  • 22
1

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

Community
  • 1
  • 1
Chad Bingham
  • 30,680
  • 19
  • 84
  • 114
1

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.

weston
  • 52,585
  • 20
  • 135
  • 197