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.

GoCli Tooling

Code

gosnippet
32 lines
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

FAQ

How do you run Group Integer Digits With Commas?
Direct execution is enough; the script has no external requirements.