NumberUtils 数字工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package 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);
}

}