How to fmt.Printf an integer with thousands comma

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

    If you don't want to use a library (for whatever reason), I knocked this up. It seems to work and can use any specified rune as a delimiter:

    import (
        "strconv"
    )
    
    func delimitNumeral(i int, delim rune) string {
    
        src := strconv.Itoa(i)
        strLen := utf8.RuneCountInString(src)
        outStr := ""
        digitCount := 0
        for i := strLen - 1; i >= 0; i-- {
    
            outStr = src[i:i+1] + outStr
            if digitCount == 2 {
                outStr = string(delim) + outStr
                digitCount = 0
            } else {
                digitCount++
            }
        }
    
        return outStr
    }
    

    Note: after further testing, this function doesn't work perfectly. I would suggest using the solution posted by @IvanTung, and welcome any edits from anyone who can get mine to work perfectly.

    0 讨论(0)
提交回复
热议问题