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 }