Start learning free

LESSON 164 OF 415 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in Swift

Practice

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

You start with:

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

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 print(result).

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

Use string interpolation, for example "Total: $\(total)", to embed a number in text.

Swift's Int / Int truncates, so afterDiscount * taxRate / 100 already rounds down.

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

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

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V2 in Swift

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