Encode non-fatal floats as integers in canonical mode
Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
This commit is contained in:
Родитель
d818992b91
Коммит
d62108ab70
|
@ -526,7 +526,13 @@ func (bits floatEncoder) encode(e *encodeState, v reflect.Value, quoted bool) {
|
||||||
if math.IsInf(f, 0) || math.IsNaN(f) || (e.canonical && math.Floor(f) != f) {
|
if math.IsInf(f, 0) || math.IsNaN(f) || (e.canonical && math.Floor(f) != f) {
|
||||||
e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
|
e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
|
||||||
}
|
}
|
||||||
b := strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
|
|
||||||
|
var b []byte
|
||||||
|
if e.canonical {
|
||||||
|
b = strconv.AppendInt(e.scratch[:0], int64(f), 10)
|
||||||
|
} else {
|
||||||
|
b = strconv.AppendFloat(e.scratch[:0], f, 'g', -1, int(bits))
|
||||||
|
}
|
||||||
if quoted {
|
if quoted {
|
||||||
e.WriteByte('"')
|
e.WriteByte('"')
|
||||||
}
|
}
|
||||||
|
|
|
@ -589,3 +589,17 @@ func TestCanonicalFloatError(t *testing.T) {
|
||||||
t.Errorf("want float error, got nil")
|
t.Errorf("want float error, got nil")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCanonicalFloatAsInt(t *testing.T) {
|
||||||
|
in := struct{ A float64 }{1234567}
|
||||||
|
|
||||||
|
b, err := MarshalCanonical(in)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Marshal(%q): %v", in, err)
|
||||||
|
}
|
||||||
|
out := string(b)
|
||||||
|
expected := `{"A":1234567}`
|
||||||
|
if out != expected {
|
||||||
|
t.Errorf("Marshal(%q) = %#q, want %#q", in, out, expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Загрузка…
Ссылка в новой задаче