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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* @Description: 检测是否为数字
* @author cr
* @date 2020/4/18
* @time 12:01
*/
function isNumber(val: any): boolean {
const regPos = /^\d+(\.\d+)?$/; //非负浮点数
const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
return regPos.test(val) || regNeg.test(val);
}
/**
* @Description: 精度
* @author cr
* @date 2020/4/18
* @time 12:03
*/
function prefixZero(value: number, num: number): string {
let a, i;
a = value.toString();
const b = a.indexOf(".");
const c = a.length;
if (num === 0) {
if (b !== -1) {
a = a.substring(0, b);
}
} else {
/*如果没有小数点*/
if (b === -1) {
a = a + ".";
for (i = 1; i <= num; i++) {
a = a + "0";
}
} else {
/*有小数点,超出位数自动截取,否则补0*/
a = a.substring(0, b + num + 1);
for (i = c; i <= b + num; i++) {
a = a + "0";
}
}
}
return a;
}
/**
* @Description: 四舍五入
* @author cr
* @date 2020/4/18
* @time 12:02
*/
function roundFixed(num: any, fixed: number): string {
const pos = num.toString().indexOf(".");
const decimalPlaces = num.toString().length - pos - 1;
const _int = num * Math.pow(10, decimalPlaces);
const divisorOne = Math.pow(10, decimalPlaces - fixed);
const divisorTwo = Math.pow(10, fixed);
const value = Math.round(_int / divisorOne) / divisorTwo;
return prefixZero(value, fixed);
}
/**
* @Description: 保留小数位数
* @author cr
* @date 2020/4/18
* @time 12:01
*/
function toDecimal(value: any, decimal: number): string {
if (isNumber(value)) {
if (isNumber(decimal)) {
return roundFixed(value, decimal);
} else {
return value;
}
}
return "";
}
/**
* @Description: 加千分位
* @author cr
* @date 2020/4/18
* @time 12:12
*/
function executeLcommafy(val: string) {
if (!val || !isNumber(val)) {
return "";
}
if (isNumber(val)) {
val = val.toString();
}
if (/^.*\..*$/.test(val)) {
const pointIndex = val.lastIndexOf(".");
let intPart = val.substring(0, pointIndex);
const pointPart = val.substring(pointIndex + 1, val.length);
intPart = intPart + "";
const re = /(-?\d+)(\d{3})/;
while (re.test(intPart)) {
intPart = intPart.replace(re, "$1,$2");
}
val = intPart + "." + pointPart;
} else {
const re = /(-?\d+)(\d{3})/;
while (re.test(val)) {
val = val.replace(re, "$1,$2");
}
}
return val;
}
/**
* @Description: 千分位转换
* @author cr
* @date 2020/4/18
* @time 12:05
*/
function encode(value: any, decimal: number) {
let number = toDecimal(value, decimal);
number = executeLcommafy(number);
if (value === "" || (value == null && value !== 0)) {
return "";
}
return number;
}
const thousandBitConvert = (value: any, decimal: number) => {
return encode(value, decimal);
};
export default thousandBitConvert;