1
0
Fork 0

Simplify formatFileSize

No need to use a loop with divisions and multiplications when we have logarithms.
This commit is contained in:
jvoisin 2024-02-27 20:40:43 +01:00 committed by Frédéric Guillot
parent 9a4a942cc4
commit f274394f0e
2 changed files with 8 additions and 10 deletions

View file

@ -209,11 +209,7 @@ func formatFileSize(b int64) string {
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB",
float64(b)/float64(div), "KMGTPE"[exp])
base := math.Log(float64(b)) / math.Log(unit)
number := math.Pow(unit, base-math.Floor(base))
return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
}

View file

@ -156,6 +156,8 @@ func TestFormatFileSize(t *testing.T) {
input int64
expected string
}{
{0, "0 B"},
{1, "1 B"},
{500, "500 B"},
{1024, "1.0 KiB"},
{43520, "42.5 KiB"},