How to fmt.Printf an integer with thousands comma

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

    Here is a function that takes an integer and grouping separator and returns a string delimited with the specified separator. I have tried to optimize for efficiency, no string concatenation or mod/division in the tight loop. From my profiling it is more than twice as fast as the humanize.Commas implementation (~680ns vs 1642ns) on my Mac. I am new to Go, would love to see faster implementations!

    Usage: s := NumberToString(n int, sep rune)

    Examples

    Illustrates using different separator (',' vs ' '), verified with int value range.

    s:= NumberToString(12345678, ',')

    => "12,345,678"

    s:= NumberToString(12345678, ' ')

    => "12 345 678"

    s: = NumberToString(-9223372036854775807, ',')

    => "-9,223,372,036,854,775,807"

    Function Implementation

    func NumberToString(n int, sep rune) string {
    
        s := strconv.Itoa(n)
    
        startOffset := 0
        var buff bytes.Buffer
    
        if n < 0 {
            startOffset = 1
            buff.WriteByte('-')
        }
    
    
        l := len(s)
    
        commaIndex := 3 - ((l - startOffset) % 3) 
    
        if (commaIndex == 3) {
            commaIndex = 0
        }
    
        for i := startOffset; i < l; i++ {
    
            if (commaIndex == 3) {
                buff.WriteRune(sep)
                commaIndex = 0
            }
            commaIndex++
    
            buff.WriteByte(s[i])
        }
    
        return buff.String()
    }
    

提交回复
热议问题