Home > Article > Backend Development > How to Format Integers with Thousands Commas using fmt.Printf in Go?
Comma-Separated Integers with fmt.Printf
In Go, the fmt.Printf function provides a versatile way to format and print various data types, including integers. However, by default, fmt.Printf does not support outputting integers with thousands commas.
To address this need, the golang.org/x/text/message package offers localized formatting, allowing you to print numbers according to the cultural norms of different languages.
Utilizing the message Package
To use the message package:
Import the package into your Go program:
<code class="go">import ( "golang.org/x/text/language" "golang.org/x/text/message" )</code>
Create a message Printer for a specific language. In this case, we use English:
<code class="go">p := message.NewPrinter(language.English)</code>
Use the Printer to format and print your integer using "%d":
<code class="go">p.Printf("%d\n", 1000)</code>
Example Output
Running the provided code will print the integer 1000 with a thousands comma separator:
1,000
This approach leverages the Unicode CLDR (Common Locale Data Repository) to provide accurate and culturally appropriate formatting for various languages and locales.
The above is the detailed content of How to Format Integers with Thousands Commas using fmt.Printf in Go?. For more information, please follow other related articles on the PHP Chinese website!