From 9ec74ab2f7a7161664182fd4e5e292fccffbc75f Mon Sep 17 00:00:00 2001 From: Dustin Sallings Date: Mon, 9 Jan 2023 20:44:38 -1000 Subject: [PATCH] Don't strip zeroes from numbers that don't have decimal points Fixes #106 --- ftoa.go | 3 +++ ftoa_test.go | 2 ++ si_test.go | 17 +++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/ftoa.go b/ftoa.go index 1c62b64..bce923f 100644 --- a/ftoa.go +++ b/ftoa.go @@ -6,6 +6,9 @@ import ( ) func stripTrailingZeros(s string) string { + if !strings.ContainsRune(s, '.') { + return s + } offset := len(s) - 1 for offset > 0 { if s[offset] == '.' { diff --git a/ftoa_test.go b/ftoa_test.go index 45ef9c5..43c74d5 100644 --- a/ftoa_test.go +++ b/ftoa_test.go @@ -14,6 +14,7 @@ import ( func TestFtoa(t *testing.T) { testList{ {"200", Ftoa(200), "200"}, + {"20", Ftoa(20.0), "20"}, {"2", Ftoa(2), "2"}, {"2.2", Ftoa(2.2), "2.2"}, {"2.02", Ftoa(2.02), "2.02"}, @@ -24,6 +25,7 @@ func TestFtoa(t *testing.T) { func TestFtoaWithDigits(t *testing.T) { testList{ {"1.23, 0", FtoaWithDigits(1.23, 0), "1"}, + {"20, 0", FtoaWithDigits(20.0, 0), "20"}, {"1.23, 1", FtoaWithDigits(1.23, 1), "1.2"}, {"1.23, 2", FtoaWithDigits(1.23, 2), "1.23"}, {"1.23, 3", FtoaWithDigits(1.23, 3), "1.23"}, diff --git a/si_test.go b/si_test.go index 2165857..3a129b4 100644 --- a/si_test.go +++ b/si_test.go @@ -126,3 +126,20 @@ func BenchmarkParseSI(b *testing.B) { ParseSI("2.2346ZB") } } + +// There was a report that zeroes were being truncated incorrectly +func TestBug106(t *testing.T) { + tests := []struct{ + in float64 + want string + }{ + {20.0, "20 U"}, + {200.0, "200 U"}, + } + + for _, test := range tests { + if got :=SIWithDigits(test.in, 0, "U") ; got != test.want { + t.Errorf("on %f got %v, want %v", test.in, got, test.want); + } + } +}