From 24904dde666ce92c346c71ffbe7eed2430db6b6f Mon Sep 17 00:00:00 2001 From: Arthur Lu Date: Fri, 26 Jun 2026 20:51:46 +0000 Subject: [PATCH] improve FormatNumber logic --- units.go | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/units.go b/units.go index 24edd60..d9d84a2 100644 --- a/units.go +++ b/units.go @@ -24,30 +24,27 @@ const GiB uint64 = MiB * Base1024 const TiB uint64 = GiB * Base1024 func FormatNumber(val uint64, base uint64) (string, string) { + prefixes := []string{""} + switch base { + case Base1000: + prefixes = prefixesBase1000 + case Base1024: + prefixes = prefixesBase1024 + default: + } + valf := float64(val) basef := float64(base) steps := 0 - for math.Abs(valf) > basef && steps < 4 { + for math.Abs(valf) > basef && steps < len(prefixes)-1 { valf /= basef steps++ } - switch base { - case Base1000: - s := fmt.Sprintf("%.4f", valf) - s = strings.TrimRight(s, "0") - s = strings.TrimRight(s, ".") - prefixes := prefixesBase1000 - return s, prefixes[steps] - case Base1024: - s := fmt.Sprintf("%.4f", valf) - s = strings.TrimRight(s, "0") - s = strings.TrimRight(s, ".") - prefixes := prefixesBase1024 - return s, prefixes[steps] - default: - return "0", "" - } + s := fmt.Sprintf("%.4f", valf) + s = strings.TrimRight(s, "0") + s = strings.TrimRight(s, ".") + return s, prefixes[steps] } // Converts int, int32, and int64 to uint64. Less than 0 check.