1

I am trying to divide two integer and get a decimal number I am keep getting 0 result when I divide 10/29 I would like to get 0.34

my code is :

private int totalCount_Games;
private int totalCount_Hints_Statistics;
double avgHints;
avgHints=totalCount_Hints_Statistics/totalCount_Games;
michal
  • 17
  • 6

3 Answers3

2

In Java, when you divide two integers, the result is another integer.

In your case, 10/29 will result in 0 as you mentioned. If you want to get the results of these in floating digits, then change the above two integers to float or double.

In that case, the result for the above calculation will be 0.34.

PS: This is really basic. You should do more research in the official java site for documentation on datatypes.

shaheer_
  • 406
  • 1
  • 4
  • 12
0

The above code will result in 0.0 as int/int will always be a int which is further type casted into double thus output is 0.0

Use the below code, Using big decimal for Rounding

    double totalCount_Games_double = totalCount_Games;
    double totalCount_Hints_Statistics_double = totalCount_Hints_Statistics;
    double value =  totalCount_Hints_Statistics/totalCount_Games_double;
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(2, RoundingMode.HALF_UP);
hagarwal
  • 1,153
  • 11
  • 27
0

The result of a int division is another int, rounded. Casting int to double (or float) in the expression part will make the division occurs on doubles instead of int, note that this is different from casting the result from the int division to double.

int i = 5, b = 10;
double result = ((double)i)/((double)b);

result is 0.5

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • 1
    can you explain a little bit more why your answer works – petey Sep 19 '17 at 21:37
  • Code-only answers are discouraged because they do not explain how they resolve the issue in the question. Consider updating your answer to explain what this does and how it addresses the problem - this will help not just the OP but others with similar issues. Please review [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) – FluffyKitten Sep 20 '17 at 00:12
  • explanation added – Marcos Vasconcelos Sep 20 '17 at 12:48