feat: SMF数据单位转换MB显示

This commit is contained in:
TsMask
2025-03-12 11:12:30 +08:00
parent a24122ecd7
commit 37a1f748e7
3 changed files with 33 additions and 18 deletions

View File

@@ -192,17 +192,31 @@ export function parseSizeFromBits(bits: number | string): string {
/**
* 字节数转换单位
* @param byte 字节Byte大小 64009540 = 512.08 MB
* @param unit 指定单位 B / KB / MB / GB / TB / PB / EB / ZB / YB
* @returns xx B / KB / MB / GB / TB / PB / EB / ZB / YB
*/
export function parseSizeFromByte(byte: number | string): string {
export function parseSizeFromByte(
byte: number | string,
unit?: string
): string {
byte = Number(byte) || 0;
if (byte <= 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const unitIndex = Math.floor(Math.log2(byte) / 10);
const unti = units[unitIndex];
let unitIndex = 0;
let unitStr = 'B';
if (unit) {
const index = units.indexOf(unit);
if (index > -1) {
unitIndex = index;
unitStr = unit;
}
} else {
unitIndex = Math.floor(Math.log2(byte) / 10);
unitStr = units[unitIndex];
}
const value = byte / Math.pow(1000, unitIndex);
if (unitIndex > 0) {
return `${value.toFixed(2)} ${unti}`;
return `${value.toFixed(2)} ${unitStr}`;
}
return `${value} ${unti}`;
return `${value} ${unitStr}`;
}