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.
<code class="go">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("%24v (%v): %v%v\n", n.Name(lang), cur, currency.Symbol(cur), dec) } // Output: // American English (USD): 0,000.00 // Brazilian Portuguese (BRL): R0.000,00 // German (EUR): €100.000,00 // Japanese (JPY): ¥100,000 // Hindi (INR): ₹1,00,000.00</code>
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:
<code class="go">// 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: 0,000.00 // BRL: R0,000.00 // EUR: €100,000.00 // JPY: ¥100,000 // INR: ₹100,000.00</code>
The above is the detailed content of How Can I Leverage System Locale Resources for Currency Formatting in Go?. For more information, please follow other related articles on the PHP Chinese website!