How can I format integers with thousands commas in Go?

Patricia Arquette
Release: 2024-10-30 18:57:30
Original
583 people have browsed it

How can I format integers with thousands commas in Go?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
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!