Formatting Output with fmt.Printf
fmt.Println is handy, but you can't control how its output looks. That's what fmt.Printf is for: it takes a format string containing verbs (each starting with %), followed by the values to slot in:
nama := "Doni"
umur := 21
fmt.Printf("%s berumur %d tahun\n", nama, umur)
// Doni berumur 21 tahun
That prints "Doni berumur 21 tahun" ("Doni is 21 years old").
Printfdoesn't add a newline automatically. Add\nyourself at the end of the format string.
The verbs you'll use most
| Verb | Meaning | Example | Result |
|---|---|---|---|
%v | value in its default format (anything) | Printf("%v", true) | true |
%d | integer (decimal) | Printf("%d", 42) | 42 |
%s | string | Printf("%s", "Go") | Go |
%q | string in quotes | Printf("%q", "Go") | "Go" |
%f | floating-point number (6 decimals by default) | Printf("%f", 2.5) | 2.500000 |
%.2f | floating-point number with 2 decimals | Printf("%.2f", 2.5) | 2.50 |
%T | the type of the value | Printf("%T", 2.5) | float64 |
%% | a literal percent sign | Printf("100%%") | 100% |
%.2f also rounds: fmt.Printf("%.1f", 3.46) prints 3.5.
Task
A coffee shop cashier wants to print a tidy receipt. Replace every fmt.Println in the editor with fmt.Printf so the output is exactly:
Pelanggan: "Rina"
Menu: Kopi Susu
Jumlah: 2
Harga satuan: 18500.00
Total: 37000.00
Member: true
Tipe total: float64
(The labels mean customer, menu item, quantity, unit price, total, member, and type of total.)
Hint: the customer name uses %q, the menu item %s, the quantity %d, the price and total %.2f, member %v, and the last line %T. Use the variables that are already there — don't type the numbers in directly.