Fmt Width Padding And Alignment

Control column width, zero padding, and left alignment with printf verbs so tabular CLI output and fixed-width logs line up without manual spacing.

GoCli Tooling

Code

gosnippet
31 lines
package main

import "fmt"

func main() {
	// %9.3f:总宽 9、小数 3 位,右对齐(默认)
	fmt.Printf("[%9.3f]\n", 3.14159)
	fmt.Printf("[%9.3f]\n", 1234.5)

	// %-8s:左对齐(负号),不足右侧补空格
	fmt.Printf("[%-8s]\n", "go")
	fmt.Printf("[%8s]\n", "go")

	// %05d:宽度 5,空位补零——工单号、时间戳的定宽输出
	fmt.Printf("[%05d]\n", 42)

	// % + d:强制显示正负号,便于对齐差异列
	fmt.Printf("[% +d] [% +d]\n", 12, -12)

	// 组合:左对齐名称 + 右对齐金额,组成两列报表
	rows := []struct {
		name  string
		cents int
	}{
		{"widget", 199_00},
		{"gadget-xl", 4_999_00},
	}
	for _, r := range rows {
		fmt.Printf("%-12s %9.2f\n", r.name, float64(r.cents)/100)
	}
}

What the code does

All of the logic lives in the function main.

Iteration happens inside for _, r := range rows — everything outside it runs once.

Iteration is driven by for _, r := range rows.

Statements that decide the outcome

for _, r := range rows {
fmt.Printf("%-12s %9.2f\n", r.name, float64(r.cents)/100)
}

Interactive Tools for This Topic

FAQ

How do you run Fmt Width Padding And Alignment?
Just run the file; everything it needs ships with the runtime itself.