Skip to content

Commit

Permalink
fix: properly stringify floats when writing to redis (resolves #25)
Browse files Browse the repository at this point in the history
  • Loading branch information
chetan committed Oct 9, 2023
1 parent 59ffe47 commit 10ab916
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
16 changes: 14 additions & 2 deletions kv.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -112,13 +113,24 @@ func walk(kv *KV, path string, obj interface{}, pos string) {
}

case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Float32, reflect.Float64, reflect.String, reflect.Bool:
reflect.String, reflect.Bool:

// stringify it
kv.add(fmt.Sprintf("%v", val.Interface()), path)
kv.add(stringify(val.Interface()), path)

case reflect.Float32, reflect.Float64:
kv.add(stringifyFloat(val.Float()), path)

default:
logrus.Warnf("unhandled kind %s: %#v\n", val.Kind(), obj)
}

}

func stringify(val interface{}) string {
return fmt.Sprintf("%v", val)
}

func stringifyFloat(val float64) string {
return strconv.FormatFloat(val, 'f', -1, 64)
}
24 changes: 24 additions & 0 deletions kv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,27 @@ func dumpKV(kv map[string]interface{}) {
fmt.Printf("%s = %s\n", k, v)
}
}

func Test_stringify(t *testing.T) {
v := 15552000
s := stringify(v)
require.Equal(t, "15552000", s, "int should match")

b := false
s = stringify(b)
require.Equal(t, "false", s, "bool should match")

b = true
s = stringify(b)
require.Equal(t, "true", s, "bool should match")
}

func Test_stringifyFloat(t *testing.T) {
f := float64(15552000)
s := stringifyFloat(f)
require.Equal(t, "15552000", s, "float should match")

f32 := float32(15552000)
s = stringifyFloat(float64(f32))
require.Equal(t, "15552000", s, "float should match")
}

0 comments on commit 10ab916

Please sign in to comment.