How to fmt.Printf an integer with thousands comma

BrandonAGr picture BrandonAGr · Oct 22, 2012 · Viewed 31.7k times · Source

Does Go's fmt.Printf support outputting a number with the thousands comma?

fmt.Printf("%d", 1000) outputs 1000, what format can I specify to output 1,000 instead?

The docs don't seem to mention commas, and I couldn't immediately see anything in the source.

Answer

dolmen picture dolmen · Oct 18, 2017

Use golang.org/x/text/message to print using localized formatting for any language in the Unicode CLDR:

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
}