Skip to content

Commit

Permalink
Use underlying float precision when formatting floats (#353)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
prashantv authored and niemeyer committed Mar 28, 2018
1 parent 4fc5987 commit 5420a8b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
8 changes: 7 additions & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 5420a8b

Please sign in to comment.