0
0
Goprogramming~5 mins

Output formatting basics in Go

Choose your learning style9 modes available
Introduction

Output formatting helps you show information clearly and nicely when your program runs.

You want to print a message with numbers aligned.
You need to show a date or time in a specific style.
You want to display a list of items in columns.
You want to control how many decimal places a number shows.
Syntax
Go
fmt.Printf("format string", values...)

Use fmt.Printf to print formatted output.

The format string uses special codes like %d for integers, %s for strings, and %f for floats.

Examples
Prints a string inside a message.
Go
fmt.Printf("Hello, %s!\n", "world")
Prints an integer number.
Go
fmt.Printf("You have %d apples.\n", 5)
Prints a float with 2 decimal places.
Go
fmt.Printf("Price: $%.2f\n", 3.456)
Prints a left-aligned string and right-aligned number in columns.
Go
fmt.Printf("%-10s %5d\n", "Item", 42)
Sample Program

This program shows how to print strings, integers, and floats with formatting. It also shows alignment in columns.

Go
package main

import "fmt"

func main() {
    name := "Alice"
    age := 30
    score := 95.6789

    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d years\n", age)
    fmt.Printf("Score: %.1f%%\n", score)
    fmt.Printf("%-10s | %5d | %8.2f\n", "Test", 7, 123.456)
}
OutputSuccess
Important Notes

Always end your format string with \n to move to the next line.

Use %% to print a percent sign.

Try different format codes to see how output changes.

Summary

Use fmt.Printf with format codes to control output.

Format codes like %s, %d, and %f help print different data types.

You can align text and numbers for neat columns.