"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 to Format Currency Values with Commas and Thousand Separators Using Currency.Symbol in Go?

How to Format Currency Values with Commas and Thousand Separators Using Currency.Symbol in Go?

Published on 2024-11-04
Browse:427

How to Format Currency Values with Commas and Thousand Separators Using Currency.Symbol in Go?

Formatting Currency Values with Currency.Symbol in Go

In Go, the golang.org/x/text/currency package provides a comprehensive solution for formatting currency values. This package allows developers to work with currency codes, symbols, and localization information to format values in human-readable formats.

Here's an example demonstrating how to use currency.Symbol to format a currency value:

unit, _ := currency.ParseISO("BRL")
p := message.NewPrinter(language.BrazilianPortuguese)
result := p.Sprint(currency.Symbol(unit.Amount(float64(valor) / 100)))

The output of the above code is "R$ 123.456,78". However, if you're getting a format with points instead of commas and no thousands separators, it's likely due to not setting the appropriate locale or language in the message.NewPrinter function.

To use system locale resources, you can specify the language in the message.NewPrinter function as follows:

import (
    "fmt"

    "golang.org/x/text/currency"
    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func main() {
    // Get the current locale
    locale, err := language.Parse(language.Default())
    if err != nil {
        panic(err)
    }

    // Use the locale to create a message printer
    p := message.NewPrinter(locale)

    // Format the currency value using currency.Symbol
    fmt.Println(p.Sprintf("%v", currency.Symbol(currency.MustParseISO("USD"), 12345678)))
}

This approach will automatically use the system's locale settings to format the currency value. For example, if the system locale is set to "en_US", the output will be "$12,345,678.00".

By leveraging the currency.Symbol function in conjunction with the message.NewPrinter function and proper locale handling, you can effectively format currency values in a wide range of locales and currency formats.

Release Statement This article is reprinted at: 1729688639 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