Add a discount and sales tax to a single-item purchase using integer math.
You start with:
const item: string = "Coffee Mug";
const price: number = 12;
const quantity: number = 3;
const tax_rate: number = 8;
const discount: number = 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 withMath.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 stringresult, then print it withconsole.log(result).
Compute the four numbers (
subtotal, after_discount, tax, total) before formatting.
In TypeScript
"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: string = "Coffee Mug";
const price: number = 12;
const quantity: number = 3;
const tax_rate: number = 8;
const discount: number = 5;
const subtotal: number = price * quantity;
const after_discount: number = subtotal - discount;
const tax: number = Math.floor(after_discount * tax_rate / 100);
const total: number = after_discount + tax;
const line1: string = "Subtotal: $" + subtotal;
const line2: string = "Discount: $" + discount;
const line3: string = "Tax: $" + tax;
const line4: string = "Total: $" + total;
const result: string = line1 + "\n" + line2 + "\n" + line3 + "\n" + line4;
console.log(result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
