From fb9cb8ada961081ad3b1b70b7df69cf4b6af63aa Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Tue, 19 Nov 2024 22:49:22 +0800 Subject: [PATCH] =?UTF-8?q?BigDecimals=EF=BC=9A=E6=96=B0=E5=A2=9E=20sum?= =?UTF-8?q?=E3=80=81nullToZero=20=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plusone/commons/util/BigDecimals.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/BigDecimals.java b/src/main/java/xyz/zhouxy/plusone/commons/util/BigDecimals.java index 90a707e..11c9664 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/BigDecimals.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/BigDecimals.java @@ -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;