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.
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.
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 .
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.
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 }
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With