Add functions to support precise float compute of weight (#5663)

This commit is contained in:
mikezhang
2019-10-17 00:29:21 +09:00
committed by Ludovic Fernandez
parent 29ef007917
commit 9f72b6d1d5
9 changed files with 2097 additions and 8 deletions

View File

@@ -3,6 +3,8 @@ package kubernetes
import (
"strconv"
"strings"
"github.com/shopspring/decimal"
)
const defaultPercentageValuePrecision = 3
@@ -43,5 +45,6 @@ func newPercentageValueFromString(rawValue string) (percentageValue, error) {
// newPercentageValueFromFloat64 reads percentage value from float64
func newPercentageValueFromFloat64(f float64) percentageValue {
return percentageValue(f * (1000 * 100))
value := decimal.NewFromFloat(f).Mul(decimal.NewFromFloat(1000 * 100))
return percentageValue(value.IntPart())
}

View File

@@ -74,46 +74,54 @@ func TestNewPercentageValueFromString(t *testing.T) {
}{
{
value: "1%",
expectError: false,
expectedString: "1.000%",
expectedFloat64: 0.01,
},
{
value: "0.5",
expectError: false,
expectedString: "0.500%",
expectedFloat64: 0.005,
},
{
value: "99%",
expectError: false,
expectedString: "99.000%",
expectedFloat64: 0.99,
},
{
value: "99.9%",
expectError: false,
expectedString: "99.900%",
expectedFloat64: 0.999,
},
{
value: "-99.9%",
expectError: false,
expectedString: "-99.900%",
expectedFloat64: -0.999,
},
{
value: "-99.99999%",
expectError: false,
expectedString: "-99.999%",
expectedFloat64: -0.99999,
},
{
value: "0%",
expectError: false,
expectedString: "0.000%",
expectedFloat64: 0,
},
{
value: "2.3%",
expectedString: "2.300%",
expectedFloat64: 0.023,
},
{
value: "5.1%",
expectedString: "5.100%",
expectedFloat64: 0.051,
},
{
value: "83.85%",
expectedString: "83.850%",
expectedFloat64: 0.83850,
},
{
value: "%",
expectError: true,