-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmoneyFormat.ts
More file actions
31 lines (30 loc) · 1.05 KB
/
moneyFormat.ts
File metadata and controls
31 lines (30 loc) · 1.05 KB
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
import splitFormat from './splitFormat';
import cut from './cut';
import round from './round';
import decimalPadEnd from './decimalPadEnd';
/**
* 格式化金额,按千分位以逗号分隔
* @param value
* @param precision 精度
* @param isCut 是否截取
*/
export default function moneyFormat(value: string | number, precision?: number, isCut?: boolean): string | number {
const num = +value;
if (isNaN(num)) return value;
const result = String(num).split('.');
const integer = result[0];
const float = result[1];
// 处理整数部分
const formattedInteger = splitFormat(integer, { separator: ',', reverse: true });
// 处理小数部分
if (typeof precision === 'number') {
let floatStr = float ? Number([0, float].join('.')) : 0;
floatStr = isCut ? cut(floatStr, precision) : round(floatStr, precision);
const formattedFloat = decimalPadEnd(floatStr, precision).split('.')[1];
return `${formattedInteger}.${formattedFloat}`;
}
if (float) {
return `${formattedInteger}.${float}`;
}
return formattedInteger;
}