Fix formatting helpers: add math import and self-contained reduction formatting

This commit is contained in:
Stu Leak 2025-12-08 20:43:17 -05:00
parent b31f528dc5
commit 4f4ecc450d
2 changed files with 27 additions and 4 deletions

View File

@ -1,6 +1,9 @@
package utils package utils
import "math" import (
"fmt"
"math"
)
// ReductionText returns a string like "965 MB (24% reduction)" given original bytes and new bytes. // ReductionText returns a string like "965 MB (24% reduction)" given original bytes and new bytes.
func ReductionText(origBytes, newBytes int64) string { func ReductionText(origBytes, newBytes int64) string {
@ -14,14 +17,33 @@ func ReductionText(origBytes, newBytes int64) string {
if reduction <= 0 { if reduction <= 0 {
return "" return ""
} }
return formatFileSize(newBytes) + " (" + formatPercent(reduction) + " reduction)" return formatBytes(newBytes) + " (" + formatPercent(reduction) + " reduction)"
}
func formatBytes(b int64) string {
if b <= 0 {
return "0 B"
}
const (
KB = 1024
MB = KB * 1024
GB = MB * 1024
)
switch {
case b >= GB:
return fmt.Sprintf("%.2f GB", float64(b)/float64(GB))
case b >= MB:
return fmt.Sprintf("%.2f MB", float64(b)/float64(MB))
default:
return fmt.Sprintf("%.2f KB", float64(b)/float64(KB))
}
} }
// formatPercent renders a percentage with no trailing zeros after decimal. // formatPercent renders a percentage with no trailing zeros after decimal.
func formatPercent(val float64) string { func formatPercent(val float64) string {
val = math.Round(val*10) / 10 // one decimal val = math.Round(val*10) / 10 // one decimal
if val == math.Trunc(val) { if val == math.Trunc(val) {
return formatInt(int(val)) + "%" return fmt.Sprintf("%d%%", int(val))
} }
return formatFloat(val) + "%" return fmt.Sprintf("%.1f%%", val)
} }

View File

@ -3,6 +3,7 @@ package utils
import ( import (
"fmt" "fmt"
"image/color" "image/color"
"math"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"