mirror of
https://github.com/json-iterator/go.git
synced 2024-11-27 08:30:57 +02:00
write float64
This commit is contained in:
parent
ba3c30799b
commit
bdbf8dcd42
@ -37,3 +37,33 @@ func (stream *Stream) WriteFloat32(val float32) {
|
||||
stream.n--;
|
||||
}
|
||||
}
|
||||
|
||||
func (stream *Stream) WriteFloat64(val float64) {
|
||||
if val < 0 {
|
||||
stream.writeByte('-')
|
||||
val = -val
|
||||
}
|
||||
if val > 0x4ffffff {
|
||||
stream.WriteRaw(strconv.FormatFloat(val, 'f', -1, 64));
|
||||
return
|
||||
}
|
||||
precision := 6
|
||||
exp := uint64(1000000) // 6
|
||||
lval := uint64(val * float64(exp) + 0.5)
|
||||
stream.WriteUint64(lval / exp)
|
||||
fval := lval % exp
|
||||
if fval == 0 {
|
||||
return
|
||||
}
|
||||
stream.writeByte('.')
|
||||
if stream.Available() < 10 {
|
||||
stream.Flush()
|
||||
}
|
||||
for p := precision - 1; p > 0 && fval < POW10[p]; p-- {
|
||||
stream.writeByte('0')
|
||||
}
|
||||
stream.WriteUint64(fval);
|
||||
for stream.buf[stream.n - 1] == '0' {
|
||||
stream.n--;
|
||||
}
|
||||
}
|
@ -58,6 +58,30 @@ func Test_write_float32(t *testing.T) {
|
||||
should.Equal("abcdefg1.123456", buf.String())
|
||||
}
|
||||
|
||||
func Test_write_float64(t *testing.T) {
|
||||
vals := []float64{0, 1, -1, 99, 0xff, 0xfff, 0xffff, 0xfffff, 0xffffff, 0x4ffffff, 0xfffffff,
|
||||
-0x4ffffff, -0xfffffff, 1.2345, 1.23456, 1.234567, 1.001}
|
||||
for _, val := range vals {
|
||||
t.Run(fmt.Sprintf("%v", val), func(t *testing.T) {
|
||||
should := require.New(t)
|
||||
buf := &bytes.Buffer{}
|
||||
stream := NewStream(buf, 4096)
|
||||
stream.WriteFloat64(val)
|
||||
stream.Flush()
|
||||
should.Nil(stream.Error)
|
||||
should.Equal(strconv.FormatFloat(val, 'f', -1, 64), buf.String())
|
||||
})
|
||||
}
|
||||
should := require.New(t)
|
||||
buf := &bytes.Buffer{}
|
||||
stream := NewStream(buf, 10)
|
||||
stream.WriteRaw("abcdefg")
|
||||
stream.WriteFloat64(1.123456)
|
||||
stream.Flush()
|
||||
should.Nil(stream.Error)
|
||||
should.Equal("abcdefg1.123456", buf.String())
|
||||
}
|
||||
|
||||
func Benchmark_jsoniter_float(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for n := 0; n < b.N; n++ {
|
||||
|
Loading…
Reference in New Issue
Block a user