Cookies management by TermsFeed Cookie Consent

📒 Print a number with (comma) thousands separator in Go

numbers strings format

To print a number with thousands separator in Go, you can use the Printer object from the official golang.org/x/text/message package. Its job is to translate text strings from one language to another, and it also allows you to print numbers in a language-specific format.

More specifically, the message.Printer object allows a number to be formatted using the Unicode CLDR.

package main

import (
    "fmt"

    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func main() {
    number := 1_000_000.23456

    p := message.NewPrinter(language.English)
    withCommaThousandSep := p.Sprintf("%f", number)
    fmt.Println(withCommaThousandSep)
}

Output:

1,000,000.234560

In standard English format, the comma is the thousands separator, and the point is the decimal separator. However, you can format the number in any language format:

package main

import (
    "fmt"

    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func main() {
    number := 1_000_000.23456

    langs := []language.Tag{
        language.German,
        language.Ukrainian,
        language.Chinese,
        language.Arabic,
        language.French,
    }

    for _, l := range langs {
        p := message.NewPrinter(l)
        withCommaThousandSep := p.Sprintf("%s %f", l, number)
        fmt.Println(withCommaThousandSep)
    }
}

Output:

de 1.000.000,234560
uk 1 000 000,234560
zh 1,000,000.234560
ar ١٬٠٠٠٬٠٠٠٫٢٣٤٥٦٠
fr 1 000 000,234560

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

📰 String padding in Go

Learn how to print aligned strings padded with spaces
introduction strings format

🐾 How to compare strings in Go

shorts introduction strings

🔁 Repeat a string in Go

shorts strings