Skip to content

Commit

Permalink
Ensure that an empty locale is always treated the same as "en".
Browse files Browse the repository at this point in the history
This avoids empty output from GetSymbol() or the formatter.
  • Loading branch information
bojanz committed Nov 19, 2023
1 parent d662aac commit 6f1903f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
9 changes: 5 additions & 4 deletions currency.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion currency_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 6f1903f

Please sign in to comment.