CodeBlanks Logo Icon CodeBlanks

Printing the cart

Format and print the cart with fmt.Printf.

Printing the cart

To print the cart as a readable table, Printf width and precision fields are used:

for _, u := range s.Urunler {
    fmt.Printf("%-8s %3d x %6.2f = %7.2f\n", u.Ad, u.Adet, u.Fiyat, u.AraToplam())
}
fmt.Printf("%-8s %22.2f\n", "TOPLAM", s.Toplam())

%-8s left-aligns the name in 8 characters and %6.2f writes the number in 6 characters with 2 decimals.

The cart as a Stringer

If a String() string method is added to the cart, fmt.Println(s) prints the cart in its own format. To build the text piece by piece, strings.Builder and fmt.Fprintf are used together:

func (s Sepet) String() string {
    var b strings.Builder
    for _, u := range s.Urunler {
        fmt.Fprintf(&b, "%s x%d\n", u.Ad, u.Adet)
    }
    return b.String()
}

Practice Cart receipt

With Urun (and AraToplam), print two products in the format fmt.Printf("%-8s %2d x %5.2f = %6.2f\n", ...): Kalem 12.5 × 2 and Defter 20 × 1.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Urun struct {
    Ad    string
    Fiyat float64
    Adet  int
}

func (u Urun) AraToplam() float64 { return u.Fiyat * float64(u.Adet) }

func main() {
    for _, u := range []Urun{{"Kalem", 12.5, 2}, {"Defter", 20, 1}} {
        fmt.Printf("%-8s %2d x %5.2f = %6.2f\n", u.Ad, u.Adet, u.Fiyat, u.AraToplam())
    }
}

Expected output

Kalem     2 x 12.50 =  25.00
Defter    1 x 20.00 =  20.00

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the output of <code>fmt.Printf("%6.2f", 7.5)</code>?

  • "000007.50"
  • " 7.50" Correct answer
  • "7.50"
  • "7.5 "

Explanation: Width 6 with two decimals: "7.50" is 4 characters, so 2 spaces are added in front.

2 Left-align

Question
fmt.Printf("____|
", "Kalem")  // "Kalem   |"
Answer
fmt.Printf("%-8s|
", "Kalem")  // "Kalem   |"

Explanation: %-8s left-aligns text in an 8-character field.

3 Format and effect

Term Meaning
%-8s Left-aligned text
%3d 3-wide number
%6.2f 2 decimals, width 6
String() Println format

All lessons in Beginner