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

Susan Sarandon
Release: 2024-10-24 02:27:01
Original
486 people have browsed it

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:

<code class="go">unit, _ := currency.ParseISO("BRL")
p := message.NewPrinter(language.BrazilianPortuguese)
result := p.Sprint(currency.Symbol(unit.Amount(float64(valor) / 100)))</code>
Copy after login

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:

<code class="go">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)))
}</code>
Copy after login

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.

The above is the detailed content of How to Format Currency Values with Commas and Thousand Separators Using Currency.Symbol 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!