Start learning free

LESSON 159 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in JavaScript

Practice

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

You start with:

const item = "Coffee Mug";
const price = 12;
const quantity = 3;
const tax_rate = 8;
const 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 = Math.floor(after_discount * tax_rate / 100) (rounded down with Math.floor). 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.log(result).

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

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

Use Math.floor for the whole-number tax: Math.floor(after_discount * tax_rate / 100).

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

const subtotal = price * quantity;
const after_discount = subtotal - discount;
const tax = Math.floor(after_discount * tax_rate / 100);
const total = after_discount + tax;
const line1 = "Subtotal: $" + subtotal;
const line2 = "Discount: $" + discount;
const line3 = "Tax: $" + tax;
const line4 = "Total: $" + total;
const result = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4;
console.log(result);

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V2 in JavaScript

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