0
点赞
收藏
分享

微信扫一扫

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();
}

方法调用

第一个方法: 类.BigDecimalCalSum("+",“1.123”, “1.4321”, “0.001”);

第二个方法: 类.BigDecimalCalSum("+", 1.123, 1.2434, 0.1234);


举报

相关推荐

0 条评论