Real World Example

Average Rating on a Product Page

Flipkart and Amazon show an average rating like 4.3 for a product. Ratings arrive as text from a request, are parsed to numbers, summed as int, and divided as double so the decimal part is not lost.

Example

public class Main {
    public static void main(String[] args) {
        String[] ratingsFromRequest = {"5", "4", "4", "3", "5", "4", "5"};

        int sum = 0;
        for (String r : ratingsFromRequest) {
            sum += Integer.parseInt(r);       // String -> int
        }
        int count = ratingsFromRequest.length;

        int wrongAverage = sum / count;              // int division
        double average = (double) sum / count;       // cast first
        double shown = Math.round(average * 10) / 10.0;  // one decimal place

        System.out.println("Wrong average : " + wrongAverage);
        System.out.println("Real average  : " + average);
        System.out.println("Shown on page : " + shown + " stars (" + count + " ratings)");
    }
}

Output

Wrong average : 4
Real average  : 4.285714285714286
Shown on page : 4.3 stars (7 ratings)