Browse Source

codec: json should encode regular floats without 'E' all the time.

We previously encoded floats using 'E' format, which meant that even
for a float like 3232, we encoded as 3.232E+3 (instead of 3232.0).

Now, we encode as 3232.0.

Note: For precision (as this package tries to infer whether a float or an int),
we have to always have an E or a . in the number when encoding.

Fixes #174
Ugorji Nwoke 9 years ago
parent
commit
b7eff9abce
1 changed files with 10 additions and 2 deletions
  1. 10 2
      codec/json.go

+ 10 - 2
codec/json.go

@@ -197,12 +197,20 @@ func (e *jsonEncDriver) EncodeBool(b bool) {
 }
 
 func (e *jsonEncDriver) EncodeFloat32(f float32) {
-	e.w.writeb(strconv.AppendFloat(e.b[:0], float64(f), 'E', -1, 32))
+	e.encodeFloat(float64(f), 32)
 }
 
 func (e *jsonEncDriver) EncodeFloat64(f float64) {
 	// e.w.writestr(strconv.FormatFloat(f, 'E', -1, 64))
-	e.w.writeb(strconv.AppendFloat(e.b[:0], f, 'E', -1, 64))
+	e.encodeFloat(f, 64)
+}
+
+func (e *jsonEncDriver) encodeFloat(f float64, numbits int) {
+	x := strconv.AppendFloat(e.b[:0], float64(f), 'G', -1, numbits)
+	e.w.writeb(x)
+	if bytes.IndexByte(x, 'E') == -1 && bytes.IndexByte(x, '.') == -1 {
+		e.w.writen2('.', '0')
+	}
 }
 
 func (e *jsonEncDriver) EncodeInt(v int64) {