From 6f1903fa66a3a07941b8271a561ae1bfa230c2f1 Mon Sep 17 00:00:00 2001 From: Bojan Zivanovic Date: Sun, 19 Nov 2023 11:37:32 +0100 Subject: [PATCH] Ensure that an empty locale is always treated the same as "en". This avoids empty output from GetSymbol() or the formatter. --- currency.go | 9 +++++---- currency_test.go | 3 ++- formatter_test.go | 4 ++++ 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/currency.go b/currency.go index 0b42c9a..276dd62 100644 --- a/currency.go +++ b/currency.go @@ -60,7 +60,7 @@ func GetSymbol(currencyCode string, locale Locale) (symbol string, ok bool) { } enLocale := Locale{Language: "en"} enUSLocale := Locale{Language: "en", Territory: "US"} - if locale == enLocale || locale == enUSLocale { + if locale == enLocale || locale == enUSLocale || locale.IsEmpty() { // The "en"/"en-US" symbol is always first. return symbols[0].symbol, true } @@ -87,13 +87,14 @@ func GetSymbol(currencyCode string, locale Locale) (symbol string, ok bool) { // getFormat returns the format for a locale. func getFormat(locale Locale) currencyFormat { - var format currencyFormat // CLDR considers "en" and "en-US" to be equivalent. // Fall back immediately for better performance enUSLocale := Locale{Language: "en", Territory: "US"} - if locale == enUSLocale { - locale = Locale{Language: "en"} + if locale == enUSLocale || locale.IsEmpty() { + return currencyFormats["en"] } + + var format currencyFormat for { localeID := locale.String() if cf, ok := currencyFormats[localeID]; ok { diff --git a/currency_test.go b/currency_test.go index 0025528..db86d1e 100644 --- a/currency_test.go +++ b/currency_test.go @@ -120,7 +120,8 @@ func TestGetSymbol(t *testing.T) { {"USD", currency.NewLocale("en-AU"), "US$", true}, {"USD", currency.NewLocale("es"), "US$", true}, {"USD", currency.NewLocale("es-ES"), "US$", true}, - {"USD", currency.NewLocale(""), "", true}, + // An empty locale should use "en" data. + {"USD", currency.NewLocale(""), "$", true}, } for _, tt := range tests { diff --git a/formatter_test.go b/formatter_test.go index fc510b8..8d87f1d 100644 --- a/formatter_test.go +++ b/formatter_test.go @@ -43,6 +43,10 @@ func TestFormatter_Format(t *testing.T) { {"1234.00", "CHF", "de-CH", "CHF\u00a01’234.00"}, {"1234.00", "CHF", "sr", "1.234,00\u00a0CHF"}, + // An empty locale should be equivalent to "en". + {"1234.59", "USD", "", "$1,234.59"}, + {"-1234.59", "USD", "", "-$1,234.59"}, + // Arabic digits. {"12345678.90", "USD", "ar", "\u200f١٢٬٣٤٥٬٦٧٨٫٩٠\u00a0US$"}, // Arabic extended (Persian) digits.