bojanz / currency

Currency handling for Go.

Home Page:https://pkg.go.dev/github.com/bojanz/currency

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why does this code work? What is the purpose of Locale?

curiosport opened this issue · comments

I ran into the problem that I only have the country name and not the Locale, so reading the code among other things in the end I don't understand what is the purpose of Locale in this package?

Why if I do this don't I get any errors or an empty output?
locale := currency.NewLocale(" ")

package main

import (
	"fmt"

	"github.com/bojanz/currency"
)

func main() {
	locale := currency.NewLocale(" ")
	formatter := currency.NewFormatter(locale)
	amount, err := currency.NewAmount("1245.988", "JPY")

	fmt.Println(err, formatter.Format(amount))

	formatter.MaxDigits = 2
	fmt.Println(formatter.Format(amount))

	formatter.NoGrouping = true
	amount, _ = currency.NewAmount("1245", "EUR")
	fmt.Println(formatter.Format(amount))

	formatter.MinDigits = 0
	fmt.Println(formatter.Format(amount))

	formatter.CurrencyDisplay = currency.DisplayNone
	fmt.Println(formatter.Format(amount))
}

Output:

<nil> ¥1,245.988
¥1,245.99
€1245.00
€1245
1245

The locale is important because currency formatting varies by both language and country, and the locale (potentially) has both.

We fall back to en if the specified locale is not found, that's why your code works.

Consumers will sometimes assemble combinations that do not exist such as de-RS (German - Serbia), in which case you want there to be a fallback to a locale that does exist (such as de). And at the top of the fallback tree is en.

We rely on this when deduplicating locale data, so de-DE is not included if it's identical to its parent, de.

I've made two commits to improve the current behavior and ensure " " is always treated the same as "en".

d662aac
6f1903f