Calculating average of an array list?

后端 未结 11 864
天涯浪人
天涯浪人 2020-11-29 09:04

I\'m trying to use the below code to calculate the average of a set of values that a user enters and display it in a jTextArea but it does not work properly. Sa

11条回答
  •  借酒劲吻你
    2020-11-29 09:33

    Here a version which uses BigDecimal instead of double:

    public static BigDecimal calculateAverage(final List values) {
        int sum = 0;
        if (!values.isEmpty()) {
            for (final Integer v : values) {
                sum += v;
            }
            return new BigDecimal(sum).divide(new BigDecimal(values.size()), 2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }
    

提交回复
热议问题