Просмотр исходного кода

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.
Prashant Varanasi 8 лет назад
Родитель
Сommit
5420a8b674
2 измененных файлов с 10 добавлено и 1 удалено
  1. 7 1
      encode.go
  2. 3 0
      encode_test.go

+ 7 - 1
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"

+ 3 - 0
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",