From 86d2716b8d64a21053cd5827583973398f925168 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Tue, 19 Nov 2024 22:51:16 +0800 Subject: [PATCH] =?UTF-8?q?Numbers=EF=BC=9A=E9=87=8D=E8=BD=BD=20BigInteger?= =?UTF-8?q?=20=E7=9A=84=20sum=20=E6=96=B9=E6=B3=95=EF=BC=9B=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20nullToZero=20=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../zhouxy/plusone/commons/util/Numbers.java | 60 +++++++++++++++++-- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/Numbers.java b/src/main/java/xyz/zhouxy/plusone/commons/util/Numbers.java index 2004527..5c96878 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/Numbers.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/Numbers.java @@ -17,6 +17,10 @@ package xyz.zhouxy.plusone.commons.util; import java.math.BigDecimal; +import java.math.BigInteger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Numbers @@ -25,7 +29,7 @@ import java.math.BigDecimal; */ public class Numbers { - // sum + // #region - sum public static int sum(final short... numbers) { int result = 0; @@ -67,14 +71,60 @@ public class Numbers { return result; } - public static BigDecimal sum(final BigDecimal... numbers) { - BigDecimal result = BigDecimals.of("0.00"); - for (BigDecimal number : numbers) { - result = result.add(number); + public static BigInteger sum(final BigInteger... numbers) { + if (ArrayTools.isNullOrEmpty(numbers)) { + return BigInteger.ZERO; + } + BigInteger result = Numbers.nullToZero(numbers[0]); + for (int i = 1; i < numbers.length; i++) { + BigInteger value = numbers[i]; + if (value != null) { + result = result.add(value); + } } return result; } + public static BigDecimal sum(final BigDecimal... numbers) { + return BigDecimals.sum(numbers); + } + + // #endregion + + // #region - nullToZero + + public static short nullToZero(@Nullable final Short val) { + return val != null ? val : 0; + } + + public static int nullToZero(@Nullable final Integer val) { + return val != null ? val : 0; + } + + public static long nullToZero(@Nullable final Long val) { + return val != null ? val : 0L; + } + + public static float nullToZero(@Nullable final Float val) { + return val != null ? val : 0.0F; + } + + public static double nullToZero(@Nullable final Double val) { + return val != null ? val : 0.0; + } + + @Nonnull + public static BigInteger nullToZero(@Nullable final BigInteger val) { + return val != null ? val : BigInteger.ZERO; + } + + @Nonnull + public static BigDecimal nullToZero(@Nullable final BigDecimal val) { + return BigDecimals.nullToZero(val); + } + + // #endregion + private Numbers() { throw new IllegalStateException("Utility class"); }