How to Format a Currency with Commas in Golang
Created
Modified
Using localized formatting
Use golang.org/x/text/message to print using localized formatting for any language in the Unicode CLDR.
Make a main.go file containing the following:
package main
import (
"golang.org/x/text/language"
"golang.org/x/text/message"
)
func main() {
p := message.NewPrinter(language.English)
p.Printf("%v\n", 1000)
p.Printf("%v\n", 1000.02)
}
$ go run main.go 1,000 1,000.02
A classic example of recursion
The argument to comma is a string. If its length is less than or equal to 3, no comma is neces- sary. Otherwise, comma calls itself recursively with a substring consisting of all but the last three characters, and appends a comma and the last three characters to the result of the recur- sive call.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(comma("-100"))
fmt.Println(comma("1000"))
fmt.Println(comma("1000.02"))
fmt.Println(comma(".020"))
}
// comma inserts commas in a non-negative decimal integer string.
func comma(s string) string {
neg := ""
if s[0:1] == "-" {
neg = "-"
s = s[1:]
}
end := strings.Index(s, ".")
point := ""
if end >= 0 {
point = s[end:]
s = s[0:end]
}
n := len(s)
if n <= 3 {
return neg + s + point
}
return neg + comma(s[:n-3]) + "," + s[n-3:] + point
}
$ go run main.go -100 1,000 1,000.02 .020