fix: pretty bytes

This commit is contained in:
GyDi 2022-11-20 23:08:24 +08:00
parent 7338838b0e
commit d21bb015e8
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A

View File

@ -1,30 +1,12 @@
/** const UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
* parse the traffic to
* xxx B
* xxx KB
* xxx MB
* xxx GB
*/
const parseTraffic = (num: number) => {
const gb = 1024 ** 3;
const mb = 1024 ** 2;
const kb = 1024;
let t = num;
let u = "B";
if (num < 1000) return [`${Math.round(t)}`, "B"]; const parseTraffic = (num: number) => {
if (num <= mb) { if (num < 1000) return [`${Math.round(num)}`, "B"];
t = num / kb; const exp = Math.min(Math.floor(Math.log10(num) / 3), UNITS.length - 1);
u = "KB"; const ret = (num / Math.pow(1000, exp)).toPrecision(3);
} else if (num <= gb) { const unit = UNITS[exp];
t = num / mb;
u = "MB"; return [ret, unit];
} else {
t = num / gb;
u = "GB";
}
if (t >= 100) return [`${Math.round(t)}`, u];
return [`${Math.round(t * 10) / 10}`, u];
}; };
export default parseTraffic; export default parseTraffic;