Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fmt.Printf an integer with thousands comma

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.

like image 301
BrandonAGr Avatar asked Oct 22 '12 21:10

BrandonAGr


People also ask

What verb should we use with FMT printf to print integer?

Printf, Sprintf, and Fprintf all take a format string that specifies how to format the subsequent arguments. For example, %d (we call that a 'verb') says to print the corresponding argument, which must be an integer (or something containing an integer, such as a slice of ints) in decimal.

What is FMT printf?

Faraz Karim. The fmt. Printf function in the GO programming language is a function used to print out a formatted string to the console. fmt. Printf supports custom format specifiers and uses a format string to generate the final output string .

How do you add a comma to a thousand in Python?

In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left.


2 Answers

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 } 
like image 146
dolmen Avatar answered Oct 10 '22 06:10

dolmen


I wrote a library for this as well as a few other human-representation concerns.

Example results:

0 -> 0 100 -> 100 1000 -> 1,000 1000000000 -> 1,000,000,000 -100000 -> -100,000 

Example Usage:

fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) 
like image 20
Dustin Avatar answered Oct 10 '22 04:10

Dustin