go · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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).
guess first
Money and padding. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
price := 4.0 / 3
fmt.Printf("£%.2f\n", price)
fmt.Printf("[%4d]\n", 7)
}
your turn
Your turn. Print a tidy receipt.
Type two prices in pounds with a decimal point, such as 1.50, then name the two things you bought. The verbs line the prices up for you.
output
press run to see what happens
fix it
The cake price comes out garbled. Fix it!
output
press run to see what happens
- The output shows %!d(float64=2.5). Go is telling you the verb does not fit the value.
%dis for whole numbers, butpriceis afloat64with decimals.- Change %d to %.2f on line 5, then run.
nailed it
your output lines up perfectly. :D
%d,%s,%tand%qshow numbers, strings, bools and quoted text.%.2fshows exactly two decimal places.- A width like
%-8sor%5dlines up a table.
new words in your collection
- verb
- precision
- width
This lesson isn’t saved. A free account remembers every lesson you finish.