Skip to content

Commit e3d5f50

Browse files
authored
Update readable.go
1 parent 4b6acec commit e3d5f50

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

readable/readable.go

+46
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,49 @@ func FormatDuration(buf []byte, d time.Duration) []byte {
4848
}
4949
return buf
5050
}
51+
52+
53+
// FormatNumberCompact formats numbers into a compact form using 'k' for thousand, 'M' for million, etc.,
54+
// aiming for zero heap allocations. The buffer must be pre-allocated with enough space.
55+
func FormatNumberCompact(num int64, buf []byte) []byte {
56+
if num == 0 {
57+
return append(buf, '0')
58+
}
59+
60+
// Determine the scale and suffix
61+
suffix := ""
62+
value := float64(num)
63+
if num < 0 {
64+
value = -value // Make positive for logarithmic calculation
65+
}
66+
67+
switch {
68+
case value < 1000:
69+
return strconv.AppendInt(buf, num, 10) // No suffix needed for < 1000
70+
case value < 1_000_000:
71+
value /= 1000
72+
suffix = "k"
73+
case value < 1_000_000_000:
74+
value /= 1_000_000
75+
suffix = "M"
76+
default:
77+
value /= 1_000_000_000
78+
suffix = "B"
79+
}
80+
81+
// Adjust the number to one decimal place and format
82+
value = math.Round(value*10) / 10
83+
startIndex := len(buf)
84+
buf = strconv.AppendFloat(buf, value, 'f', 1, 64)
85+
86+
// Remove unnecessary decimal and zero if integer value
87+
if buf[len(buf)-2] == '.' && buf[len(buf)-1] == '0' {
88+
buf = buf[:len(buf)-2] // Remove trailing ".0"
89+
}
90+
91+
// Append the suffix
92+
buf = append(buf, suffix...)
93+
94+
return buf
95+
}
96+

0 commit comments

Comments
 (0)