From 5420a8b6744d3b0345ab293f6fcba19c978f1183 Mon Sep 17 00:00:00 2001 From: Prashant Varanasi Date: Wed, 28 Mar 2018 12:50:20 -0700 Subject: [PATCH] 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. --- encode.go | 8 +++++++- encode_test.go | 3 +++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/encode.go b/encode.go index b3c62b39..a14435e8 100644 --- a/encode.go +++ b/encode.go @@ -333,7 +333,13 @@ func (e *encoder) timev(tag string, in reflect.Value) { } 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 0324a909..f0911a76 100644 --- a/encode_test.go +++ b/encode_test.go @@ -75,6 +75,9 @@ var marshalTests = []struct { }, { 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",