Go course

Constants and FormattingFormatting Output with fmt.Printf

Go

Display

Theme

Constants and Formatting · Output exercise

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").

Printf doesn't add a newline automatically. Add \n yourself at the end of the format string.

The verbs you'll use most

VerbMeaningExampleResult
%vvalue in its default format (anything)Printf("%v", true)true
%dinteger (decimal)Printf("%d", 42)42
%sstringPrintf("%s", "Go")Go
%qstring in quotesPrintf("%q", "Go")"Go"
%ffloating-point number (6 decimals by default)Printf("%f", 2.5)2.500000
%.2ffloating-point number with 2 decimalsPrintf("%.2f", 2.5)2.50
%Tthe type of the valuePrintf("%T", 2.5)float64
%%a literal percent signPrintf("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.

main.go
package main

import "fmt"

func main() {
	nama := "Rina"
	menu := "Kopi Susu"
	jumlah := 2
	harga := 18500.0
	total := harga * float64(jumlah)
	member := true

	// TODO: ganti setiap Println dengan Printf sesuai format di tugas
	fmt.Println("Pelanggan:", nama)
	fmt.Println("Menu:", menu)
	fmt.Println("Jumlah:", jumlah)
	fmt.Println("Harga satuan:", harga)
	fmt.Println("Total:", total)
	fmt.Println("Member:", member)
	fmt.Println("Tipe total:", total)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)