Skip to content

Commit 720cd42

Browse files
committed
encoding/json: use standard ES6 formatting for numbers during marshal
golang/go@92b3e36
1 parent 9b00d50 commit 720cd42

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

stream_float.go

+16
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ func (stream *Stream) WriteFloat32(val float32) {
2727
}
2828
}
2929
stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32)
30+
if fmt == 'e' {
31+
// clean up e-09 to e-9
32+
n := len(stream.buf)
33+
if n >= 4 && stream.buf[n-4] == 'e' && stream.buf[n-3] == '-' && stream.buf[n-2] == '0' {
34+
stream.buf[n-2] = stream.buf[n-1]
35+
stream.buf = stream.buf[:n-1]
36+
}
37+
}
3038
}
3139

3240
// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster
@@ -76,6 +84,14 @@ func (stream *Stream) WriteFloat64(val float64) {
7684
}
7785
}
7886
stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64)
87+
if fmt == 'e' {
88+
// clean up e-09 to e-9
89+
n := len(stream.buf)
90+
if n >= 4 && stream.buf[n-4] == 'e' && stream.buf[n-3] == '-' && stream.buf[n-2] == '0' {
91+
stream.buf[n-2] = stream.buf[n-1]
92+
stream.buf = stream.buf[:n-1]
93+
}
94+
}
7995
}
8096

8197
// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster

value_tests/float_test.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ import (
44
"bytes"
55
"encoding/json"
66
"fmt"
7-
"github.com/json-iterator/go"
8-
"github.com/stretchr/testify/require"
97
"strconv"
108
"testing"
9+
10+
jsoniter "github.com/json-iterator/go"
11+
"github.com/stretchr/testify/require"
1112
)
1213

1314
func Test_read_float(t *testing.T) {
@@ -88,7 +89,7 @@ func Test_write_float32(t *testing.T) {
8889

8990
stream = jsoniter.NewStream(jsoniter.ConfigDefault, nil, 0)
9091
stream.WriteFloat32(float32(0.0000001))
91-
should.Equal("1e-07", string(stream.Buffer()))
92+
should.Equal("1e-7", string(stream.Buffer()))
9293
}
9394

9495
func Test_write_float64(t *testing.T) {
@@ -125,5 +126,5 @@ func Test_write_float64(t *testing.T) {
125126

126127
stream = jsoniter.NewStream(jsoniter.ConfigDefault, nil, 0)
127128
stream.WriteFloat64(float64(0.0000001))
128-
should.Equal("1e-07", string(stream.Buffer()))
129+
should.Equal("1e-7", string(stream.Buffer()))
129130
}

0 commit comments

Comments
 (0)