BigDecimals:新增 sum、nullToZero 方法

pull/1/head
ZhouXY108 2024-11-19 22:49:22 +08:00
parent 8d24d8de23
commit fb9cb8ada9
1 changed files with 21 additions and 0 deletions

View File

@ -17,6 +17,8 @@
package xyz.zhouxy.plusone.commons.util;
import java.math.BigDecimal;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
@ -49,6 +51,25 @@ public class BigDecimals {
return lt(a, b) || equalsValue(a, b);
}
public static BigDecimal sum(final BigDecimal... numbers) {
if (ArrayTools.isNullOrEmpty(numbers)) {
return BigDecimal.ZERO;
}
BigDecimal result = BigDecimals.nullToZero(numbers[0]);
for (int i = 1; i < numbers.length; i++) {
BigDecimal value = numbers[i];
if (value != null) {
result = result.add(value);
}
}
return result;
}
@Nonnull
public static BigDecimal nullToZero(@Nullable final BigDecimal val) {
return val != null ? val : BigDecimal.ZERO;
}
@StaticFactoryMethod(BigDecimal.class)
public static BigDecimal of(final String val) {
return (StringTools.isNotBlank(val)) ? new BigDecimal(val) : BigDecimal.ZERO;