Home > Article > Backend Development > How to Add Commas to Numbers in Go\'s fmt.Printf Output?
Adding Commas to Go's fmt.Printf Output
fmt.Printf is a versatile formatting function in Go, but it lacks the ability to add comma separators to integers by default. This limitation can be encountered when formatting numeric values such as currency or large numbers for display purposes.
To overcome this, we can leverage the golang.org/x/text/message library, which provides localized formatting capabilities.
Code Example:
<code class="go">package main import ( "golang.org/x/text/language" "golang.org/x/text/message" ) func main() { p := message.NewPrinter(language.English) p.Printf("%d\n", 1000) // Output: // 1,000 }</code>
In this example, we use the NewPrinter function to create a message.Printer object with the specified language (English in this case). The Printf method formats the integer 1000 using the localized formatting rules for English, which include the addition of commas for numbers over 999. By default, the printer uses the CLDR (Common Locale Data Repository) database for formatting rules, ensuring a standardized and localized output.
The above is the detailed content of How to Add Commas to Numbers in Go\'s fmt.Printf Output?. For more information, please follow other related articles on the PHP Chinese website!