Start learning free

LESSON 191 OF 292 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 in Swift: Discount and Tax with Integer Math

Practice Read the full explanation

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

    SWIFT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V2 in Swift, explained

    Problem overview

    Version 2 of the shopping cart adds a flat discount and a sales tax to a single-item purchase, using only integers. The starter code defines item, price (12), quantity (3), taxRate (8, meaning 8%) and discount (5, a flat amount). The program prints a four-line receipt:

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

    The rules fix the order of the arithmetic:

    • subtotal = price * quantity;
    • afterDiscount = subtotal - discount: the discount comes off first;
    • tax = afterDiscount * taxRate / 100: tax is charged on the discounted amount, with integer division rounding it down;
    • total = afterDiscount + tax.

    The previous version printed a two-line receipt for the same item. This one adds the discount and the tax.

    Approach: calculate everything, then format

    Each number depends on the one before it, so the four values are computed in a chain: subtotal, then the amount after the discount, then tax, then total. Only after all four exist does the program build the four text rows and join them.

    The order of the operations decides the answer. Charging tax on the subtotal instead of the discounted amount gives a different number. For the starter data, the rule's tax is 2, from 31 * 8 / 100 = 2.48 cut down to 2.

    The tax calculation multiplies first and divides second. A percentage is "times the rate, divided by 100", and doing the multiplication first keeps as much precision as integers allow. Integer division then drops the fraction, which rounds the tax down, as the rules ask.

    The values for the starter data

    NameExpressionValue
    subtotal12 * 336
    afterDiscount36 - 531
    tax31 * 8 / 1002
    total31 + 233

    The receipt shows the discount and the tax as separate rows, but the total reuses afterDiscount, which already holds the subtracted amount, so nothing is subtracted twice. Naming each intermediate value means every formula in the program is one short expression.

    Using whole numbers throughout is a deliberate choice. The program works in whole dollars, and a Double can't store most decimal fractions exactly, so a receipt computed with Double would need rounding rules of its own. With Int the rule is built in: every division drops the fraction. The cost is that amounts below one dollar of tax vanish, which the edge cases below show.

    Step by step

    1. Create subtotal as price * quantity, the cost before any discount or tax.
    2. Create afterDiscount as subtotal - discount.
    3. Create tax as afterDiscount * taxRate / 100.
    4. Create total as afterDiscount + tax, which is what the customer pays.
    5. Create line1 for the Subtotal row: the label Subtotal: $ and the number, using interpolation.
    6. Create line2 for the Discount row in the same way.
    7. Create line3 for the Tax row.
    8. Create line4 for the Total row.
    9. Create result: the four rows in order, with a newline between each two. Four rows need three newlines.
    10. Print result.

    The solution in Swift

            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)
    

    The Swift details worth knowing:

    • Integer division truncates toward zero. Both operands of afterDiscount * taxRate / 100 are Int, so the result is an Int with the fraction dropped. That is rounding down for positive amounts. For negative ones, truncating toward zero rounds up, since -4 * 8 / 100 is 0, not -1.
    • No automatic mixing of types. Swift doesn't convert between Int and Double on its own. Staying with Int from start to finish keeps the code simple and the results whole.
    • Interpolation and $. "Tax: $\(tax)" contains a plain dollar sign followed by an interpolated value.
    • Joining with +. The expression line1 + "\n" + line2 + "\n" + line3 + "\n" + line4 chains string concatenations, all of them String + String, which is why it compiles without conversions.
    • Unused starter value. item is defined but not printed in this version's receipt.

    Edge cases and common mistakes

    • Tax rounds down. With discount = 0, the tax is 36 * 8 / 100 = 2, and the total is 38. The fractional part of 2.88 is cut off, not rounded to 3.
    • Small amounts give zero tax. For a subtotal of 10 with no discount, the tax is 10 * 8 / 100, which is 0, so the total stays 10.
    • A discount larger than the subtotal. With discount = 40, the amount after the discount is -4. The tax is 0, and the receipt shows Total: $-4. The lesson's rules don't clamp the value at zero.
    • A zero tax rate or zero discount. Both are ordinary values: with taxRate = 0 the tax row shows $0, and the total equals the amount after the discount. No special case is needed.
    • Taxing the wrong amount. The tax uses afterDiscount, not subtotal.
    • Dividing first. afterDiscount / 100 * taxRate truncates the amount before multiplying and loses most of the tax: for 31 it gives 0 instead of 2.
    • Missing newlines. Four rows need three "\n" separators. Forgetting one runs two rows together.

    Testing

    • The starter data prints Subtotal: $36, Discount: $5, Tax: $2 and Total: $33.
    • With discount = 0, it prints Subtotal: $36, Discount: $0, Tax: $2 and Total: $38.
    • With discount = 40, it prints Subtotal: $36, Discount: $40, Tax: $0 and Total: $-4.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free