×

go · level 2 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Formatting verbs decide exactly how each value looks.

%v shows any value in a sensible way. When you want more control, Go has other verbs: %d for whole numbers, %s for strings, %t for true or false, and %q for a string inside double quotes.

%f shows a float64, and the sets the decimal places: %.2f turns 3.5 into 3.50, perfect for money. It rounds to the nearest, so 2.999 becomes 3.00.

A pads a value with spaces to line up a table. %5d pushes a number to the right of five spaces, and %-8s puts a string on the left of eight. The same verbs work in Sprintf and Errorf too.

package main
import "fmt"
func main() {
	fmt.Printf("%-8s|%5s\n", "Snack", "Price")
	fmt.Printf("%-8s|%5.2f\n", "crisps", 0.85)
	fmt.Printf("%-8s|%5.2f\n", "cake", 2.5)
	fmt.Printf("%d items, paid: %t, code %q\n", 2, true, "SUMMER")
}

To show a real percent sign, write two of them, as in fmt.Printf("%d%%", 50).