When using golang.org/x/text/currency to format currency values in Golang, it's possible to retrieve the appropriate format from the system locale by leveraging the DisplayTags and FromTag functions. The DisplayTags function provides localized names for languages, and FromTag retrieves a currency based on the language tag.
n := display.Tags(language.English)
for _, lcode := range []string{"en_US", "pt_BR", "de", "ja", "hi"} {
lang := language.MustParse(lcode)
cur, _ := currency.FromTag(lang)
scale, _ := currency.Cash.Rounding(cur) // fractional digits
dec := number.Decimal(100000.00, number.Scale(scale))
p := message.NewPrinter(lang)
p.Printf("$v (%v): %v%v\n", n.Name(lang), cur, currency.Symbol(cur), dec)
}
// Output:
// American English (USD): $100,000.00
// Brazilian Portuguese (BRL): R$100.000,00
// German (EUR): €100.000,00
// Japanese (JPY): ¥100,000
// Hindi (INR): ₹1,00,000.00
Alternatively, you can explicitly specify the language or ISO currency code to retrieve the correct currency format. However, you must provide the language in which to format the number:
// Parse ISO currency code and specify language
for _, iso := range []string{"USD", "BRL", "EUR", "JPY", "INR"} {
cur := currency.MustParseISO(iso)
scale, _ := currency.Cash.Rounding(cur) // fractional digits
dec := number.Decimal(100000.00, number.Scale(scale))
p := message.NewPrinter(language.English)
p.Printf("%v: %v%v\n", cur, currency.Symbol(cur), dec)
}
// Output:
// USD: $100,000.00
// BRL: R$100,000.00
// EUR: €100,000.00
// JPY: ¥100,000
// INR: ₹100,000.00
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3