-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
percentage.go
50 lines (40 loc) · 1.41 KB
/
percentage.go
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
45
46
47
48
49
50
package kubernetes
import (
"strconv"
"strings"
"github.com/shopspring/decimal"
)
const defaultPercentageValuePrecision = 3
// percentageValue is int64 form of percentage value with 10^-3 precision.
type percentageValue int64
// toFloat64 returns its decimal float64 value.
func (v percentageValue) toFloat64() float64 {
return float64(v) / (1000 * 100)
}
func (v percentageValue) computeWeight(count int) int {
if count == 0 {
return 0
}
return int(float64(v) / float64(count))
}
// String returns its string form of percentage value.
func (v percentageValue) String() string {
return strconv.FormatFloat(v.toFloat64()*100, 'f', defaultPercentageValuePrecision, 64) + "%"
}
// newPercentageValueFromString tries to read percentage value from string, it can be either "1.1" or "1.1%", "6%".
// It will lose the extra precision if there are more digits after decimal point.
func newPercentageValueFromString(rawValue string) (percentageValue, error) {
if strings.HasSuffix(rawValue, "%") {
rawValue = rawValue[:len(rawValue)-1]
}
value, err := strconv.ParseFloat(rawValue, 64)
if err != nil {
return 0, err
}
return newPercentageValueFromFloat64(value) / 100, nil
}
// newPercentageValueFromFloat64 reads percentage value from float64
func newPercentageValueFromFloat64(f float64) percentageValue {
value := decimal.NewFromFloat(f).Mul(decimal.NewFromFloat(1000 * 100))
return percentageValue(value.IntPart())
}