"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Leverage System Locale Resources for Currency Formatting in Go?

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

Published on 2024-11-09
Browse:404

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.

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

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:

// 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
Release Statement This article is reproduced at: 1729688479 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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