From 0902b13705825cf69223163a9c02f31522b94ad3 Mon Sep 17 00:00:00 2001 From: Julien Riou Date: Sun, 28 Feb 2021 15:33:59 +0100 Subject: [PATCH] Add USD currency to price format on Twitter Signed-off-by: Julien Riou --- twitter.go | 12 +++++++----- twitter_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/twitter.go b/twitter.go index cdfbf08..e8dfc62 100644 --- a/twitter.go +++ b/twitter.go @@ -90,16 +90,18 @@ func (c *TwitterNotifier) buildHashtags(productName string) string { return "" } -// replace price currency by its symbol +// formatPrice using internationalization rules +// euro sign is placed after the value +// default the currency, or symbol if applicable, is placed before the value func formatPrice(value float64, currency string) string { - var symbol string switch { case currency == "EUR": - symbol = "€" + return fmt.Sprintf("%.2f€", value) + case currency == "USD": + return fmt.Sprintf("$%.2f", value) default: - symbol = currency + return fmt.Sprintf("%s%.2f", currency, value) } - return fmt.Sprintf("%.2f%s", value, symbol) } // NotifyWhenAvailable create a Twitter status for announcing that a product is available diff --git a/twitter_test.go b/twitter_test.go index 0ce7b65..db3af41 100644 --- a/twitter_test.go +++ b/twitter_test.go @@ -55,3 +55,27 @@ func TestBuildHashtags(t *testing.T) { }) } } + +func TestFormatPrice(t *testing.T) { + tests := []struct { + value float64 + currency string + expected string + }{ + {999.99, "EUR", "999.99€"}, + {999.99, "USD", "$999.99"}, + {999.99, "CHF", "CHF999.99"}, + {999.99, "", "999.99"}, + } + + for i, tc := range tests { + t.Run(fmt.Sprintf("TestFormatPrice#%d", i), func(t *testing.T) { + got := formatPrice(tc.value, tc.currency) + if got != tc.expected { + t.Errorf("for value %0.2f and currency %s, got %s, want %s", tc.value, tc.currency, got, tc.expected) + } else { + t.Logf("for value %0.2f and currency %s, got %s, want %s", tc.value, tc.currency, got, tc.expected) + } + }) + } +}