Start learning free

LESSON 162 OF 413 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in C#

Practice

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

You start with:

        string item = "Coffee Mug";
        int price = 12;
        int quantity = 3;
        int tax_rate = 8;
        int discount = 5;

Build:

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

Rules:

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

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

In C# "Total: $" + total converts the number to text for you.

C#'s int / int truncates, so after_discount * tax_rate / 100 already rounds down.

        string item = "Coffee Mug";
        int price = 12;
        int quantity = 3;
        int tax_rate = 8;
        int discount = 5;

        int subtotal = price * quantity;
        int after_discount = subtotal - discount;
        int tax = after_discount * tax_rate / 100;
        int total = after_discount + tax;
        string line1 = "Subtotal: $" + subtotal;
        string line2 = "Discount: $" + discount;
        string line3 = "Tax: $" + tax;
        string line4 = "Total: $" + total;
        string result = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4;
        Console.WriteLine(result);

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V2 in C#

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