Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java giving wrong answer on a calculation

Tags:

java

android

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));
like image 248
user3032484 Avatar asked Nov 17 '25 18:11

user3032484


2 Answers

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.

like image 54
Samrat Dutta Avatar answered Nov 20 '25 09:11

Samrat Dutta


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

like image 43
Chad Bingham Avatar answered Nov 20 '25 08:11

Chad Bingham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!