From 262fa02e347ac7b91f3ed63301499d8f21bf6b79 Mon Sep 17 00:00:00 2001 From: Akshay Shah Date: Tue, 26 Jul 2016 15:59:04 -0700 Subject: [PATCH] Always use grade-school notation for floats (#104) In JSON output, always use grade-school notation for floats. Exponential notation is allowed by the JSON spec, but this is more obviously correct (and it matches the desired behavior for timestamps, which will soon use float fields). --- field.go | 5 ++--- json_encoder.go | 8 +++----- json_encoder_test.go | 2 +- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/field.go b/field.go index 2ca08b752..f24f8d854 100644 --- a/field.go +++ b/field.go @@ -75,9 +75,8 @@ func Bool(key string, val bool) Field { return Field{key: key, fieldType: boolType, ival: ival} } -// Float64 constructs a Field with the given key and value. The floating-point -// value is encoded using strconv.FormatFloat's 'g' option (exponential notation -// for large exponents, grade-school notation otherwise). +// Float64 constructs a Field with the given key and value. The way the +// floating-point value is represented is encoder-dependent. func Float64(key string, val float64) Field { return Field{key: key, fieldType: floatType, ival: int64(math.Float64bits(val))} } diff --git a/json_encoder.go b/json_encoder.go index c3183a2e9..94a83ea28 100644 --- a/json_encoder.go +++ b/json_encoder.go @@ -106,8 +106,8 @@ func (enc *jsonEncoder) AddInt64(key string, val int64) { // AddFloat64 adds a string key and float64 value to the encoder's fields. The // key is JSON-escaped, and the floating-point value is encoded using -// strconv.FormatFloat's 'g' option (exponential notation for large exponents, -// grade-school notation otherwise). +// strconv.FormatFloat's 'f' option (always use grade-school notation, even for +// large exponents). func (enc *jsonEncoder) AddFloat64(key string, val float64) { enc.addKey(key) switch { @@ -118,13 +118,11 @@ func (enc *jsonEncoder) AddFloat64(key string, val float64) { case math.IsInf(val, -1): enc.bytes = append(enc.bytes, `"-Inf"`...) default: - enc.bytes = strconv.AppendFloat(enc.bytes, val, 'g', -1, 64) + enc.bytes = strconv.AppendFloat(enc.bytes, val, 'f', -1, 64) } } // AddMarshaler adds a LogMarshaler to the encoder's fields. -// -// TODO: Encode the error into the message instead of returning. func (enc *jsonEncoder) AddMarshaler(key string, obj LogMarshaler) error { enc.addKey(key) enc.bytes = append(enc.bytes, '{') diff --git a/json_encoder_test.go b/json_encoder_test.go index 6de153c7d..76c743bce 100644 --- a/json_encoder_test.go +++ b/json_encoder_test.go @@ -103,7 +103,7 @@ func TestJSONAddInt64(t *testing.T) { func TestJSONAddFloat64(t *testing.T) { withJSONEncoder(func(enc *jsonEncoder) { enc.AddFloat64("baz", 1e10) - assertJSON(t, `"foo":"bar","baz":1e+10`, enc) + assertJSON(t, `"foo":"bar","baz":10000000000`, enc) // Keys should be escaped. enc.truncate()