天天看點

Java中多個Double類型的數進行計算 - Java

​​Java中Double類型的加減 - Java​​, 這篇文章隻是簡單的兩個數的運算, 如果要是多個浮點數進行計算, 顯然要多次調用方法才可以實作.

為了解決這個問題, 專門寫了一個方法來取出繁雜的操作.

/**
   * 適用多個數進行累加,累乘或者減除減去多個數,除數除以多個數, 其中第二個參數為減數或者除數,
   * 
   * @param operation: + || - || * || /
   * @param v: the first is divisor or subtrahend, The back is all subtracted or
   *        dividend
   * @return
   * @AddBy 2020-12-24
   * @author xyLi
   */
  public static String BigDecimalCalSum(String operation, String... v) {
    BigDecimal b = new BigDecimal("0");
    BigDecimal b2 = new BigDecimal("0");
    if (v[0] != null) {
      b = new BigDecimal(v[0]);
    }
    for (int i = 1; i < v.length; i++) {
      if (v[i] != null) {
        b2 = new BigDecimal((v[i]));
        if ("+".equals(operation)) {
          b = b.add(b2);
        } else if ("-".equals(operation)) {
          b = b.subtract(b2);
        } else if ("*".equals(operation)) {
          b = b.multiply(b2);
        } else if ("/".equals(operation)) {
          b = b.divide(b2);
        }
      }

    }
    return b.toString();
  }

  /**
   * 適用多個數進行累加,累乘或者減除減去多個數,除數除以多個數, 其中第二個參數為減數或者除數,
   * 
   * @param operation: + || - || * || /
   * @param v: the first is divisor or subtrahend, The back is all subtracted or
   *        dividend
   * @return
   * @AddBy 2020-12-24
   * @author xyLi
   */
  public static Double BigDecimalCalSum(String operation, Double... v) {
    BigDecimal b = new BigDecimal("0");
    BigDecimal b2 = new BigDecimal("0");
    if (v[0] != null) {
      b = new BigDecimal(String.valueOf(v[0]));
    }
    for (int i = 1; i < v.length; i++) {
      if (v[i] != null) {
        b2 = new BigDecimal(String.valueOf(v[i]));
        if ("+".equals(operation)) {
          b = b.add(b2);
        } else if ("-".equals(operation)) {
          b = b.subtract(b2);
        } else if ("*".equals(operation)) {
          b = b.multiply(b2);
        } else if ("/".equals(operation)) {
          b = b.divide(b2);
        }
      }

    }
    return b.doubleValue();
  }      

方法調用