Go course

Constants and FormattingColumn Width and Padding

Go

Display

Theme

Constants and Formatting · Test exercise

Column Width and Padding

When you print a table or a code number, you often need text with a fixed width. A number between the % and the verb letter sets the minimum width:

fmt.Printf("[%6d]\n", 42)    // [    42]  rata kanan, lebar 6
fmt.Printf("[%-6d]\n", 42)   // [42    ]  tanda - membuat rata kiri
fmt.Printf("[%06d]\n", 42)   // [000042]  diisi angka nol di depan
fmt.Printf("[%8s]\n", "Go")  // [      Go]
fmt.Printf("[%-8s]\n", "Go") // [Go      ]

By default the value is right-aligned within the width; a - flag left-aligns it, and a leading 0 pads it with zeros.

You can combine width and precision for floating-point numbers. %8.2f means "8 characters wide in total, 2 digits after the decimal point":

fmt.Printf("[%8.2f]\n", 3.14159) // [    3.14]

If the value is longer than the width you asked for, Go doesn't cut it off — the width is only a minimum.

A simple table example:

fmt.Printf("%-10s|%6d\n", "Kopi", 18000)
fmt.Printf("%-10s|%6d\n", "Roti Bakar", 15000)
// Kopi      | 18000
// Roti Bakar| 15000

Task

A movie theater ticket counter needs two functions (use fmt.Sprintf):

  1. nomorTiket(n int) string — the ticket code starts with TKT- and the number is always 5 digits with leading zeros.

    • nomorTiket(42) → TKT-00042
    • nomorTiket(12345) → TKT-12345
  2. barisJadwal(film string, studio int, harga float64) string — a single row of the showtime table:

    • the movie title left-aligned with a width of 12,
    • then |, the studio number right-aligned with a width of 3,
    • then |, the price right-aligned with a width of 10 and 2 decimal places.

    Example: barisJadwal("Laskar", 2, 45000) →

    Laskar      |  2|  45000.00
main.go
package main

import "fmt"

func nomorTiket(n int) string {
	// TODO: TKT- diikuti nomor 5 digit dengan nol di depan
	return fmt.Sprintf("TKT-%d", n)
}

func barisJadwal(film string, studio int, harga float64) string {
	// TODO: atur lebar setiap kolom
	return fmt.Sprintf("%s|%d|%.2f", film, studio, harga)
}

func main() {
	fmt.Println(nomorTiket(42))
	fmt.Println(barisJadwal("Laskar", 2, 45000))
	fmt.Println(barisJadwal("Kapal Layar", 11, 52500.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)