Skip to content

Commit 4427aef

Browse files
committed
✨ feat: mathutil - add new func: FormatBytes Format the byte size to be a readable string.
1 parent e2147b2 commit 4427aef

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

mathutil/format.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@ func DataSize(size uint64) string {
2222
}
2323
}
2424

25+
// FormatBytes Format the byte size to be a readable string. eg: 1024 => 1 KB
26+
func FormatBytes(bytes int) string {
27+
const unit = 1024
28+
if bytes < unit {
29+
return fmt.Sprintf("%d B", bytes)
30+
}
31+
32+
div, exp := int64(unit), 0
33+
for n := bytes / unit; n >= unit; n /= unit {
34+
div *= unit
35+
exp++
36+
}
37+
return fmt.Sprintf("%.2f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
38+
}
39+
2540
var timeFormats = [][]int{
2641
{0},
2742
{1},

mathutil/format_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,25 @@ func TestDataSize(t *testing.T) {
2424
}
2525
}
2626

27+
func TestFormatBytes(t *testing.T) {
28+
tests := []struct {
29+
input int
30+
expected string
31+
}{
32+
{0, "0 B"},
33+
{1024, "1.00 KB"},
34+
{1536, "1.50 KB"},
35+
{1048576, "1.00 MB"},
36+
{1073741824, "1.00 GB"},
37+
{1200346778, "1.12 GB"},
38+
}
39+
40+
for _, tt := range tests {
41+
result := mathutil.FormatBytes(tt.input)
42+
assert.Eq(t, tt.expected, result)
43+
}
44+
}
45+
2746
func TestHowLongAgo(t *testing.T) {
2847
tests := []struct {
2948
args int64

0 commit comments

Comments
 (0)