Fix formatting helpers: add math import and self-contained reduction formatting
This commit is contained in:
parent
b31f528dc5
commit
4f4ecc450d
|
|
@ -1,6 +1,9 @@
|
|||
package utils
|
||||
|
||||
import "math"
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// ReductionText returns a string like "965 MB (24% reduction)" given original bytes and new bytes.
|
||||
func ReductionText(origBytes, newBytes int64) string {
|
||||
|
|
@ -14,14 +17,33 @@ func ReductionText(origBytes, newBytes int64) string {
|
|||
if reduction <= 0 {
|
||||
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.
|
||||
func formatPercent(val float64) string {
|
||||
val = math.Round(val*10) / 10 // one decimal
|
||||
if val == math.Trunc(val) {
|
||||
return formatInt(int(val)) + "%"
|
||||
return fmt.Sprintf("%d%%", int(val))
|
||||
}
|
||||
return formatFloat(val) + "%"
|
||||
return fmt.Sprintf("%.1f%%", val)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package utils
|
|||
import (
|
||||
"fmt"
|
||||
"image/color"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user