Go course

Constants and FormattingBuilding Strings with fmt.Sprintf

Go

Display

Theme

Constants and Formatting · Test exercise

Building Strings with fmt.Sprintf

fmt.Printf prints straight to the screen. Often, though, you'd rather keep the formatted result in a string — say, to send it as a notification, save it to a database, or return it from a function. That's what fmt.Sprintf is for (S = string):

pesan := fmt.Sprintf("Pesanan #%d dikirim ke %s", 17, "Medan")
fmt.Println(pesan)
// Pesanan #17 dikirim ke Medan

That builds the string "Pesanan #17 dikirim ke Medan" ("Order #17 shipped to Medan").

The verbs are exactly the same as in Printf. The only difference: Sprintf returns a string and prints nothing.

The fmt functions follow the same naming pattern:

FunctionWhat it does
Printprints values as they are
Printlnprints with spaces between values + a newline
Printfprints with a format
Sprint, Sprintln, Sprintfsame, but return a string

Task

A chat app needs two helper functions. Complete both with fmt.Sprintf:

  1. pesanSambutan(nama string, pesanBaru int) string (a welcome message)

    • pesanSambutan("Budi", 3) → Halo, Budi! Kamu punya 3 pesan baru.

    ("Hi, Budi! You have 3 new messages.")

  2. formatSaldo(saldo float64) string — the digital wallet balance is always shown with two decimal places.

    • formatSaldo(12500.5) → Saldo dompet: Rp12500.50
    • formatSaldo(0) → Saldo dompet: Rp0.00

    ("Wallet balance: Rp…")

Watch the punctuation and spaces — the tests compare the strings exactly.

main.go
package main

import "fmt"

func pesanSambutan(nama string, pesanBaru int) string {
	// TODO: gunakan fmt.Sprintf
	return ""
}

func formatSaldo(saldo float64) string {
	// TODO: gunakan fmt.Sprintf dengan dua angka desimal
	return ""
}

func main() {
	fmt.Println(pesanSambutan("Budi", 3))
	fmt.Println(formatSaldo(12500.5))
}

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)