Files
gaoYuJournal/miniprogram/utils/IOSize.ts
2025-12-05 10:38:55 +08:00

112 lines
2.0 KiB
TypeScript

export enum Unit {
/** B */
B = "B",
/** KB */
KB = "KB",
/** MB */
MB = "MB",
/** GB */
GB = "GB",
/** TB */
TB = "TB",
/** PB */
PB = "PB",
/** EB */
EB = "EB"
}
/** 储存单位 */
export default class IOSize {
/** 1 字节 */
public static BYTE = 1;
/** 1 KB */
public static KB = IOSize.BYTE << 10;
/** 1 MB */
public static MB = IOSize.KB << 10;
/** 1 GB */
public static GB = IOSize.MB << 10;
/** 1 TB */
public static TB = IOSize.GB << 10;
/** 1 PB */
public static PB = IOSize.TB << 10;
/** 1 EB */
public static EB = IOSize.PB << 10;
public static Unit = Unit;
/**
* <p>格式化一个储存容量,保留两位小数
* <pre>
* // 返回 100.01 KB
* format(102411, 2);
* </pre>
*
* @param size 字节大小
* @param fixed 保留小数
* @param stopUnit 停止单位
* @return
*/
public static format(size: number, fixed = 2, stopUnit?: Unit): string {
const units = Object.keys(Unit);
if (0 < size) {
for (let i = 0; i < units.length; i++, size /= 1024) {
const unit = units[i];
if (size <= 1000 || i === units.length - 1 || unit === stopUnit) {
if (i === 0) {
// 最小单位不需要小数
return size + " B";
} else {
return `${size.toFixed(fixed)} ${unit}`;
}
}
}
}
return "0 B";
}
/**
* <p>格式化一个储存容量,保留两位小数,不带单位
* <pre>
* // 返回 100.01
* format(102411, 2);
* </pre>
*
* @param size 字节大小
* @param fixed 保留小数
* @param stopUnit 停止单位
* @return
*/
public static formatWithoutUnit(size: number, fixed = 2, stopUnit?: Unit): string {
const units = Object.keys(Unit);
if (0 < size) {
for (let i = 0; i < units.length; i++, size /= 1024) {
const unit = units[i];
if (size <= 1000 || i === units.length - 1 || unit === stopUnit) {
if (i === 0) {
// 最小单位不需要小数
return size.toFixed(0);
} else {
return size.toFixed(fixed);
}
}
}
}
return "0";
}
}