Formatting Output with Printf

The fmt package has three print functions. You know Println. Here are all three together:

package main

import "fmt"

func main() {
	fmt.Print("Hello")
	fmt.Print("World\n")
	fmt.Println("Hello", "World")
	fmt.Printf("%s scored %d\n", "Alice", 92)
}

Output:

HelloWorld
Hello World
Alice scored 92
  • fmt.Print prints its values and nothing more: no space between strings, and no new line at the end.
  • fmt.Println puts a space between the values and a new line at the end.
  • fmt.Printf prints a format string, a template with gaps in it.

\n inside a string means "new line". Print and Printf never add one, so you write \n yourself.

Format verbs

In a format string, each % with a letter is a verb. Printf replaces each verb with the next value after the string, from left to right. In the last line above, %s became Alice and %d became 92.

VerbPrints
%dan integer
%sa string
%fa float64, with 6 decimal places
%.2fa float64, with 2 decimal places
%vany value, the same way Println shows it
%Tthe type of the value
%qa string in double quotes
%%a % sign
price := 8.5
fmt.Printf("%f %.2f\n", price, price)
fmt.Printf("%v %v %v\n", "Alice", 92, price)
fmt.Printf("%T %T %T\n", "Alice", 92, price)
fmt.Printf("%q %d%%\n", "Alice", 50)

Output:

8.500000 8.50
Alice 92 8.5
string int float64
"Alice" 50%

%.2f is the usual choice for prices and averages. %T helps when you are not sure what type Go gave a variable. %q shows exactly where a string starts and ends, which helps when it is empty or has spaces at the ends.

%.2f also solves a problem from the Basic Types lesson, where Println showed a big number in short form:

total := 1500000.0
fmt.Println(total)
fmt.Printf("%.2f\n", total)

Output:

1.5e+06
1500000.00

Formatting only changes the printed text. total still holds the same number.

Widths

A number between % and the letter sets a width: the value takes at least that many characters. By default the value lines up on the right. A - lines the value up on the left. This is how you print neat columns:

fmt.Printf("%-8s|%5d|\n", "Apples", 3)
fmt.Printf("%-8s|%5d|\n", "Kiwis", 120)

Output:

Apples  |    3|
Kiwis   |  120|

When verbs and values do not match

If a verb does not fit its value, or a value is missing, Go does not stop. It prints a marker in the output instead:

fmt.Printf("%d\n", "Alice")
fmt.Printf("%d and %d\n", 5)

Output:

%!d(string=Alice)
5 and %!d(MISSING)

When you see %! in your output, count the verbs and the values, and check that each verb fits its type.

Sprintf

fmt.Sprintf works like Printf, but it does not print. It gives back the text as a string, which you can store and use later:

label := fmt.Sprintf("ID-%03d", 7)
fmt.Println(label)

Output:

ID-007

%03d means a width of 3, filled with zeros in front.

In the exercise, write the format string for a receipt line, with the total shown to two decimal places.