Outputting Numbers with Thousands Comma in Go's fmt.Printf
Go's fmt.Printf function provides formatting options for outputting various data types. However, it does not have an explicit support for adding thousands commas to numbers.
Overcoming the Absence of Commas
To add thousands commas to numbers, a third-party library, such as golang.org/x/text/message, can be utilized. This library enables the formatting of numbers according to localized conventions.
Implementation
To use golang.org/x/text/message for outputting numbers with thousands commas:
First, import the library:
<code class="go">import ( "golang.org/x/text/language" "golang.org/x/text/message" )</code>
Create a new message.Printer object, specifying the desired language for formatting:
<code class="go">p := message.NewPrinter(language.English)</code>
Call the Printf method on the message.Printer object, passing in the number to be formatted:
<code class="go">p.Printf("%d\n", 1000)</code>
Example
The following example prints the number 1000 with thousands commas using golang.org/x/text/message:
<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>
By using golang.org/x/text/message, it becomes possible to conveniently output numbers with thousands commas, adhering to localized formatting conventions for different languages.
The above is the detailed content of How to Output Numbers with Thousands Commas in Go\'s fmt.Printf?. For more information, please follow other related articles on the PHP Chinese website!