Start learning free

LESSON 166 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V2 - Tax and Discount in Rust

Practice

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

You start with: an empty editor (no starter code). Declare this data yourself:

let item = "Coffee Mug";
let price = 12;
let quantity = 3;
let tax_rate = 8;
let 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 println!("{}", result).

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

Use format!("Total: ${}", total) to build each line from a number.

Rust's i32 / i32 truncates, so after_discount * tax_rate / 100 already rounds down.

        let item = "Coffee Mug";
        let price = 12;
        let quantity = 3;
        let tax_rate = 8;
        let discount = 5;
        let subtotal = price * quantity;
        let after_discount = subtotal - discount;
        let tax = after_discount * tax_rate / 100;
        let total = after_discount + tax;
        let line1 = format!("Subtotal: ${}", subtotal);
        let line2 = format!("Discount: ${}", discount);
        let line3 = format!("Tax: ${}", tax);
        let line4 = format!("Total: ${}", total);
        let result = format!("{}\n{}\n{}\n{}", line1, line2, line3, line4);
        println!("{}", result);

STEP 1 OF 15
    Ctrl + Enter to check

    Shopping Cart V2 in Rust

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