Group Integer Digits With Commas
Insert a comma every three digits by walking the formatted bytes, so reports read 1,234,567 without pulling in any formatting library.
Code
package main
import (
"fmt"
"strconv"
"strings"
)
// groupDigits 从左往右每三位插一个逗号:负号提前挂,0 原样返回
func groupDigits(n int64) string {
sign := ""
if n < 0 {
sign = "-"
n = -n
}
digits := strconv.FormatInt(n, 10)
var b strings.Builder
b.WriteString(sign)
for i, d := range digits {
if i > 0 && (len(digits)-i)%3 == 0 {
b.WriteByte(',')
}
b.WriteByte(d)
}
return b.String()
}
func main() {
for _, n := range []int64{0, 999, 1000, 1234567, -9876543, 25000000} {
fmt.Printf("%d -> %s\n", n, groupDigits(n))
}
}What runs when
Structurally, expect the functions groupDigits and main and nothing else.
for i, d := range digits is where the per-item work happens.
Caveats
- Standard-library through and through — paste it in and run.
Putting it to use
Entry signature: func groupDigits(n int64) string
The demo flow inside main is groupDigits — run the file to see it end to end.
Core lines
for _, n := range []int64{0, 999, 1000, 1234567, -9876543, 25000000} {
fmt.Printf("%d -> %s\n", n, groupDigits(n))
}
for i, d := range digits {
if i > 0 && (len(digits)-i)%3 == 0 {
b.WriteByte(',')
}
b.WriteByte(d)
}
return b.String()
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run Group Integer Digits With Commas?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.