Reputation: 1
So I am trying to calculate my average goals blocked by dividing how many I stopped by how many shots have been taken. How can I stop it from rounding my average
counter = goals blocked goalCounter = goals scored
avg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
BigDecimal avgCalc = new BigDecimal(counter/goalCounter);
tvDisplayAvg.setText("Goal Avg: " + avgCalc);
}
});
So I got it to divide and get decimals but is there a way to set a limit of only dividing to the thousandths place?
Upvotes: 0
Views: 215
Reputation: 8662
your rounding comes probably from counter/goalCounter
if you are using big decimal, stay with it.
avg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BigDecimal c = new BigDecimal(counter);
BigDecimal g = new BigDecimal(goalCounter);
BigDecimal answer=c.divide(g);
tvDisplayAvg.setText("Goal Avg: " + amswer.toString());
}
});
Upvotes: 5
Reputation: 1048
The problem might be that counter
and goalCounter
are both ints. Try casting one of them to double when you divide (e.g. counter/(double)goalCounter
). This is because if Java sees you dividing two integers, the result will also be an integer.
If they are not ints (i.e. they are floats or doubles), the float and double types have limited precision, and the BigDecimal class was created to rectify this situation. Make two BigDecimals - one for each variable - and then assign avgCalc to their quotient.
Upvotes: -1