Start learning free

LESSON 163 OF 404 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in Go

Practice

Add a discount and sales tax to a single-item purchase using integer math.

You start with:

item := "Coffee Mug"
price := 12
quantity := 3
taxRate := 8
discount := 5
_ = item

Build:

Subtotal: $36
Discount: $5
Tax: $2
Total: $33

Rules:

  • subtotal := price * quantity.
  • afterDiscount := subtotal - discount (the discount is a flat amount taken off before tax).
  • tax = afterDiscount * taxRate / 100 (integer division, so the result is rounded down). The tax is charged on the discounted amount.
  • total := afterDiscount + tax.
  • Build four lines (Subtotal, Discount, Tax, Total) and join them with a newline "\n" into one string result, then print it with fmt.Println(result).

Compute the four numbers (subtotal, afterDiscount, tax, total) before formatting.

Use strconv.Itoa(...) to convert each number to text before concatenating it.

Go's int / int truncates, so afterDiscount * taxRate / 100 already rounds down.

item := "Coffee Mug"
price := 12
quantity := 3
taxRate := 8
discount := 5
_ = item

subtotal := price * quantity
afterDiscount := subtotal - discount
tax := afterDiscount * taxRate / 100
total := afterDiscount + tax
line1 := "Subtotal: $" + strconv.Itoa(subtotal)
line2 := "Discount: $" + strconv.Itoa(discount)
line3 := "Tax: $" + strconv.Itoa(tax)
line4 := "Total: $" + strconv.Itoa(total)
result := line1 + "\n" + line2 + "\n" + line3 + "\n" + line4
fmt.Println(result)

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V2 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free