How to fmt.Printf an integer with thousands comma

2019-01-17 19:24发布

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

fmt.Printf("%d", 1000) outputs 1000, what format can I specify to output 1,000 instead?

The docs don't seem to mention commas, and I couldn't immediately see anything in the source.

11条回答
来,给爷笑一个
2楼-- · 2019-01-17 19:41

I wrote a library for this as well as a few other human-representation concerns.

Example results:

0 -> 0
100 -> 100
1000 -> 1,000
1000000000 -> 1,000,000,000
-100000 -> -100,000

Example Usage:

fmt.Printf("You owe $%s.\n", humanize.Comma(6582491))
查看更多
Fickle 薄情
3楼-- · 2019-01-17 19:41

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.

查看更多
Viruses.
4楼-- · 2019-01-17 19:43

Use golang.org/x/text/message to print using localized formatting for any language in the Unicode CLDR:

package main

import (
    "golang.org/x/text/language"
    "golang.org/x/text/message"
)

func main() {
    p := message.NewPrinter(language.English)
    p.Printf("%d\n", 1000)

    // Output:
    // 1,000
}
查看更多
forever°为你锁心
5楼-- · 2019-01-17 19:46

I published a Go snippet over at Github of a function to render a number (float64 or int) according to user-specified thousand separator, decimal separator and decimal precision.

https://gist.github.com/gorhill/5285193

Usage: s := RenderFloat(format, n)

The format parameter tells how to render the number n.

Examples of format strings, given n = 12345.6789:

"#,###.##" => "12,345.67"
"#,###." => "12,345"
"#,###" => "12345,678"
"#\u202F###,##" => "12 345,67"
"#.###,###### => 12.345,678900
"" (aka default format) => 12,345.67
查看更多
叼着烟拽天下
6楼-- · 2019-01-17 19:46

Here's a simple function using regex:

import (
    "strconv"
    "regexp"
)

func formatCommas(num int) string {
    str := strconv.Itoa(num)
    re := regexp.MustCompile("(\\d+)(\\d{3})")
    for i := 0; i < (len(str) - 1) / 3; i++ {
        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/0v6wOzxJ1H

查看更多
女痞
7楼-- · 2019-01-17 19:46
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]
}
查看更多
登录 后发表回答