How to fmt.Printf an integer with thousands comma

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

    import ("fmt"; "strings")
    
    func commas(s string) string {
        if len(s) <= 3 {
            return s
        } else {
            return commas(s[0:len(s)-3]) + "," + s[len(s)-3:]
        }
    }
    
    func toString(f float64) string {
        parts := strings.Split(fmt.Sprintf("%.2f", f), ".")
        if parts[0][0] == '-' {
            return "-" + commas(parts[0][1:]) + "." + parts[1]
        }
        return commas(parts[0]) + "." + parts[1]
    }
    

提交回复
热议问题