Introduction
Output formatting helps you show information clearly and nicely when your program runs.
Output formatting helps you show information clearly and nicely when your program runs.
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.
fmt.Printf("Hello, %s!\n", "world")
fmt.Printf("You have %d apples.\n", 5)
fmt.Printf("Price: $%.2f\n", 3.456)
fmt.Printf("%-10s %5d\n", "Item", 42)
This program shows how to print strings, integers, and floats with formatting. It also shows alignment in columns.
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) }
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.
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.
%d format specifier do in fmt.Printf in Go?%d specifier is used to print decimal integers in Go's fmt.Printf.%d prints integers, it matches integer values, not floats, strings, or booleans.%d = integer [OK]name using fmt.Printf in Go?fmt.Printf is %s.fmt.Printf("%s", name), which correctly prints the string variable name.%s prints strings [OK]package main
import "fmt"
func main() {
x := 7
y := 3.14
fmt.Printf("x = %d, y = %.1f\n", x, y)
}%d prints integer x as 7. %.1f prints floating-point y rounded to 1 decimal place.package main
import "fmt"
func main() {
name := "Alice"
age := 30
fmt.Printf("Name: %s, Age: %f\n", name, age)
}name is a string, printed with %s correctly. age is an integer but printed with %f, which expects a float.%f for an integer causes a runtime error or incorrect output.fmt.Printf. Which format string correctly aligns the name left in 10 spaces and price right in 6 spaces with 2 decimals?
fmt.Printf("...", name, price)%-10s means left-align string in 10 spaces; %6.2f means right-align float in 6 spaces with 2 decimals."%-10s %6.2f\n" fits.Pass the test and this pattern moves unknown