File: format.go

package info (click to toggle)
golang-pb 0.0~git20131219-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 88 kB
  • ctags: 40
  • sloc: makefile: 7
file content (44 lines) | stat: -rw-r--r-- 916 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package pb

import (
	"fmt"
	"strings"
	"strconv"
)


const (
	// By default, without type handle
	U_NO = 0
	// Handle as b, Kb, Mb, etc
	U_BYTES = 1
)

// Format integer
func Format(i int64, units int) string {
	switch units {
		case U_BYTES:
			return FormatBytes(i)
	}
	// by default just convert to string
	return strconv.Itoa(int(i))
}


// Convert bytes to human readable string. Like a 2 MiB, 64.2 KiB, 52 B
func FormatBytes(i int64) (result string) {
	switch {
	case i > (1024 * 1024 * 1024 * 1024):
		result = fmt.Sprintf("%#.02f TB", float64(i)/1024/1024/1024/1024)
	case i > (1024 * 1024 * 1024):
		result = fmt.Sprintf("%#.02f GB", float64(i)/1024/1024/1024)
	case i > (1024 * 1024):
		result = fmt.Sprintf("%#.02f MB", float64(i)/1024/1024)
	case i > 1024:
		result = fmt.Sprintf("%#.02f KB", float64(i)/1024)
	default:
		result = fmt.Sprintf("%d B", i)
	}
	result = strings.Trim(result, " ")
	return
}