How to fmt.Printf an integer with thousands comma

后端 未结 13 1866
独厮守ぢ
独厮守ぢ 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:08

    Here's a simple function using regex:

    import (
        "regexp"
    )
    
    func formatCommas(num int) string {
        str := fmt.Sprintf("%d", num)
        re := regexp.MustCompile("(\\d+)(\\d{3})")
        for n := ""; n != str; {
            n = str
            str = re.ReplaceAllString(str, "$1,$2")
        }
        return str
    }
    

    Example:

    fmt.Println(formatCommas(1000))
    fmt.Println(formatCommas(-1000000000))
    

    Output:

    1,000
    -1,000,000,000
    

    https://play.golang.org/p/vnsAV23nUXv

提交回复
热议问题