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):
-
nomorTiket(n int) string— the ticket code starts withTKT-and the number is always 5 digits with leading zeros.nomorTiket(42)→TKT-00042nomorTiket(12345)→TKT-12345
-
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