Skip to content

Commit 914c4ff

Browse files
authored
json: Fix encoding complex with negative i (#1001)
Fix encoding of complex numbers with negative imaginary components. Previously, `2 - 3i` was encoded as the following: 2+-3i Instead of the following: 2-3i Fix this by handling negative imaginary components correctly. Fixes #995
1 parent d8fd848 commit 914c4ff

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

zapcore/json_encoder.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,11 @@ func (enc *jsonEncoder) AppendComplex128(val complex128) {
228228
// Because we're always in a quoted string, we can use strconv without
229229
// special-casing NaN and +/-Inf.
230230
enc.buf.AppendFloat(r, 64)
231-
enc.buf.AppendByte('+')
231+
// If imaginary part is less than 0, minus (-) sign is added by default
232+
// by AppendFloat.
233+
if i >= 0 {
234+
enc.buf.AppendByte('+')
235+
}
232236
enc.buf.AppendFloat(i, 64)
233237
enc.buf.AppendByte('i')
234238
enc.buf.AppendByte('"')

zapcore/json_encoder_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func TestJSONEncodeEntry(t *testing.T) {
6464
"so": "passes",
6565
"answer": 42,
6666
"common_pie": 3.14,
67+
"complex_value": "3.14-2.71i",
6768
"null_value": null,
6869
"array_with_null_elements": [{}, null, null, 2],
6970
"such": {
@@ -86,6 +87,7 @@ func TestJSONEncodeEntry(t *testing.T) {
8687
zap.String("so", "passes"),
8788
zap.Int("answer", 42),
8889
zap.Float64("common_pie", 3.14),
90+
zap.Complex128("complex_value", 3.14-2.71i),
8991
// Cover special-cased handling of nil in AddReflect() and
9092
// AppendReflect(). Note that for the latter, we explicitly test
9193
// correct results for both the nil static interface{} value

0 commit comments

Comments
 (0)