summaryrefslogtreecommitdiff
path: root/conv
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2017-10-26 11:06:50 -0400
committerDave Henderson <dhenderson@gmail.com>2017-10-26 11:06:50 -0400
commit105630b8166c0df6ffae140964733ea6c5212fec (patch)
tree42212280c73cd961bf2b5775e5d9f46f494f6bb6 /conv
parenta9e9acc6fec55b5036f1ffec4bc130961a9ef4c0 (diff)
Fixing bugs in ToInt64/ToFloat64
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
Diffstat (limited to 'conv')
-rw-r--r--conv/conv.go22
-rw-r--r--conv/conv_test.go6
2 files changed, 22 insertions, 6 deletions
diff --git a/conv/conv.go b/conv/conv.go
index 8d427ce0..464df7dd 100644
--- a/conv/conv.go
+++ b/conv/conv.go
@@ -114,7 +114,13 @@ func ToInt64(v interface{}) int64 {
if str, ok := v.(string); ok {
iv, err := strconv.ParseInt(str, 0, 64)
if err != nil {
- return 0
+ // maybe it's a float?
+ var fv float64
+ fv, err = strconv.ParseFloat(str, 64)
+ if err != nil {
+ return 0
+ }
+ return ToInt64(fv)
}
return iv
}
@@ -168,11 +174,19 @@ func ToInts(in ...interface{}) []int {
// ToFloat64 - taken from github.com/Masterminds/sprig
func ToFloat64(v interface{}) float64 {
if str, ok := v.(string); ok {
- iv, err := strconv.ParseFloat(str, 64)
+ // this is inefficient, but it's the only way I can think of to
+ // properly convert octal integers to floats
+ iv, err := strconv.ParseInt(str, 0, 64)
if err != nil {
- return 0
+ // ok maybe it's a float?
+ var fv float64
+ fv, err = strconv.ParseFloat(str, 64)
+ if err != nil {
+ return 0
+ }
+ return fv
}
- return iv
+ return float64(iv)
}
val := reflect.Indirect(reflect.ValueOf(v))
diff --git a/conv/conv_test.go b/conv/conv_test.go
index 52b924b1..5150fbcd 100644
--- a/conv/conv_test.go
+++ b/conv/conv_test.go
@@ -93,6 +93,8 @@ func TestToInt64(t *testing.T) {
assert.Equal(t, int64(1), ToInt64(float32(1)))
assert.Equal(t, int64(1), ToInt64(float64(1)))
assert.Equal(t, int64(42), ToInt64(42))
+ assert.Equal(t, int64(42), ToInt64("42.0"))
+ assert.Equal(t, int64(3), ToInt64("3.5"))
assert.Equal(t, int64(-1), ToInt64(uint64(math.MaxUint64)))
assert.Equal(t, int64(0xFF), ToInt64(uint8(math.MaxUint8)))
@@ -145,12 +147,12 @@ func TestToInts(t *testing.T) {
}
func TestToFloat64(t *testing.T) {
- z := []interface{}{0, 0.0, nil, false, float32(0), "", "0", "foo", int64(0), uint(0)}
+ z := []interface{}{0, 0.0, nil, false, float32(0), "", "0", "foo", int64(0), uint(0), "0x0", "00"}
for _, n := range z {
assert.Equal(t, 0.0, ToFloat64(n))
}
assert.Equal(t, 1.0, ToFloat64(true))
- z = []interface{}{42, 42.0, float32(42), "42", "42.0", uint8(42)}
+ z = []interface{}{42, 42.0, float32(42), "42", "42.0", uint8(42), "0x2A", "052"}
for _, n := range z {
assert.Equal(t, 42.0, ToFloat64(n))
}