diff --git a/format/format.go b/format/format.go index d233240f7..b48962c97 100644 --- a/format/format.go +++ b/format/format.go @@ -2,32 +2,41 @@ package format import ( "fmt" - "math" -) - -const ( - Thousand = 1000 - Million = Thousand * 1000 - Billion = Million * 1000 ) func HumanNumber(b uint64) string { + const ( + Thousand = 1000 + Million = Thousand * 1000 + Billion = Million * 1000 + Trillion = Billion * 1000 + ) + switch { + case b >= Trillion: + number := float64(b) / Trillion + return fmt.Sprintf("%sT", decimalPlace(number)) case b >= Billion: number := float64(b) / Billion - if number == math.Floor(number) { - return fmt.Sprintf("%.0fB", number) // no decimals if whole number - } - return fmt.Sprintf("%.2fB", number) // two decimals if not a whole number + return fmt.Sprintf("%sB", decimalPlace(number)) case b >= Million: number := float64(b) / Million - if number == math.Floor(number) { - return fmt.Sprintf("%.0fM", number) // no decimals if whole number - } - return fmt.Sprintf("%.2fM", number) // two decimals if not a whole number + return fmt.Sprintf("%sM", decimalPlace(number)) case b >= Thousand: - return fmt.Sprintf("%.0fK", float64(b)/Thousand) + number := float64(b) / Thousand + return fmt.Sprintf("%sK", decimalPlace(number)) default: return fmt.Sprintf("%d", b) } } + +func decimalPlace(number float64) string { + switch { + case number >= 100: + return fmt.Sprintf("%.0f", number) + case number >= 10: + return fmt.Sprintf("%.1f", number) + default: + return fmt.Sprintf("%.2f", number) + } +} diff --git a/format/format_test.go b/format/format_test.go index a02cb3c2c..ec4174f57 100644 --- a/format/format_test.go +++ b/format/format_test.go @@ -11,15 +11,14 @@ func TestHumanNumber(t *testing.T) { } testCases := []testCase{ - {0, "0"}, - {1000000, "1M"}, - {125000000, "125M"}, - {500500000, "500.50M"}, - {500550000, "500.55M"}, - {1000000000, "1B"}, - {2800000000, "2.80B"}, - {2850000000, "2.85B"}, - {1000000000000, "1000B"}, + {26000000, "26.0M"}, + {26000000000, "26.0B"}, + {1000, "1.00K"}, + {1000000, "1.00M"}, + {1000000000, "1.00B"}, + {1000000000000, "1.00T"}, + {100, "100"}, + {206000000, "206M"}, } for _, tc := range testCases {