How to fmt.Printf an integer with thousands comma

后端 未结 13 1904
独厮守ぢ
独厮守ぢ 2020-12-04 21:21

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

fmt.Printf(\"%d\", 1000) outputs 1000, what format

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 22:03

    The package humanize can do the magic! Refer the documentation of this package here. To use this package, install it first by using a tool like Git SCM. If you are using Git Bash, open the shell window and type:

    go get -u github.com/dustin/go-humanize
    

    Once this is done, you can use the following solution code (Say, main.go):

    package main
    
    import (
        "fmt"
        "github.com/dustin/go-humanize"
    )
    
    func main() {
        fmt.Println(humanize.Commaf(float64(123456789)));
        fmt.Println(humanize.Commaf(float64(-1000000000)));
        fmt.Println(humanize.Commaf(float64(-100000.005)));
        fmt.Println(humanize.Commaf(float64(100000.000)));
    }
    

    There are other variations to Commaf like BigComma, Comma, BigCommaf etc. which depends on the data type of your input.

    So, on running this program using the command:

    go run main.go
    

    You will see an output such as this:

    123,456,789
    -1,000,000,000
    -100,000.005
    100,000
    

提交回复
热议问题