Formatting Integers with Thousands Commas in Go
Go's builtin fmt.Printf function doesn't natively support outputting integers with thousands commas. However, there are several ways to achieve this.
One option is to use the golang.org/x/text/message package, which provides localized formatting for any language supported by the Unicode CLDR. Here's an 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>
This code uses the English language locale, but you can specify any other supported locale if desired.
Another option is to use a third-party library, such as [github.com/AlekSi/decimal](https://github.com/AlekSi/decimal). This library provides a variety of methods for formatting numbers, including the ability to add thousands commas. Here's an example:
<code class="go">package main import ( "github.com/AlekSi/decimal" ) func main() { num := decimal.NewFromFloat(1000) str := num.String() fmt.Println(str) // Output: // 1,000 }</code>
Finally, if you don't want to use any external libraries, you can manually format the number yourself. This is relatively simple to do. First, you need to convert the integer to a string. Then, you need to insert commas at the appropriate positions. Here's how to do it:
<code class="go">func fmtComma(n int) string { str := strconv.Itoa(n) formatted := "" for i := len(str); i > 0; i -= 3 { if i == len(str) { formatted = str[:i] } else { formatted = str[i-3:i] + "," + formatted } } return formatted } func main() { fmt.Println(fmtComma(1000)) // Output: // 1,000 }</code>
The above is the detailed content of How can I format integers with thousands commas in Go?. For more information, please follow other related articles on the PHP Chinese website!