From 1249e92ef315e88c6384dd7120ec05a233e5ce9f Mon Sep 17 00:00:00 2001 From: Edward Welch <edward.welch@grafana.com> Date: Tue, 9 Jul 2019 21:25:45 -0400 Subject: [PATCH] use strconf.FormatFloat instead of fmt.Sprintf for converting floats to strings, this way we can eliminate non significant trailing zeros such that the float value 1 would be "1" as a string instead of "1.000000" --- pkg/logentry/stages/util.go | 4 ++-- pkg/logentry/stages/util_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/pkg/logentry/stages/util.go b/pkg/logentry/stages/util.go index ee340e4b..95a94b6e 100644 --- a/pkg/logentry/stages/util.go +++ b/pkg/logentry/stages/util.go @@ -85,9 +85,9 @@ func getString(unk interface{}) (string, error) { switch i := unk.(type) { case float64: - return fmt.Sprintf("%f", i), nil + return strconv.FormatFloat(i, 'f', -1, 64), nil case float32: - return fmt.Sprintf("%f", i), nil + return strconv.FormatFloat(float64(i), 'f', -1, 32), nil case int64: return strconv.FormatInt(i, 10), nil case int32: diff --git a/pkg/logentry/stages/util_test.go b/pkg/logentry/stages/util_test.go index 26bd2f76..06f8f46c 100644 --- a/pkg/logentry/stages/util_test.go +++ b/pkg/logentry/stages/util_test.go @@ -37,3 +37,31 @@ func assertLabels(t *testing.T, expect map[string]string, got model.LabelSet) { assert.Equal(t, model.LabelValue(v), gotV, "mismatch label value") } } + +// Verify the formatting of float conversion to make sure there are not any trailing zeros, +// and also make sure unix timestamps are converted properly +func TestGetString(t *testing.T) { + var f64, f64_1 float64 + var f32 float32 + f64 = 1 + f64_1 = 1562723913000 + f32 = 2.02 + s64, err := getString(f64) + if err != nil { + t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err) + return + } + s64_1, err := getString(f64_1) + if err != nil { + t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err) + return + } + s32, err := getString(f32) + if err != nil { + t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err) + return + } + assert.Equal(t, "1", s64) + assert.Equal(t, "2.02", s32) + assert.Equal(t, "1562723913000", s64_1) +} -- GitLab