-4

Hello why when i doing division here i getting bad result. I have in array[0] 4 digits 3 4 5 1 result if 13 and doing division from 4 result need to 3.25 but getting 3.0 where i am doing mistake?

final long[] total = {0};
        eventReference.child(eventId).child("EventRating").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        int rating = snapshot.child("rated").getValue(Integer.class);
                        total[0] = total[0] + rating;
                    }
                }
                double average = total[0] /dataSnapshot.getChildrenCount();
                Toast.makeText(getContext(), average + "           " + total[0], Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441

1 Answers1

0

By the name getChildrenCount() I understand that this method returns an integer, and if so, it's probably the issue since a division by an integer in Java is always results in an integer, in your case it's being implicitly converted to double, thus you get 3.0.

Try replacing this line with:

double average = total[0] / (double) dataSnapshot.getChildrenCount();

Tomer Gal
  • 933
  • 12
  • 21