Format Like a Pro

Format Like a Pro

Formatting Power

So far you've used fmt.Println to print values separated by spaces. But what if you want control over how things look? Go has three formatting functions:

Function What it does
fmt.Printf Prints a formatted string to the screen
fmt.Sprintf Returns a formatted string (does not print)
fmt.Fprintf Writes a formatted string to a file or connection

They all use the same format verbs. The difference is where the result goes.

example.go
fmt.Printf("Server %s: %d requests\n", "api-1", 1523)
// prints: Server api-1: 1523 requests

msg := fmt.Sprintf("Server %s: %d requests", "api-1", 1523)
// returns: "Server api-1: 1523 requests"

Notice Printf needs \n at the end for a newline. Println adds one automatically, but the format functions don't.

Format Verbs

Verb Type Example
%s string fmt.Sprintf("hi %s", "Go")"hi Go"
%d integer fmt.Sprintf("%d errors", 3)"3 errors"
%.2f float (2 decimals) fmt.Sprintf("$%.2f", 9.9)"$9.90"
%v any value fmt.Sprintf("%v", true)"true"

The number after the dot in %.2f controls decimal places. %.1f shows one, %.3f shows three.

Sprintf is the one you'll use most. Whenever a function needs to return formatted text, this is how you do it.

>_Exercise

Exercise: Format Download

Fill in formatDownload so it returns a formatted download status line.

The format is: "backup.zip (3.50 MB) downloaded in 12s"

  • The size always shows exactly 2 decimal places, so 0.8 renders as 0.80 and 125.0 renders as 125.00
  • Put a single space between the number and MB: 3.50 MB, not 3.50MB
  • Use fmt.Sprintf to build the string

Examples:

  • formatDownload("backup.zip", 3.5, 12) returns "backup.zip (3.50 MB) downloaded in 12s"
  • formatDownload("photo.png", 0.8, 1) returns "photo.png (0.80 MB) downloaded in 1s"
  • formatDownload("video.mp4", 125.0, 45) returns "video.mp4 (125.00 MB) downloaded in 45s"
Stuck? Reveal a hint to help you.
Hints (0/4)
Key Takeaway