Use underlying float precision when formatting floats (#353)
Currently, all float values are formatted using 64-bit, but that
incorrectly formats float32 values like 0.01 and 0.99.
See https://play.golang.org/p/jbseI1ivyMW for more context.
Fixes #352.
diff --git a/encode.go b/encode.go
index b3c62b3..a14435e 100644
--- a/encode.go
+++ b/encode.go
@@ -333,7 +333,13 @@
}
func (e *encoder) floatv(tag string, in reflect.Value) {
- s := strconv.FormatFloat(in.Float(), 'g', -1, 64)
+ // Issue #352: When formatting, use the precision of the underlying value
+ precision := 64
+ if in.Kind() == reflect.Float32 {
+ precision = 32
+ }
+
+ s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
switch s {
case "+Inf":
s = ".inf"
diff --git a/encode_test.go b/encode_test.go
index 0324a90..f0911a7 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -76,6 +76,9 @@
map[string]interface{}{"v": float64(0.1)},
"v: 0.1\n",
}, {
+ map[string]interface{}{"v": float32(0.99)},
+ "v: 0.99\n",
+ }, {
map[string]interface{}{"v": -0.1},
"v: -0.1\n",
}, {