Refactor size formatting for readability

This commit is contained in:
mhsanaei 2024-10-16 15:55:35 +02:00
parent 2ef5ccc2fd
commit 863009dcaa
No known key found for this signature in database
GPG key ID: 4DACC0663B5986F5
2 changed files with 21 additions and 31 deletions

View file

@ -4,18 +4,14 @@ import (
"fmt" "fmt"
) )
func FormatTraffic(trafficBytes int64) (size string) { func FormatTraffic(trafficBytes int64) string {
if trafficBytes < 1024 { units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
return fmt.Sprintf("%.2fB", float64(trafficBytes)/float64(1)) unitIndex := 0
} else if trafficBytes < (1024 * 1024) { size := float64(trafficBytes)
return fmt.Sprintf("%.2fKB", float64(trafficBytes)/float64(1024))
} else if trafficBytes < (1024 * 1024 * 1024) { for size >= 1024 && unitIndex < len(units)-1 {
return fmt.Sprintf("%.2fMB", float64(trafficBytes)/float64(1024*1024)) size /= 1024
} else if trafficBytes < (1024 * 1024 * 1024 * 1024) { unitIndex++
return fmt.Sprintf("%.2fGB", float64(trafficBytes)/float64(1024*1024*1024))
} else if trafficBytes < (1024 * 1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2fTB", float64(trafficBytes)/float64(1024*1024*1024*1024))
} else {
return fmt.Sprintf("%.2fEB", float64(trafficBytes)/float64(1024*1024*1024*1024*1024))
} }
return fmt.Sprintf("%.2f%s", size, units[unitIndex])
} }

View file

@ -1,25 +1,19 @@
const ONE_KB = 1024; const ONE_KB = 1024;
const ONE_MB = ONE_KB * 1024; const units = ["B", "KB", "MB", "GB", "TB", "PB"];
const ONE_GB = ONE_MB * 1024;
const ONE_TB = ONE_GB * 1024;
const ONE_PB = ONE_TB * 1024;
function sizeFormat(size) { function sizeFormat(size) {
if (size < 0) { if (size < 0) {
return "0 B"; return "0 B";
} else if (size < ONE_KB) {
return size.toFixed(0) + " B";
} else if (size < ONE_MB) {
return (size / ONE_KB).toFixed(2) + " KB";
} else if (size < ONE_GB) {
return (size / ONE_MB).toFixed(2) + " MB";
} else if (size < ONE_TB) {
return (size / ONE_GB).toFixed(2) + " GB";
} else if (size < ONE_PB) {
return (size / ONE_TB).toFixed(2) + " TB";
} else {
return (size / ONE_PB).toFixed(2) + " PB";
} }
let index = 0;
while (size >= ONE_KB && index < units.length - 1) {
size /= ONE_KB;
index++;
}
return `${size.toFixed(index === 0 ? 0 : 2)} ${units[index]}`;
} }
function cpuSpeedFormat(speed) { function cpuSpeedFormat(speed) {