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
|
export const bytes = function (value, type = -1, dot=2) {
if (type == 1) {
return asciiCompute(value, 1024, ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 1)
} else if (type == -1) {
return asciiCompute(value, 1024, ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], dot)
} else {
return asciiCompute(value, 1024, ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 2)
}
}
/*
* 一般数值格式化方法
* num: 需要格式化的值
* ascii:进制,比如数据为1024
* units:单位列表
* dot:保留的小数位,
* */
function asciiCompute (num, ascii, units, dot = 2) {
if (isNaN(num) || num === null) {
return num
}
const scientificNotationValue = formatScientificNotation(num, dot)
if (!numberWithEConvent(scientificNotationValue)) {
return scientificNotationValue
}
if (!num && num !== 0 && num !== '0') {
return ''
}
num = Number(num)
const SIGN = num > 0 ? 1 : -1
num = Math.abs(num)
let carry = 0
if (num > 1) {
const log = Math.log(num) / Math.log(ascii)
carry = parseInt(log)
num = num / Math.pow(ascii, carry)
}
if (Number.isInteger(num)) {
return {
value: num * SIGN,
unit: units[carry]
}
} else {
return{
value: num.toFixed(dot) * SIGN,
unit: units[carry]
}
}
}
/* 数字转换保留小数,数字很小时转为科学计数法, dot为保留几位小数 */
function formatScientificNotation (value, dot = 2) {
if (isNaN(value) || value === null) {
return value
}
let val = value ? parseFloat(Number(value).toFixed(dot)) : 0
if (val === 0) {
val = Number(value).toPrecision(dot + 1)
}
return val
}
function numberWithEConvent (num) {
if (num) {
if ((('' + num).indexOf('E') !== -1) || (('' + num).indexOf('e') !== -1)) {
const regExp = /'^((\\d+.?\\d+)[Ee]{1}(\\d+))$', 'ig'/
let result = regExp.exec(num)
let resultValue = ''
let power
if (result != null) {
resultValue = result[2]
power = result[3]
result = regExp.exec(num)
}
if (resultValue) {
if (power) {
const powVer = Math.pow(10, power)
resultValue = resultValue * powVer
return resultValue
}
}
} else {
return num
}
}
if (isNaN(num) || num === null) {
return num
}
return 0
}
|