Skip to content
This repository was archived by the owner on Apr 1, 2025. It is now read-only.

Commit 5420a8b

Browse files
prashantvniemeyer
authored andcommitted
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.
1 parent 4fc5987 commit 5420a8b

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

encode.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,13 @@ func (e *encoder) timev(tag string, in reflect.Value) {
333333
}
334334

335335
func (e *encoder) floatv(tag string, in reflect.Value) {
336-
s := strconv.FormatFloat(in.Float(), 'g', -1, 64)
336+
// Issue #352: When formatting, use the precision of the underlying value
337+
precision := 64
338+
if in.Kind() == reflect.Float32 {
339+
precision = 32
340+
}
341+
342+
s := strconv.FormatFloat(in.Float(), 'g', -1, precision)
337343
switch s {
338344
case "+Inf":
339345
s = ".inf"

encode_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ var marshalTests = []struct {
7575
}, {
7676
map[string]interface{}{"v": float64(0.1)},
7777
"v: 0.1\n",
78+
}, {
79+
map[string]interface{}{"v": float32(0.99)},
80+
"v: 0.99\n",
7881
}, {
7982
map[string]interface{}{"v": -0.1},
8083
"v: -0.1\n",

0 commit comments

Comments
 (0)