How Can I Leverage System Locale Resources for Currency Formatting in Go?

Patricia Arquette
Release: 2024-10-24 05:15:30
Original
285 people have browsed it

How Can I Leverage System Locale Resources for Currency Formatting in Go?

Currency Formatting in Golang Using currency.Symbol from golang.org/x/text/currency

Using System Locale Resources

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>
Copy after login

Specifying Language and ISO Codes

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!