average a list of BigDecimal - Java java.math

Java examples for java.math:BigDecimal Calculation

Description

average a list of BigDecimal

Demo Code



//package com.java2s;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] argv) throws Exception {
    BigDecimal numbers = new BigDecimal("1234");
    System.out.println(average(numbers));
  }/*from   w ww  .j  av  a  2 s.c  o m*/

  public static BigDecimal average(final BigDecimal... numbers) {
    return IntStream.range(0, numbers.length).mapToObj(i -> numbers[i]).reduce((sum, next) -> sum.add(next))
        .map(sum -> sum.divide(BigDecimal.valueOf(numbers.length))).orElse(BigDecimal.ZERO);
  }

  public static BigDecimal divide(final BigDecimal amount, final BigDecimal divideBy, final int scale) {
    return amount.setScale(scale, RoundingMode.HALF_EVEN).divide(divideBy, RoundingMode.HALF_EVEN);
  }
}

Related Tutorials