Numeral
coderljw 2024-10-13 小于 1 分钟
# 1. 四舍五入
/**
* @param {number | string} num 值
* @param {number} reserved 保留位数,默认值:2
* @return {string} string
*/
export const round = (num?: number | string, reserved: number = 2) => {
const pureNum = Number(num)
if (!num || Number.isNaN(pureNum)) return num?.toString() || ''
return (
Math.round(pureNum * Math.pow(10, reserved)) / Math.pow(10, reserved)
).toFixed(reserved)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 2. 单位格式化
import { round } from 'lodash'
/**
* @param {number | string} num 值
* @param {number} reserved 保留位数,默认值:2
* @return {string} string
*/
export const monetization = (num?: number | string, reserved: number = 2) => {
const pureNum = Number(num)
if (!num || Number.isNaN(pureNum)) return num?.toString() || ''
const { length } = Number.parseInt(pureNum.toString()).toString()
switch (true) {
case length > 12:
return convertUnit(12, '万亿')
case length > 8:
return convertUnit(8, '亿')
case length > 4:
return convertUnit(4, '万')
default:
return round(pureNum, reserved).toString()
}
function convertUnit(digit: number, unit: string = '') {
const divisor = pureNum / Math.pow(10, digit)
return `${round(divisor, reserved)}${unit}`
}
}
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
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