format.go 782 Bytes
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
4
5
package format

import (
	"fmt"
	"math"
xuxzh1's avatar
init  
xuxzh1 committed
6
	"strconv"
mashun1's avatar
v1  
mashun1 committed
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
)

const (
	Thousand = 1000
	Million  = Thousand * 1000
	Billion  = Million * 1000
)

func HumanNumber(b uint64) string {
	switch {
	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("%.1fB", number) // one decimal if not a whole 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
	case b >= Thousand:
		return fmt.Sprintf("%.0fK", float64(b)/Thousand)
	default:
xuxzh1's avatar
init  
xuxzh1 committed
32
		return strconv.FormatUint(b, 10)
mashun1's avatar
v1  
mashun1 committed
33
34
	}
}