โ†“Skip to main content
  1. Tutorials/

๐Ÿ“’ Print a number with (comma) thousands separator in Go

ยท1 min

Please consider supporting us by disabling your ad blocker ๐Ÿ™

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
โ†‘