NumberUtils 数字工具类 发表于 2023-01-09 | 分类于 ---代码备份 | 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495package com.amoros.hawkeye.util;import cn.hutool.core.util.NumberUtil;import javax.annotation.Nullable;import java.math.BigDecimal;/** * 数字工具类 * * @author 陶攀峰 * @date 2023-01-09 17:32 */public class NumberUtils { public static final String DEFAULT_DISPLAY = "--"; /** * 千分位处理 ",###" * <pre> * String s = StrSplitter.numberFormat(null);// s = "--" * String s1 = StrSplitter.numberFormat(12);// s1 = "12" * String s2 = StrSplitter.numberFormat(123);// s2 = "123" * String s3 = StrSplitter.numberFormat(1234);// s3 = "1,234" * String s4 = StrSplitter.numberFormat(12345);// s4 = "12,345" * String s5 = StrSplitter.numberFormat(123456);// s5 = "123,456" * String s6 = StrSplitter.numberFormat(1234567);// s6 = "1,234,567" * </pre> */ public static String numberFormat(@Nullable Number num) { if (num == null) { return DEFAULT_DISPLAY; } // 四舍五入,取整 long longValue = NumberUtil.toBigDecimal(num).setScale(0, BigDecimal.ROUND_HALF_UP).longValue(); // 千分位处理 return NumberUtil.decimalFormat(",###", longValue); // String[] split = bigDecimal.toString().split("\\."); // split[0] = split[0].replaceAll("\\B(?=(\\d{3})+(?!\\d))", ","); // return StrUtil.join(".", split); } /** * 向上取整 * <pre> * BigDecimal b = roundHalfUp_0(null);// 0 * BigDecimal b1 = roundHalfUp_0(1.4);// 1 * BigDecimal b2 = roundHalfUp_0(1.5);// 2 * </pre> */ public static BigDecimal roundHalfUp_0(@Nullable Number num) { // null => BigDecimal.ZERO BigDecimal bigDecimal = NumberUtil.toBigDecimal(num); return bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP); } /** * 格式化百分比,保留一位百分比小数 "#.#%" * <pre> * String s = formatPercent_1(0.1234);// 12.3% * String s1 = formatPercent_1(0.1235);// 12.4% * String s2 = formatPercent_1(null);// -- * String s3 = formatPercent_1(0);// -- * </pre> */ public static String formatPercent_1(@Nullable Number num) { // null => BigDecimal.ZERO BigDecimal bigDecimal = NumberUtil.toBigDecimal(num); if (isZeroOrNull(bigDecimal)) { return DEFAULT_DISPLAY; } return NumberUtil.decimalFormat("#.#%", bigDecimal); } /** * 0 或 null ? * <pre> * boolean z = isZeroOrNull(null);// true * boolean z1 = isZeroOrNull(0);// true * boolean z2 = isZeroOrNull(0.0001);// false * </pre> */ public static boolean isZeroOrNull(@Nullable Number num) { // null => BigDecimal.ZERO BigDecimal bigDecimal = NumberUtil.toBigDecimal(num); return NumberUtil.equals(BigDecimal.ZERO, bigDecimal); }}