bytes.go 412 Bytes
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
package format

import "fmt"

Michael Yang's avatar
Michael Yang committed
5
6
7
8
9
10
11
const (
	Byte     = 1
	KiloByte = Byte * 1000
	MegaByte = KiloByte * 1000
	GigaByte = MegaByte * 1000
)

Michael Yang's avatar
Michael Yang committed
12
13
func HumanBytes(b int64) string {
	switch {
Michael Yang's avatar
Michael Yang committed
14
15
16
17
18
19
	case b > GigaByte:
		return fmt.Sprintf("%d GB", b/GigaByte)
	case b > MegaByte:
		return fmt.Sprintf("%d MB", b/MegaByte)
	case b > KiloByte:
		return fmt.Sprintf("%d KB", b/KiloByte)
Michael Yang's avatar
Michael Yang committed
20
21
22
23
	default:
		return fmt.Sprintf("%d B", b)
	}
}